/**
 * GuestPlanPage — `/plan/:id`
 *
 * 손님(비계약 방문자)이 보는 플랜 미리보기. 본문은 UserPlanPage 와 동일하나,
 * 인터랙티브 섹션(자산 업로드/전략 조정/워크플로우)은 노출되지 않고
 * 하단에 도입 문의 CTA(PlanCTA) 가 붙습니다.
 */
import { useEffect } from 'react';
import { Link, useParams, useLocation } from 'react-router';
import { ArrowRight, ArrowLeft } from 'lucide-react';
import { AppIcon } from '@/shared/icons/AppIcon';
import { useMarketingPlan } from '../hooks/useMarketingPlan';
import { ReportNav } from '@/features/report/components/ReportNav';
import { PlanDownloadMenuButton } from '../components/PlanDownloadMenuButton';
import { PLAN_SECTIONS } from '@/shared/constants/planSections';
import PlanBody from '../components/PlanBody';

export default function GuestPlanPage() {
  const { id } = useParams<{ 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}
        leftSlot={
          <Link
            to="/clinics/view-clinic"
            className="inline-flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-primary-900 transition-colors"
          >
            <ArrowLeft size={14} />
            클리닉으로
          </Link>
        }
        rightSlot={
          <div className="flex items-center gap-2">
            <PlanDownloadMenuButton filename={`${data.clinicName}_Marketing_Plan`} plan={data} />
            <Link
              to={`/report/${id}`}
              className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full text-xs font-semibold text-slate-700 bg-white border border-slate-200 hover:border-slate-300 hover:bg-slate-50 transition-colors"
            >
              <AppIcon kind="report" size={12} />
              분석 리포트 보기
              <ArrowRight size={11} className="opacity-80" />
            </Link>
          </div>
        }
      />
      <PlanBody data={data} />
    </div>
  );
}
