/**
 * PlanPage — 마케팅 기획 화면 (단일 페이지).
 *
 * 두 경로에서 동일 컴포넌트로 진입:
 *  - `/plan/:id`                       (랜딩 → 분석 → 리포트 → 플랜)
 *  - `/clinics/:clinicId/plan/:id`     (워크스페이스 진입)
 *
 * 본문(PlanBody) + 인터랙티브 섹션(MyAssetUpload / WorkflowTracker) + 도입 문의 CTA 모두 노출.
 * 업로드는 analysisRunId(=URL :id) 를 항상 넘기므로 어디서 들어와도 SDK 호출.
 */
import { useEffect } from 'react';
import { useParams, useLocation } from 'react-router';
import { useMarketingPlan } from '../hooks/useMarketingPlan';
import { ReportNav } from '@/features/report/components/ReportNav';
import { PLAN_SECTIONS } from '@/shared/constants/planSections';
import PlanBody from '../components/PlanBody';
import MyAssetUpload from '../components/MyAssetUpload';
import WorkflowTracker from '../components/WorkflowTracker';
import PlanCTA from '../components/PlanCTA';

export default function PlanPage() {
  const { id } = useParams<{ clinicId?: string; id: string }>();
  const location = useLocation();
  const { data, isLoading, error } = useMarketingPlan(id);

  // 해시 기반 스크롤: /plan/:id#section-id → 렌더링 후 해당 섹션으로
  useEffect(() => {
    if (isLoading || !location.hash) return;
    const sectionId = location.hash.slice(1);
    const timer = setTimeout(() => {
      const el = document.getElementById(sectionId);
      if (!el) return;
      const STICKY_OFFSET = 128;
      const y = el.getBoundingClientRect().top + window.scrollY - STICKY_OFFSET;
      window.scrollTo({ top: y, behavior: 'smooth' });
    }, 300);
    return () => clearTimeout(timer);
  }, [isLoading, location.hash]);

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center pt-20">
        <div className="flex flex-col items-center gap-4">
          <div className="w-10 h-10 border-4 border-[#6C5CE7] border-t-transparent rounded-full animate-spin" />
          <p className="text-slate-500 text-sm">마케팅 기획을 불러오는 중...</p>
        </div>
      </div>
    );
  }

  if (error || !data) {
    return (
      <div className="min-h-screen flex items-center justify-center pt-20">
        <div className="text-center">
          <p className="text-[#7C3A4B] font-medium mb-2">오류가 발생했습니다</p>
          <p className="text-slate-500 text-sm">{error ?? '마케팅 기획을 찾을 수 없습니다.'}</p>
        </div>
      </div>
    );
  }

  return (
    <div className="pt-20">
      <ReportNav sections={PLAN_SECTIONS} />

      <PlanBody data={data} />

      {data.workflow && (
        <div data-no-print>
          <WorkflowTracker data={data.workflow} />
        </div>
      )}

      <div data-no-print>
        <MyAssetUpload analysisRunId={id} />
      </div>

      <PlanCTA plan={data} />
    </div>
  );
}
