import type { Metadata } from "next";
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import { ArrowRight, CheckCircle2, LockKeyhole, ShieldCheck } from "lucide-react";
import { comando, pageForRoute, publicBaseUrl, type Cta, type PageData, type SectionData } from "@/lib/comando";
import { CommerceGate, CookiePreferences, DataLayerBridge, DiagnosisResult, DiagnosisTool, DynamicLeadForm, PaymentConfirmation, ProtectedHub, TicketLevels } from "@/app/components/InteractiveBlocks";
import { ExperimentProvider, InnerExperimentHero } from "@/app/components/Experimentation";
import { toPublicTicketTiers } from "@/lib/public-ticket-tiers";
import { InnerFooter, InnerHeader } from "@/app/components/SiteChrome";

type RouteProps = {
  params: Promise<{ slug: string[] }>;
  searchParams: Promise<Record<string, string | string[] | undefined>>;
};

function routeFromSlug(slug: string[]) { return `/${slug.join("/")}`; }
function first(value: string | string[] | undefined) { return Array.isArray(value) ? value[0] : value; }

export async function generateStaticParams() {
  return comando.pages.filter((page) => page.route !== "/").map((page) => ({ slug: page.route.slice(1).split("/") }));
}

export async function generateMetadata({ params }: RouteProps): Promise<Metadata> {
  const { slug } = await params;
  const page = pageForRoute(routeFromSlug(slug));
  if (!page) return {};
  const shouldIndex = page.indexing.startsWith("index");
  return {
    title: page.seo.title,
    description: page.seo.description,
    alternates: { canonical: new URL(page.seo.canonical, publicBaseUrl()).toString() },
    robots: { index: shouldIndex, follow: shouldIndex },
    openGraph: { title: page.seo.title, description: page.seo.description, type: "website", locale: "pt_PT" },
  };
}

function safeDestination(destination: string) {
  return destination.startsWith("/") || destination.startsWith("#") ? destination : undefined;
}

function Action({ cta, secondary = false }: { cta: Cta; secondary?: boolean }) {
  const destination = safeDestination(cta.destination);
  if (!destination) return <span className={secondary ? "outline-button disabled" : "solid-button disabled"}>{cta.label}</span>;
  return <Link className={secondary ? "outline-button" : "solid-button"} href={destination}>{cta.label}<ArrowRight /></Link>;
}

function heroImage(page: PageData) {
  if (page.route.includes("empresas") || page.route.includes("parceiros") || page.category === "trust") return "/brand/lucas-comando-work.jpg";
  if (page.route.includes("imersao") || page.route.includes("masterclass") || page.route.includes("vip")) return "/brand/lucas-comando-stage.jpg";
  return "/brand/lucas-comando-hero.jpg";
}

function PageHero({ page }: { page: PageData }) {
  const hero = page.hero;
  if (!hero) return null;
  return (
    <section className={`inner-hero hero-${page.category}`}>
      <DataLayerBridge route={page.route} />
      <div className="inner-hero-copy"><InnerExperimentHero hero={hero} /></div>
      <div className="inner-hero-visual"><Image src={heroImage(page)} alt="Lucas Atanazio em contexto COMANDO" fill priority sizes="(max-width: 780px) 100vw, 42vw" /><div /></div>
      <div className="inner-route-index"><b>{String(page.id).padStart(2, "0")}</b><span>{page.category}</span></div>
    </section>
  );
}

function Body({ items }: { items?: string[] }) {
  if (!items?.length) return null;
  return <div className="section-body">{items.map((item) => <p key={item}>{item}</p>)}</div>;
}

function ComponentBlock({ name, section, search }: { name: string; section: SectionData; search: Record<string, string | string[] | undefined> }) {
  if (name === "diagnosis_questions") return <DiagnosisTool config={comando.diagnosis} />;
  if (name === "diagnosis_primary_result") return <DiagnosisResult config={comando.diagnosis} focus={first(search.foco)} strength={first(search.recurso)} />;
  if (["diagnosis_strength_result", "diagnosis_exercise", "diagnosis_result_cta"].includes(name)) return null;
  if (name === "ticket_comparison") {
    const publicTiers = toPublicTicketTiers(comando.ticket_model.tiers);
    return <TicketLevels tiers={publicTiers} />;
  }
  if (name === "cookie_preference_center") return <CookiePreferences />;
  if (name === "recoverable_checkout_summary") return <CommerceGate mode="recovery" />;
  if (name === "verified_referral_offer") return <CommerceGate mode="referral" />;
  if (["selected_ticket_summary", "payment_provider_element", "payment_submit"].includes(name)) return <CommerceGate />;
  if (name === "channel_preferences") return <div className="principle-panel"><ShieldCheck /><p>Preferências de e-mail, WhatsApp e SMS são independentes, começam desligadas e podem ser alteradas sem perder comunicações estritamente operacionais.</p></div>;
  if (section.fallback_copy) return <p className="component-fallback">{section.fallback_copy}</p>;
  return null;
}

function Section({ section, index, search }: { section: SectionData; index: number; search: Record<string, string | string[] | undefined> }) {
  const form = section.form && comando.forms[section.form];
  return (
    <section className={`content-section section-tone-${index % 3}`} id={section.anchor}>
      <div className="content-number">{String(index + 1).padStart(2, "0")}</div>
      <div className="content-heading"><p>COMANDO · {String(index + 1).padStart(2, "0")}</p><h2>{section.h2}</h2></div>
      <div className="content-material">
        <Body items={section.body} />
        {section.bullets && <ul className="statement-list">{section.bullets.map((bullet) => <li key={bullet}><CheckCircle2 />{bullet}</li>)}</ul>}
        {section.steps && <div className="step-grid">{section.steps.map((step, stepIndex) => { const title = typeof step === "string" ? step : (step.title || step.label || "Movimento"); const copy = typeof step === "string" ? "" : step.copy; return <article key={`${title}-${stepIndex}`}><span>{String(stepIndex + 1).padStart(2, "0")}</span><h3>{title}</h3>{copy && <p>{copy}</p>}</article>; })}</div>}
        {section.faq && <div className="faq-list">{section.faq.map((item) => <details key={item.question}><summary>{item.question}<span>+</span></summary><p>{item.answer}</p></details>)}</div>}
        {section.component && <ComponentBlock name={section.component} section={section} search={search} />}
        {form && section.form !== "checkout" && <DynamicLeadForm name={section.form!} definition={form} consents={comando.consents} preset={section.preset} />}
        {section.form === "checkout" && <CommerceGate />}
        {section.required_acknowledgements && <ul className="ack-list">{section.required_acknowledgements.map((item) => <li key={item}><input type="checkbox" disabled /><span>{item}</span></li>)}</ul>}
        {section.cta && <Action cta={section.cta} />}
        {section.ctas && <div className="inner-actions">{section.ctas.map((cta, ctaIndex) => <Action key={cta.label} cta={cta} secondary={ctaIndex > 0} />)}</div>}
        {section.fallback_cta && <Action cta={section.fallback_cta} secondary />}
      </div>
    </section>
  );
}

function StatePage({ page, search }: { page: PageData; search: Record<string, string | string[] | undefined> }) {
  if (page.route === "/checkout/pagamento") return <section className="state-stage"><CommerceGate /></section>;
  const requested = page.route === "/obrigado" ? first(search.origem) : undefined;
  const entries = Object.entries(page.states || {});
  const state = (requested && page.states?.[requested]) || entries[0]?.[1];
  if (!state) return null;
  const heading = state.h1 || state.title || page.name;
  return <section className="state-stage"><div className="state-card"><span>{state.eyebrow || "COMANDO"}</span><h1>{heading}</h1><p>{state.copy}</p>{state.cta && <Action cta={state.cta} />}{page.support_copy && <small>{page.support_copy}</small>}</div></section>;
}

function JsonLd({ page }: { page: PageData }) {
  const graph = { "@context": "https://schema.org", "@type": "WebPage", name: page.seo.title, description: page.seo.description, url: new URL(page.route, publicBaseUrl()).toString(), inLanguage: "pt-PT" };
  return <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(graph).replace(/</g, "\\u003c") }} />;
}

export default async function DynamicPage({ params, searchParams }: RouteProps) {
  const [{ slug }, search] = await Promise.all([params, searchParams]);
  const route = routeFromSlug(slug);
  const page = pageForRoute(route);
  if (!page) notFound();
  const protectedWithoutSession = ["/confirmacao", "/participante"].includes(page.route);
  const variants = comando.ab_variants.filter((variant) => variant.route === page.route);
  const requestedVariant = first(search.variant) || first(search.v);
  return <ExperimentProvider route={page.route} variants={variants} requestedVariant={requestedVariant}><main className={`page-shell shell-${page.category}`}><JsonLd page={page} /><InnerHeader /><PageHero page={page} />
    {page.category === "trust" && <div className="legal-status"><ShieldCheck /><p><b>Documento operacional.</b> O texto final exige revisão jurídica portuguesa depois de confirmados entidade promotora, oferta, recinto e meios de pagamento.</p></div>}
    {protectedWithoutSession ? <section className="state-stage">{page.route === "/confirmacao" ? <PaymentConfirmation sessionId={first(search.session_id)} /> : page.modules ? <ProtectedHub modules={page.modules} /> : <div className="state-card"><LockKeyhole /><span>Acesso verificado</span><h1>O hub só abre com autenticação própria do participante.</h1><p>Uma referência de pagamento isolada não expõe bilhete, QR, dados pessoais ou materiais.</p><Link className="solid-button" href="/contactos-acessibilidade">Pedir apoio <ArrowRight /></Link></div>}</section> : page.sections ? page.sections.map((section, index) => <Section key={`${page.route}-${section.h2}`} section={section} index={index} search={search} />) : <StatePage page={page} search={search} />}
    <InnerFooter />
  </main></ExperimentProvider>;
}
