"use client";

// 템플릿 반응 미리보기 페이지
// ============================================================================
// 빌더(ScreenDesigner)에서 "반응 미리보기" 버튼으로 새 창으로 열림.
// URL: /admin/template-preview?id=<templateId>
// 템플릿을 서버에서 로드 → Full/Half/Quarter 토글 안에서 TemplateRenderer 로 렌더.
// ============================================================================

import { Suspense, useEffect, useState } from "react";
import { useSearchParams } from "next/navigation";
import { getTemplateInfo } from "@/lib/api/template";
import type { Template } from "@/types/invyone-component";
import { TemplateResponsivePreview } from "@/components/dash/TemplateResponsivePreview";

function PreviewInner() {
  const searchParams = useSearchParams();
  const templateId = searchParams?.get("id") ?? "";
  const [template, setTemplate] = useState<Template | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (!templateId) {
      setError("템플릿 ID가 없습니다");
      setLoading(false);
      return;
    }
    let cancel = false;
    (async () => {
      try {
        const data = await getTemplateInfo(templateId);
        if (cancel) return;
        if (!data) {
          setError("템플릿을 찾을 수 없습니다");
        } else {
          setTemplate(data as unknown as Template);
        }
      } catch (e: any) {
        if (!cancel) setError(e?.message ?? "로드 실패");
      } finally {
        if (!cancel) setLoading(false);
      }
    })();
    return () => {
      cancel = true;
    };
  }, [templateId]);

  if (loading) {
    return (
      <div className="flex h-screen w-full items-center justify-center text-sm text-muted-foreground">
        템플릿 로드 중...
      </div>
    );
  }
  if (error || !template) {
    return (
      <div className="flex h-screen w-full items-center justify-center text-sm text-destructive">
        {error ?? "템플릿이 비어있습니다"}
      </div>
    );
  }

  return (
    <div className="h-screen w-full bg-background">
      <TemplateResponsivePreview template={template} />
    </div>
  );
}

export default function TemplatePreviewPage() {
  return (
    <Suspense fallback={null}>
      <PreviewInner />
    </Suspense>
  );
}
