/** Server-rendered landing page blocks (PAGE-003) with pixel injection (PAGE-006) and A/B variants (PAGE-005). */
import Script from "next/script";
import { cookies } from "next/headers";
import { notFound } from "next/navigation";
import { and, eq } from "drizzle-orm";
import { getDb, schema } from "@/db";
import type { FormSchema, PageBlock, PageSchema } from "@/db/schema";
import { bumpFormStat, pickVariant } from "@/lib/services/forms";
import { PublicForm, VariantCookie } from "./public-form";

export async function loadPublished(wsSlug: string, slug: string) {
  const db = await getDb();
  const ws = await db.query.workspaces.findFirst({ where: eq(schema.workspaces.slug, wsSlug) });
  if (!ws) return null;
  const form = await db.query.forms.findFirst({ where: and(eq(schema.forms.workspaceId, ws.id), eq(schema.forms.slug, slug), eq(schema.forms.status, "published")) });
  return form ? { ws, form } : null;
}

export async function loadByDomain(host: string) {
  const db = await getDb();
  const form = await db.query.forms.findFirst({ where: and(eq(schema.forms.domain, host.toLowerCase()), eq(schema.forms.status, "published")) });
  if (!form) return null;
  const ws = await db.query.workspaces.findFirst({ where: eq(schema.workspaces.id, form.workspaceId) });
  return ws ? { ws, form } : null;
}

export function Pixels({ pixels }: { pixels: { metaPixelId?: string; ga4Id?: string; gtmId?: string } }) {
  return (
    <>
      {pixels.metaPixelId && <Script id="meta-pixel" strategy="afterInteractive">{`!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js');fbq('init','${pixels.metaPixelId.replace(/\D/g, "")}');fbq('track','PageView');`}</Script>}
      {pixels.ga4Id && <><Script src={`https://www.googletagmanager.com/gtag/js?id=${encodeURIComponent(pixels.ga4Id)}`} strategy="afterInteractive" /><Script id="ga4" strategy="afterInteractive">{`window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments)}window.gtag=gtag;gtag('js',new Date());gtag('config','${pixels.ga4Id.replace(/[^\w-]/g, "")}');`}</Script></>}
      {pixels.gtmId && <Script id="gtm" strategy="afterInteractive">{`(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','${pixels.gtmId.replace(/[^\w-]/g, "")}');`}</Script>}
    </>
  );
}

export async function RenderPublished({ data, embed }: { data: NonNullable<Awaited<ReturnType<typeof loadPublished>>>; embed?: boolean }) {
  const { ws, form } = data;
  const cc = ws.settings?.defaultCountryCode ?? (ws.currency === "AUD" ? "61" : ws.currency === "USD" ? "1" : "880");
  const db = await getDb();
  if (form.type === "form") {
    const s = form.schema as FormSchema;
    await bumpFormStat({ db }, form.id, "default", "views");
    return (
      <div className={embed ? "bg-transparent p-1" : "grid min-h-dvh place-items-center bg-[#F7F7FA] px-4 py-10"}>
        <Pixels pixels={form.pixels} />
        <div className={embed ? "" : "w-full max-w-[460px] rounded-[18px] bg-white p-7 text-black shadow-[0_20px_60px_-20px_rgb(0_0_0/.25)]"}>
          <PublicForm formId={form.id} title={s.title} description={s.description} fields={s.fields} consent={s.consent} submitLabel={s.submitLabel} successMessage={s.successMessage} countryCode={cc} captcha={s.captcha} />
        </div>
        {!embed && <script src="/t.js" data-ws={ws.slug} async />}
      </div>
    );
  }
  const page = form.schema as PageSchema;
  const variants = form.variants ?? [];
  let variant = "default";
  let blocks = page.blocks;
  if (variants.length >= 2) {
    const jar = await cookies();
    const sticky = jar.get(`tpv_${form.id}`)?.value;
    variant = sticky && variants.some((v) => v.key === sticky) ? sticky : pickVariant(variants);
    const v = variants.find((x) => x.key === variant);
    if (v?.blocks.length) blocks = page.blocks.map((b) => v.blocks.find((x) => x.id === b.id) ?? b).concat(v.blocks.filter((x) => !page.blocks.some((b) => b.id === x.id)));
  }
  await bumpFormStat({ db }, form.id, variant, "views");
  const linked = page.formId ? await db.query.forms.findFirst({ where: eq(schema.forms.id, page.formId) }) : null;
  const fs = linked?.schema as FormSchema | undefined;
  const accent = page.theme?.accent ?? "#2563EB";
  const dark = !!page.theme?.dark;
  return (
    <div className={dark ? "min-h-dvh bg-[#0b0b0d] text-white" : "min-h-dvh bg-white text-[#16161a]"} style={{ fontFamily: "var(--font-inter)" }}>
      <Pixels pixels={form.pixels} />
      {variant !== "default" && <VariantCookie formId={form.id} variant={variant} />}
      {blocks.map((b) => <Block key={b.id} b={b} accent={accent} dark={dark} form={fs && linked ? <PublicForm formId={form.id} title={String(b.props.title ?? fs.title)} fields={fs.fields} consent={fs.consent} submitLabel={fs.submitLabel} successMessage={fs.successMessage} accent={accent} variant={variant} countryCode={cc} captcha={fs.captcha} /> : <p className="opacity-60">Attach a form to this page.</p>} />)}
      <footer className="px-6 py-8 text-center text-[12px] opacity-50">© {new Date().getFullYear()} {ws.name}</footer>
      <script src="/t.js" data-ws={ws.slug} async />
    </div>
  );
}

function Block({ b, accent, dark, form }: { b: PageBlock; accent: string; dark: boolean; form: React.ReactNode }) {
  const p = b.props as Record<string, any>;
  const muted = dark ? "text-white/70" : "text-black/60";
  const wrap = "mx-auto max-w-[1080px] px-6";
  switch (b.type) {
    case "hero":
      return (
        <section className="relative overflow-hidden" style={{ background: p.image ? undefined : `linear-gradient(160deg, #0b0b0d 0%, ${accent} 140%)` }}>
          {p.image && <><img src={p.image} alt="" className="absolute inset-0 h-full w-full object-cover" /><div className="absolute inset-0 bg-gradient-to-b from-black/70 via-black/50 to-black/70" /></>}
          <div className={`${wrap} relative py-24 text-white md:py-32`}>
            {p.eyebrow && <div className="mb-3 inline-block rounded-full bg-white/15 px-3 py-1 text-[12px] font-semibold uppercase tracking-wider backdrop-blur">{p.eyebrow}</div>}
            <h1 className="max-w-[780px] text-[40px] font-bold leading-[1.05] md:text-[60px]" style={{ fontFamily: "var(--font-syne)" }}>{p.title}</h1>
            {p.subtitle && <p className="mt-4 max-w-[620px] text-[17px] text-white/80 md:text-[19px]">{p.subtitle}</p>}
            {p.cta && <a href="#form" className="mt-8 inline-block rounded-[12px] px-6 py-3.5 text-[15px] font-semibold text-white shadow-lg transition hover:brightness-110" style={{ background: accent }}>{p.cta}</a>}
          </div>
        </section>
      );
    case "features":
      return (
        <section className={`${wrap} py-16`}>
          {p.title && <h2 className="mb-8 text-[30px] font-bold" style={{ fontFamily: "var(--font-syne)" }}>{p.title}</h2>}
          <div className="grid gap-5 md:grid-cols-3">{(p.items ?? []).map((it: any, i: number) => (
            <div key={i} className={dark ? "rounded-[16px] bg-white/5 p-6" : "rounded-[16px] bg-[#F7F7FA] p-6"}><div className="mb-3 h-1.5 w-10 rounded-full" style={{ background: accent }} /><h3 className="text-[17px] font-semibold">{it.title}</h3><p className={`mt-1.5 text-[14.5px] ${muted}`}>{it.text}</p></div>
          ))}</div>
        </section>
      );
    case "form":
      return (
        <section id="form" className={dark ? "bg-white/5 py-16" : "bg-[#F7F7FA] py-16"}>
          <div className="mx-auto max-w-[520px] px-6"><div className="rounded-[20px] bg-white p-7 text-black shadow-[0_20px_60px_-20px_rgb(0_0_0/.25)]">{form}</div></div>
        </section>
      );
    case "cta":
      return (
        <section className="py-16 text-center text-white" style={{ background: accent }}>
          <h2 className="text-[30px] font-bold" style={{ fontFamily: "var(--font-syne)" }}>{p.title}</h2>
          {p.label && <a href={p.href || "#form"} className="mt-6 inline-block rounded-[12px] bg-white px-6 py-3 text-[15px] font-semibold" style={{ color: accent }}>{p.label}</a>}
        </section>
      );
    case "testimonial":
      return <section className={`${wrap} py-16 text-center`}><blockquote className="mx-auto max-w-[720px] text-[22px] font-medium leading-snug">“{p.quote}”</blockquote><p className={`mt-3 ${muted}`}>{p.author}</p></section>;
    case "faq":
      return (
        <section className={`${wrap} max-w-[760px] py-16`}>
          {p.title && <h2 className="mb-6 text-[28px] font-bold" style={{ fontFamily: "var(--font-syne)" }}>{p.title}</h2>}
          <div className="space-y-2">{(p.items ?? []).map((it: any, i: number) => <details key={i} className={dark ? "rounded-[12px] bg-white/5 p-4" : "rounded-[12px] bg-[#F7F7FA] p-4"}><summary className="cursor-pointer font-medium">{it.q}</summary><p className={`mt-2 ${muted}`}>{it.a}</p></details>)}</div>
        </section>
      );
    case "image":
      return <section className={`${wrap} py-10`}>{p.url && <img src={p.url} alt={p.caption ?? ""} className="w-full rounded-[18px]" />}{p.caption && <p className={`mt-2 text-center text-[13px] ${muted}`}>{p.caption}</p>}</section>;
    case "gallery":
      return <section className={`${wrap} grid grid-cols-2 gap-3 py-10 md:grid-cols-3`}>{(p.images ?? []).map((im: any, i: number) => <img key={i} src={im.url} alt="" className="aspect-[4/3] w-full rounded-[14px] object-cover" />)}</section>;
    default:
      return <section className={`${wrap} max-w-[760px] whitespace-pre-wrap py-12 text-[16px] leading-relaxed`}>{p.text}</section>;
  }
}

export { notFound };
