import { useState, useCallback } from 'react';

/**
 * Chrome(브라우저) 네이티브 인쇄 다이얼로그로 PDF 저장.
 *
 * 레이아웃·색상·페이지 분할은 `@media print` CSS가 담당 (`src/styles/custom.css`).
 * 호출 직전 framer-motion `whileInView` 잔여 요소(opacity:0/transform)를
 * 최종 상태로 강제하여 사용자가 보지 못한 섹션이 빈 페이지로 인쇄되는 것을 방지.
 */

function forceMotionFinalState(): () => void {
  const root =
    (document.querySelector('[data-report-content]') as HTMLElement | null) ||
    (document.querySelector('[data-plan-content]') as HTMLElement | null);
  if (!root) return () => {};

  const saved: { el: HTMLElement; opacity: string; transform: string }[] = [];

  root.querySelectorAll<HTMLElement>('*').forEach((el) => {
    const s = el.style;
    const opacityOff = s.opacity !== '' && parseFloat(s.opacity) < 1;
    const transformOn = s.transform !== '' && s.transform !== 'none';
    if (!opacityOff && !transformOn) return;

    saved.push({ el, opacity: s.opacity, transform: s.transform });
    if (opacityOff) s.opacity = '1';
    if (transformOn) s.transform = 'none';
  });

  return () => {
    saved.forEach(({ el, opacity, transform }) => {
      el.style.opacity = opacity;
      el.style.transform = transform;
    });
  };
}

export function useExportPDF() {
  const [isExporting, setIsExporting] = useState(false);

  const exportPDF = useCallback((filename = 'INFINITH_Marketing_Intelligence_Report') => {
    setIsExporting(true);

    const originalTitle = document.title;
    document.title = filename;
    const restoreMotion = forceMotionFinalState();

    const cleanup = () => {
      restoreMotion();
      document.title = originalTitle;
      setIsExporting(false);
      window.removeEventListener('afterprint', cleanup);
    };
    window.addEventListener('afterprint', cleanup);

    window.print();
  }, []);

  return { exportPDF, isExporting };
}
