"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { useEffect } from "react";
import { captureAttribution, identifyHubSpot, readAttribution } from "@/lib/attribution";
import { isFormPath, ORIGIN_PARAM, readFormCta } from "@/lib/cta";
import { isValidEmail } from "@/lib/email";
import { reportLeadConversion } from "@/lib/google-ads";
import { isValidPhone, sanitizePhoneInput } from "@/lib/phone";
import { isFreeEmail } from "@/lib/work-email";

const ERR_ICON =
  '<svg class="an-ico" width="14" height="14" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="9"/><path d="M12 7.5v5.5M12 16.5h.01"/></svg>';

type TrackFn = (event: string, props?: Record<string, string | boolean>) => void;

/** FormRuntime's effect runs before SiteEffects sets anTrack on a direct load, so look it up on each call. */
function getTrack(): TrackFn {
  return (event, props = {}) => {
    const w = window as Window & { anTrack?: TrackFn; dataLayer?: unknown[] };
    if (w.anTrack) return w.anTrack(event, props);
    w.dataLayer = w.dataLayer || [];
    w.dataLayer.push({ event, ...props, page: window.location.pathname });
  };
}

export default function FormRuntime() {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  useEffect(() => {
    const params = new URLSearchParams(searchParams.toString());
    const track = getTrack();
    const cleanups: Array<() => void> = [];

    document.querySelectorAll<HTMLFormElement>("form[data-form]").forEach((form) => {
      const kind = form.getAttribute("data-form") || "";
      const wrap = form.closest<HTMLElement>("[data-form-wrap]");
      const root = wrap?.parentElement;
      if (!wrap || !root) return;
      const summary = root.querySelector<HTMLElement>("[data-error-summary]");
      const list = root.querySelector<HTMLElement>("[data-error-list]");
      const svcErr = root.querySelector<HTMLElement>("[data-service-error]");
      const dupMsg = root.querySelector<HTMLElement>("[data-duplicate]");
      const success = root.querySelector<HTMLElement>("[data-success]");
      const submit = form.querySelector<HTMLButtonElement>("[data-submit]");
      if (!summary || !list || !svcErr || !success || !submit) return;

      wrap.hidden = false;
      success.hidden = true;
      svcErr.hidden = true;
      if (dupMsg) dupMsg.hidden = true;
      form.noValidate = true; // the browser checks required fields until this runs
      form.setAttribute("data-hs-do-not-collect", "true");

      let started = false;
      track(`${kind}_form_view`, { location: kind });

      const onFocusIn = () => {
        if (started) return;
        started = true;
        track(`${kind}_form_start`, { location: kind });
      };
      form.addEventListener("focusin", onFocusIn);

      const pwToggles: Array<{ btn: HTMLButtonElement; input: HTMLInputElement; onPw: () => void; onType: () => void }> = [];
      form.querySelectorAll<HTMLButtonElement>("[data-pw-toggle]").forEach((pwBtn) => {
        const input = (pwBtn.closest(".an-pw")?.querySelector("input")
          ?? pwBtn.previousElementSibling) as HTMLInputElement | null;
        if (!input) return;
        // Visibility is our own flag. Some browsers reset type="password" on the
        // next keystroke after Show, which would hide characters without clicking Hide.
        let visible = pwBtn.getAttribute("aria-pressed") === "true";
        const apply = () => {
          const start = input.selectionStart;
          const end = input.selectionEnd;
          input.type = visible ? "text" : "password";
          pwBtn.textContent = visible ? "Hide" : "Show";
          pwBtn.setAttribute("aria-pressed", String(visible));
          pwBtn.setAttribute("aria-label", visible ? "Hide password" : "Show password");
          if (start != null && end != null) {
            try { input.setSelectionRange(start, end); } catch { /* password type may reject this */ }
          }
        };
        const onPw = () => { visible = !visible; apply(); };
        const hold = () => { if (visible && input.type !== "text") apply(); };
        const onType = () => {
          hold();
          requestAnimationFrame(hold);
        };
        apply();
        pwBtn.addEventListener("click", onPw);
        input.addEventListener("input", onType);
        input.addEventListener("keyup", onType);
        pwToggles.push({ btn: pwBtn, input, onPw, onType });
      });

      const fieldOf = (el: Element) => el.closest(".an-field");

      const validate = (el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
        const v = el instanceof HTMLInputElement && el.type === "checkbox" ? el.checked : (el.value || "").trim();
        if (el.required && !v) return el.getAttribute("data-msg-required") || "This field is required";
        if (!v) return "";
        if (el instanceof HTMLInputElement && el.type === "email") {
          if (!isValidEmail(String(v))) return "Enter an email address like name@company.com";
          if (el.hasAttribute("data-work-email") && isFreeEmail(String(v))) {
            return "Use your work email so we can verify your business";
          }
        }
        if (el.hasAttribute("data-url") && !/^(https?:\/\/)?([a-z0-9-]+\.)+[a-z]{2,}(\/.*)?$/i.test(String(v))) {
          return "Enter a website like example.com";
        }
        if (
          el instanceof HTMLInputElement &&
          (el.type === "tel" || el.name === "phone" || el.hasAttribute("data-phone")) &&
          !isValidPhone(String(v))
        ) {
          return el.getAttribute("data-msg-invalid") || "Enter a valid phone number, including the country code if you’re outside the US.";
        }
        const minLength = "minLength" in el ? el.minLength : 0;
        if (minLength > 0 && String(v).length < minLength) {
          return el.getAttribute("data-msg-short") || `Use at least ${minLength} characters`;
        }
        return "";
      };

      const setError = (el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, msg: string) => {
        const f = fieldOf(el);
        if (!f) return;
        const id = `${el.id || el.name}-error`;
        f.querySelector(".an-field__error")?.remove();
        f.classList.toggle("is-invalid", !!msg);
        f.classList.toggle(
          "is-valid",
          !msg && !(el instanceof HTMLInputElement && el.type === "checkbox") && !!(el.value || "").trim(),
        );
        const described = (el.getAttribute("aria-describedby") || "").split(" ").filter((x) => x && x !== id);
        if (msg) {
          const p = document.createElement("p");
          p.className = "an-field__error";
          p.id = id;
          p.innerHTML = `${ERR_ICON}<span></span>`;
          p.querySelector("span")!.textContent = msg;
          const hint = f.querySelector(".an-field__hint");
          const anchor =
            hint ||
            (el instanceof HTMLInputElement && el.type === "checkbox"
              ? el.closest(".an-consent")
              : el.closest(".an-pw") || el);
          if (anchor) {
            anchor.insertAdjacentElement(
              el instanceof HTMLInputElement && el.type === "checkbox" ? "afterend" : hint ? "beforebegin" : "afterend",
              p,
            );
          }
          el.setAttribute("aria-invalid", "true");
          described.unshift(id);
        } else {
          el.removeAttribute("aria-invalid");
        }
        if (described.length) el.setAttribute("aria-describedby", described.join(" "));
        else el.removeAttribute("aria-describedby");
      };

      const inputs = Array.from(
        form.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>(
          "input:not([type=hidden]):not([type=radio]), select, textarea",
        ),
      );

      const onBlur = (el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
        const f = fieldOf(el);
        if (el instanceof HTMLInputElement && el.type === "checkbox") return;
        if (el.value || f?.classList.contains("is-invalid")) setError(el, validate(el));
      };
      const isPhoneField = (el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) =>
        el instanceof HTMLInputElement &&
        (el.type === "tel" || el.name === "phone" || el.hasAttribute("data-phone"));

      const onInput = (el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
        if (isPhoneField(el)) {
          const next = sanitizePhoneInput(el.value);
          if (next !== el.value) el.value = next;
        }
        const f = fieldOf(el);
        if (f?.classList.contains("is-invalid")) setError(el, validate(el));
      };
      const onChange = (el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement) => {
        if ((el instanceof HTMLInputElement && el.type === "checkbox") || el.tagName === "SELECT") {
          setError(el, validate(el));
        }
      };

      const blurHandlers = new Map<Element, EventListener>();
      const inputHandlers = new Map<Element, EventListener>();
      const changeHandlers = new Map<Element, EventListener>();
      inputs.forEach((el) => {
        const b: EventListener = () => onBlur(el);
        const i: EventListener = () => onInput(el);
        const c: EventListener = () => onChange(el);
        el.addEventListener("blur", b);
        el.addEventListener("input", i);
        el.addEventListener("change", c);
        blurHandlers.set(el, b);
        inputHandlers.set(el, i);
        changeHandlers.set(el, c);
      });

      const showSummary = (errors: { el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; msg: string }[]) => {
        list.innerHTML = "";
        errors.forEach((e) => {
          const li = document.createElement("li");
          const a = document.createElement("a");
          a.href = `#${e.el.id}`;
          a.textContent = e.msg;
          a.addEventListener("click", (ev) => {
            ev.preventDefault();
            e.el.focus();
          });
          li.appendChild(a);
          list.appendChild(li);
        });
        const count = root.querySelector("[data-error-count]");
        if (count) count.textContent = errors.length === 1 ? "this" : `these ${errors.length} items`;
        summary.hidden = false;
        summary.scrollIntoView({ block: "center", behavior: "smooth" });
        summary.focus({ preventScroll: true });
      };

      // React owns this label and changes it with ?rep=, so only restore it after a real send, and edit the
      // existing text node: replacing it would leave React updating a detached node.
      let label = "";
      const setSubmitText = (text: string) => {
        const node = submit.firstChild;
        if (node?.nodeType === Node.TEXT_NODE) node.nodeValue = text;
        else submit.textContent = text;
      };
      const setLoading = (on: boolean) => {
        const wasLoading = submit.classList.contains("is-loading");
        if (on && !wasLoading) label = submit.textContent || "";
        submit.classList.toggle("is-loading", on);
        submit.disabled = on;
        form.setAttribute("aria-busy", String(on));
        if (on) setSubmitText("Sending…");
        else if (wasLoading) setSubmitText(label);
      };

      // Multi-step forms (Sign up): each step validates before the next one opens.
      const steps = Array.from(form.querySelectorAll<HTMLElement>("[data-step]"));
      const goStep = (n: string) => {
        steps.forEach((s) => { s.hidden = s.getAttribute("data-step") !== n; });
        form.querySelectorAll<HTMLElement>("[data-step-dot]").forEach((d) => {
          d.classList.toggle("is-on", Number(d.getAttribute("data-step-dot")) <= Number(n));
        });
      };
      const stepButtons: Array<{ btn: HTMLElement; fn: EventListener }> = [];
      form.querySelectorAll<HTMLElement>("[data-step-next]").forEach((btn) => {
        const fn: EventListener = () => {
          const step = btn.closest<HTMLElement>("[data-step]");
          const fields = inputs.filter((el) => step?.contains(el));
          const failed = fields.filter((el) => {
            const m = validate(el);
            setError(el, m);
            return !!m;
          });
          if (failed.length) {
            failed[0].focus();
            return;
          }
          goStep(btn.getAttribute("data-step-next") || "1");
          track(`${kind}_step`, { location: kind });
        };
        btn.addEventListener("click", fn);
        stepButtons.push({ btn, fn });
      });
      form.querySelectorAll<HTMLElement>("[data-step-back]").forEach((btn) => {
        const fn: EventListener = () => goStep(btn.getAttribute("data-step-back") || "1");
        btn.addEventListener("click", fn);
        stepButtons.push({ btn, fn });
      });

      const showSuccess = () => {
        const name =
          (
            form.querySelector<HTMLInputElement>("[name=first_name]") ||
            form.querySelector<HTMLInputElement>("[name=name]")
          )?.value || "";
        const email = form.querySelector<HTMLInputElement>("[name=email]")?.value || "";
        const n = success.querySelector("[data-success-name]");
        if (n && name) n.textContent = `, ${name.split(" ")[0]}`;
        const em = success.querySelector("[data-success-email]");
        if (em && email) em.textContent = email;
        wrap.hidden = true;
        svcErr.hidden = true;
        if (dupMsg) dupMsg.hidden = true;
        summary.hidden = true;
        success.hidden = false;
        success.focus({ preventScroll: true });
        // On narrow screens the intro copy pushes the panel below the fold, so the top of the page can hide it.
        const box = success.getBoundingClientRect();
        const panelTop = box.top + window.scrollY;
        const header = document.querySelector("[data-an-header]")?.getBoundingClientRect().height ?? 0;
        const top = panelTop + box.height <= window.innerHeight ? 0 : Math.max(0, panelTop - header - 16);
        const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
        window.scrollTo({ top, behavior: reduce ? "auto" : "smooth" });
      };

      const showDuplicate = () => {
        const el = wrap.querySelector<HTMLElement>("[data-duplicate]") || dupMsg;
        if (!el) return false;
        svcErr.hidden = true;
        summary.hidden = true;
        el.hidden = false;
        el.removeAttribute("hidden");
        el.focus();
        form.reset();
        inputs.forEach((field) => setError(field, ""));
        if (steps.length) goStep("1");
        return true;
      };

      const send = (): Promise<"ok" | "duplicate"> => {
        const endpoint = form.getAttribute("data-endpoint");
        const data = new FormData(form);
        captureAttribution();
        const cta = readFormCta(params.get(ORIGIN_PARAM));
        if (cta.type) data.set("cta_type", cta.type);
        if (cta.id) data.set("cta_id", cta.id);
        if (cta.page) data.set("conversion_page", cta.page);
        if (cta.origin) data.set("origin_page", cta.origin);
        // The page the form was sent from, query included (HubSpot adv_source_page, like Contextual's ctx_source_page).
        data.set("source_page", `${window.location.origin}${window.location.pathname}${window.location.search}`);
        const attr = readAttribution();
        data.set("lead_channel", attr.lead_channel);
        if (attr.first.utm_source) data.set("first_utm_source", attr.first.utm_source);
        if (attr.first.utm_medium) data.set("first_utm_medium", attr.first.utm_medium);
        if (attr.first.utm_campaign) data.set("first_utm_campaign", attr.first.utm_campaign);
        if (attr.first.utm_term) data.set("first_utm_term", attr.first.utm_term);
        if (attr.first.utm_content) data.set("first_utm_content", attr.first.utm_content);
        const gclid = attr.first.gclid || attr.last?.gclid || "";
        if (gclid) data.set("gclid", gclid);
        if (attr.last?.gclid) data.set("last_gclid", attr.last.gclid);
        const fbclid = attr.first.fbclid || attr.last?.fbclid || "";
        if (fbclid) data.set("fbclid", fbclid);
        const msclkid = attr.first.msclkid || attr.last?.msclkid || "";
        if (msclkid) data.set("msclkid", msclkid);
        const liFatId = attr.first.li_fat_id || attr.last?.li_fat_id || "";
        if (liFatId) data.set("li_fat_id", liFatId);
        const ttclid = attr.first.ttclid || attr.last?.ttclid || "";
        if (ttclid) data.set("ttclid", ttclid);
        if (attr.first.fbclid) data.set("first_fbclid", attr.first.fbclid);
        if (attr.first.msclkid) data.set("first_msclkid", attr.first.msclkid);
        if (attr.first.li_fat_id) data.set("first_li_fat_id", attr.first.li_fat_id);
        if (attr.first.ttclid) data.set("first_ttclid", attr.first.ttclid);
        if (attr.first.landing_page) data.set("first_landing_page", attr.first.landing_page);
        if (attr.first.referrer) data.set("first_referrer", attr.first.referrer);
        if (attr.last?.utm_source) data.set("last_utm_source", attr.last.utm_source);
        if (attr.last?.utm_medium) data.set("last_utm_medium", attr.last.utm_medium);
        if (attr.last?.utm_campaign) data.set("last_utm_campaign", attr.last.utm_campaign);
        if (attr.last?.utm_term) data.set("last_utm_term", attr.last.utm_term);
        if (attr.last?.utm_content) data.set("last_utm_content", attr.last.utm_content);
        if (!endpoint) {
          return new Promise((res, rej) => {
            setTimeout(() => {
              const sim = params.get("simulate");
              if (sim === "duplicate") res("duplicate");
              else if (sim === "error") rej(new Error("simulated"));
              else res("ok");
            }, 1200);
          });
        }
        return fetch(endpoint, { method: "POST", body: data, headers: { Accept: "application/json" } }).then(async (r) => {
          const body = (await r.json().catch(() => null)) as { error?: string; duplicate?: boolean } | null;
          if (r.status === 409 || body?.duplicate) return "duplicate" as const;
          if (!r.ok) throw new Error(body?.error || `HTTP ${r.status}`);
          return "ok" as const;
        });
      };

      const onSubmit = (e: Event) => {
        e.preventDefault();
        svcErr.hidden = true;
        if (dupMsg) dupMsg.hidden = true;
        const errors: { el: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement; msg: string }[] = [];
        inputs.forEach((el) => {
          const m = validate(el);
          setError(el, m);
          if (m) errors.push({ el, msg: m });
        });
        track(`${kind}_submit`, { location: kind, valid: !errors.length });
        if (errors.length) {
          track(`${kind}_validation_error`, {
            location: kind,
            fields: errors.map((x) => x.el.name).join(","),
          });
          showSummary(errors);
          return;
        }
        summary.hidden = true;
        setLoading(true);
        send()
          .then((result) => {
            setLoading(false);
            if (result === "duplicate") {
              track(`${kind}_duplicate`, { location: kind });
              if (!showDuplicate()) {
                track(`${kind}_service_error`, { location: kind });
                svcErr.hidden = false;
                svcErr.focus();
              }
              return;
            }
            const redirect = form.getAttribute("data-redirect");
            if (redirect) {
              track(`${kind}_complete`, { location: kind });
              window.location.href = redirect;
              return;
            }
            const accountType = form.querySelector<HTMLInputElement>("[name=account_type]:checked")?.value || "";
            const program = form.querySelector<HTMLInputElement>("[name=program]")?.value || "";
            track(`${kind}_complete`, { location: kind, account_type: accountType, program });
            // Google Ads lead conversion (ARB-274): Send inquiry on /contact only, never the /support form.
            if (kind === "sales" && pathname === "/contact") reportLeadConversion();
            const email = (form.querySelector<HTMLInputElement>("[name=email]")?.value || "").trim();
            const firstName = (
              form.querySelector<HTMLInputElement>("[name=first_name]") ||
              form.querySelector<HTMLInputElement>("[name=name]")
            )?.value.trim() || "";
            const lastName = form.querySelector<HTMLInputElement>("[name=last_name]")?.value.trim() || "";
            // Talk to Sales stays out of HubSpot for now; its inquiries go to the team inbox only.
            if (email && kind !== "sales") {
              identifyHubSpot(email, {
                firstName: firstName.split(/\s+/)[0] || firstName,
                lastName: lastName || firstName.split(/\s+/).slice(1).join(" "),
                form: kind === "sales" ? "demo" : kind === "signup" ? "signup" : undefined,
              });
            }
            showSuccess();
          })
          .catch(() => {
            setLoading(false);
            track(`${kind}_service_error`, { location: kind });
            svcErr.hidden = false;
            svcErr.focus();
          });
      };
      form.addEventListener("submit", onSubmit);

      const onSamePageCta = (e: MouseEvent) => {
        if (success.hidden) return;
        const el = e.target instanceof Element ? e.target : (e.target as Node | null)?.parentElement;
        const a = el?.closest?.("a[href]");
        if (!a) return;
        let dest: URL;
        try {
          dest = new URL(a.getAttribute("href") || "", window.location.origin);
        } catch {
          return;
        }
        if (dest.origin !== window.location.origin) return;
        if (dest.pathname !== pathname || !isFormPath(pathname)) return;
        wrap.hidden = false;
        success.hidden = true;
        form.reset();
        inputs.forEach((field) => setError(field, ""));
      };
      document.addEventListener("click", onSamePageCta, true);

      // Design preview of each form state. Never in production, where a link could fake a success message.
      const state = process.env.NODE_ENV === "production" ? null : params.get("state");
      if (state === "errors") form.requestSubmit();
      if (state === "loading") setLoading(true);
      if (state === "success") showSuccess();
      if (state === "service-error") svcErr.hidden = false;
      if (state === "duplicate" && dupMsg) dupMsg.hidden = false;

      cleanups.push(() => {
        // Cache Components keeps visited pages alive (hidden by <Activity>) instead of unmounting them,
        // so typed values would still be there on return. Every visit to a form should start fresh.
        form.reset();
        inputs.forEach((field) => setError(field, ""));
        setLoading(false);
        if (steps.length) goStep("1");
        stepButtons.forEach(({ btn, fn }) => btn.removeEventListener("click", fn));
        summary.hidden = true;
        svcErr.hidden = true;
        if (dupMsg) dupMsg.hidden = true;
        wrap.hidden = false;
        success.hidden = true;

        form.removeEventListener("focusin", onFocusIn);
        form.removeEventListener("submit", onSubmit);
        document.removeEventListener("click", onSamePageCta, true);
        pwToggles.forEach(({ btn, input, onPw, onType }) => {
          btn.removeEventListener("click", onPw);
          input.removeEventListener("input", onType);
          input.removeEventListener("keyup", onType);
        });
        inputs.forEach((el) => {
          const b = blurHandlers.get(el);
          const i = inputHandlers.get(el);
          const c = changeHandlers.get(el);
          if (b) el.removeEventListener("blur", b);
          if (i) el.removeEventListener("input", i);
          if (c) el.removeEventListener("change", c);
        });
      });
    });

    return () => cleanups.forEach((fn) => fn());
  }, [pathname, searchParams]);

  return null;
}
