"use client";
import { useEffect, useRef, useState } from "react";
import { CheckCircle2 } from "lucide-react";

type F = { key: string; label: string; type: string; required?: boolean; options?: string[] };

/** Lightweight phone check mirrored from the server (PAGE-002: invalid numbers rejected client-side). */
function phoneOk(raw: string, cc: string) {
  const d = raw.replace(/[০-৯]/g, (x) => String(x.charCodeAt(0) - 0x09e6)).replace(/[^\d+]/g, "");
  if (cc === "880") return /^(\+?880|0)?1[3-9]\d{8}$/.test(d);
  return /^\+?\d{8,15}$/.test(d);
}

declare global { interface Window { fbq?: (...a: unknown[]) => void; gtag?: (...a: unknown[]) => void; dataLayer?: unknown[]; turnstile?: { render: (el: HTMLElement, o: Record<string, unknown>) => void } } }

export function PublicForm({ formId, title, description, fields, consent, submitLabel, successMessage, accent = "#2563EB", variant, countryCode = "880", captcha, compact }: {
  formId: string; title?: string; description?: string; fields: F[]; consent?: { channel: string; label: string }[]; submitLabel: string; successMessage: string; accent?: string; variant?: string; countryCode?: string; captcha?: boolean; compact?: boolean;
}) {
  const [values, setValues] = useState<Record<string, string | boolean>>({});
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [state, setState] = useState<"idle" | "sending" | "done">("idle");
  const [msg, setMsg] = useState("");
  const started = useRef(Date.now());
  const meta = useRef<Record<string, string>>({});
  const captchaRef = useRef<HTMLDivElement>(null);
  const token = useRef("");
  const siteKey = process.env.NEXT_PUBLIC_TURNSTILE_SITE_KEY;

  useEffect(() => {
    const q = new URLSearchParams(location.search);
    let stored: Record<string, string> = {};
    try { stored = JSON.parse(localStorage.getItem("tp_attr") || "{}"); } catch { /* storage blocked */ }
    const m: Record<string, string> = { ...stored };
    for (const k of ["utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content", "fbclid", "gclid"]) { const v = q.get(k); if (v) m[k] = v; }
    m.landing_url = m.landing_url || location.href;
    const aid = document.cookie.match(/(?:^|;\s*)tp_aid=([^;]+)/)?.[1];
    if (aid) m.anonymous_id = decodeURIComponent(aid);
    const fbp = document.cookie.match(/(?:^|;\s*)_fbp=([^;]+)/)?.[1];
    if (fbp) m.fbp = fbp;
    meta.current = m;
    try { localStorage.setItem("tp_attr", JSON.stringify(m)); } catch { /* ignore */ }
    if (captcha && siteKey && captchaRef.current) {
      const s = document.createElement("script");
      s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js";
      s.async = true;
      s.onload = () => window.turnstile?.render(captchaRef.current!, { sitekey: siteKey, callback: (t: string) => { token.current = t; } });
      document.head.appendChild(s);
    }
  }, [captcha, siteKey]);

  const validate = () => {
    const e: Record<string, string> = {};
    for (const f of fields) {
      const v = values[f.key];
      const empty = v === undefined || v === "" || v === false;
      if (f.required && empty) e[f.key] = `${f.label} is required`;
      else if (!empty && f.type === "phone" && !phoneOk(String(v), countryCode)) e[f.key] = "Enter a valid mobile number";
      else if (!empty && f.type === "email" && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(v))) e[f.key] = "Enter a valid email";
    }
    setErrors(e);
    return !Object.keys(e).length;
  };

  const submit = async (ev: React.FormEvent) => {
    ev.preventDefault();
    if (!validate()) return;
    setState("sending"); setMsg("");
    const hp = (ev.target as HTMLFormElement).querySelector<HTMLInputElement>("input[name=company_website]")?.value;
    try {
      const res = await fetch(`/api/v1/forms/${formId}/submissions`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ ...values, _meta: { ...meta.current, variant, hp, started_at: started.current, captcha_token: token.current } }) });
      const j = await res.json();
      if (!res.ok) {
        if (j.error?.details && typeof j.error.details === "object") setErrors(j.error.details);
        throw new Error(j.error?.message ?? "Something went wrong");
      }
      setState("done"); setMsg(j.message ?? successMessage);
      window.fbq?.("track", "Lead");
      window.gtag?.("event", "generate_lead", { form_id: formId });
      window.dataLayer?.push({ event: "form_submit", form_id: formId });
    } catch (e) {
      setState("idle"); setMsg((e as Error).message);
    }
  };

  if (state === "done") return (
    <div className="flex flex-col items-center gap-3 py-10 text-center">
      <CheckCircle2 className="h-12 w-12" style={{ color: accent }} />
      <p className="text-[16px] font-semibold">{msg || successMessage}</p>
    </div>
  );

  const field = "w-full rounded-[10px] border border-black/10 bg-white px-3.5 py-2.5 text-[14.5px] text-black outline-none transition focus:border-black/30 focus:ring-4 focus:ring-black/5";
  return (
    <form onSubmit={submit} noValidate className="space-y-3.5">
      {title && !compact && <div><h2 className="text-[22px] font-bold leading-tight" style={{ fontFamily: "var(--font-syne)" }}>{title}</h2>{description && <p className="mt-1 text-[14px] opacity-70">{description}</p>}</div>}
      <input type="text" name="company_website" tabIndex={-1} autoComplete="off" className="absolute left-[-9999px] h-0 w-0 opacity-0" aria-hidden />
      {fields.filter((f) => f.type !== "hidden").map((f) => (
        <label key={f.key} className="block">
          {f.type !== "checkbox" && <span className="mb-1 block text-[13px] font-medium opacity-80">{f.label}{f.required && <span style={{ color: accent }}> *</span>}</span>}
          {f.type === "select" ? (
            <select className={field} value={String(values[f.key] ?? "")} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })}><option value="">Choose…</option>{(f.options ?? []).map((o) => <option key={o}>{o}</option>)}</select>
          ) : f.type === "textarea" ? (
            <textarea className={`${field} min-h-[90px]`} value={String(values[f.key] ?? "")} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} />
          ) : f.type === "checkbox" ? (
            <span className="flex items-center gap-2 text-[14px]"><input type="checkbox" className="h-4 w-4" checked={!!values[f.key]} onChange={(e) => setValues({ ...values, [f.key]: e.target.checked })} />{f.label}</span>
          ) : (
            <input className={field} type={f.type === "phone" ? "tel" : f.type === "number" ? "number" : f.type} inputMode={f.type === "phone" ? "tel" : undefined} autoComplete={f.type === "phone" ? "tel" : f.type === "email" ? "email" : f.key === "name" ? "name" : undefined} placeholder={f.type === "phone" ? (countryCode === "880" ? "01XXXXXXXXX" : "") : ""} value={String(values[f.key] ?? "")} onChange={(e) => setValues({ ...values, [f.key]: e.target.value })} onBlur={() => errors[f.key] && validate()} />
          )}
          {errors[f.key] && <span className="mt-1 block text-[12.5px] text-red-600">{errors[f.key]}</span>}
        </label>
      ))}
      {(consent ?? []).map((c) => (
        <label key={c.channel} className="flex items-start gap-2 text-[13px] opacity-80"><input type="checkbox" className="mt-0.5 h-4 w-4" checked={!!values[`consent_${c.channel}`]} onChange={(e) => setValues({ ...values, [`consent_${c.channel}`]: e.target.checked })} />{c.label}</label>
      ))}
      {captcha && siteKey && <div ref={captchaRef} />}
      {msg && <p className="rounded-[8px] bg-red-50 px-3 py-2 text-[13px] text-red-700">{msg}</p>}
      <button type="submit" disabled={state === "sending"} className="w-full rounded-[10px] px-4 py-3 text-[15px] font-semibold text-white shadow-sm transition hover:brightness-110 disabled:opacity-60" style={{ background: accent }}>{state === "sending" ? "Sending…" : submitLabel}</button>
      <p className="text-center text-[11px] opacity-50">We respect your privacy. Reply STOP to opt out of messages anytime.</p>
    </form>
  );
}

export function VariantCookie({ formId, variant }: { formId: string; variant: string }) {
  useEffect(() => { document.cookie = `tpv_${formId}=${variant};path=/;max-age=${60 * 86400};SameSite=Lax`; }, [formId, variant]);
  return null;
}
