import { createFileRoute, notFound, Link } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery } from "@tanstack/react-query";
import { getPublishedProposal } from "@/lib/proposals.functions";
import { normalizeProposal, type ProposalData } from "@/lib/proposal-schema";
import { ProposalView } from "@/components/proposal/ProposalView";
import { openEditorAccess } from "@/components/proposal/EditorAccess";

const proposalQuery = (slug: string) =>
  queryOptions({ queryKey: ["proposal", slug], queryFn: () => getPublishedProposal({ data: { slug } }) });

export const Route = createFileRoute("/propuesta/$slug")({
  loader: async ({ params, context }) => {
    const row = await context.queryClient.ensureQueryData(proposalQuery(params.slug));
    if (!row) throw notFound();
    return { clientName: row.clientName };
  },
  head: ({ loaderData }) => {
    if (!loaderData) return { meta: [{ title: "Propuesta no encontrada" }, { name: "robots", content: "noindex" }] };
    const title = `Estrategia de adquisición digital | ${loaderData.clientName} × Sinerggia`;
    const description = `Análisis interactivo de pauta digital preparado por Sinerggia Diseño para ${loaderData.clientName}.`;
    return {
      meta: [
        { title },
        { name: "description", content: description },
        { property: "og:title", content: title },
        { property: "og:description", content: description },
        { property: "og:type", content: "website" },
        { name: "twitter:card", content: "summary_large_image" },
      ],
    };
  },
  notFoundComponent: () => (
    <div className="flex min-h-screen items-center justify-center bg-paper p-6 text-center">
      <div><h1 className="font-display text-4xl">Propuesta no disponible</h1><p className="mt-3 text-muted-foreground">El enlace no existe o la propuesta aún no se publica.</p><Link to="/" className="mt-6 inline-block underline">Ir al inicio</Link></div>
    </div>
  ),
  errorComponent: ({ error }) => <div className="p-10 text-center">No se pudo cargar la propuesta: {String((error as Error)?.message ?? error)}</div>,
  component: ProposalPage,
});

function ProposalPage() {
  const { slug } = Route.useParams();
  const { data } = useSuspenseQuery(proposalQuery(slug));
  return <ProposalView data={normalizeProposal(data?.data as Partial<ProposalData>)} onLogoTripleClick={openEditorAccess} />;
}
