"use client";

import { usePathname } from "next/navigation";
import { useEffect } from "react";
import { captureAttribution } from "@/lib/attribution";
import { channels } from "@/lib/channels";
import { storeCtaFromClick } from "@/lib/cta";

type TrackFn = (event: string, props?: Record<string, string | boolean>) => void;
type TrackWindow = Window & { dataLayer?: Record<string, unknown>[]; anTrack?: TrackFn };

const all = <T extends Element = HTMLElement>(s: string, c: ParentNode = document) => Array.from(c.querySelectorAll<T>(s));

/** Visited pages stay in the DOM, so ids can repeat: look inside the widget first. */
const byId = (scope: ParentNode, id: string | null) =>
  id ? scope.querySelector<HTMLElement>(`[id="${id}"]`) ?? document.getElementById(id) : null;

type PlanRow = { icon: string; name: string; pct: number };
type Plan = { rows: PlanRow[]; budget: string; kpiLabel: string; kpi: string };

/** Every tracked event goes to window.dataLayer. */
const track: TrackFn = (name, data = {}) => {
  const w = window as TrackWindow;
  w.dataLayer = w.dataLayer || [];
  w.dataLayer.push({ event: name, ...data, page: window.location.pathname });
};

let rotatorCount = 0;

/**
 * Pages can share a mock-up, and visited pages stay in the DOM, so the same radio name and ids can exist
 * twice. Radios with one name form one group, so each rotator gets its own name and ids.
 */
function scopeRotator(box: HTMLElement, inputs: HTMLInputElement[]) {
  if (box.dataset.amkScoped) return;
  rotatorCount += 1;
  const suffix = `-r${rotatorCount}`;
  box.dataset.amkScoped = String(rotatorCount);
  const labels = all<HTMLLabelElement>("label[for]", box);
  inputs.forEach((input) => {
    const oldId = input.id;
    input.name += suffix;
    input.id += suffix;
    labels.filter((label) => label.htmlFor === oldId).forEach((label) => { label.htmlFor = input.id; });
  });
}

/**
 * Behaviour for the server-rendered design markup: navigation, tabs, filters, reveal and mock-up rotators.
 * Render it as the last element of every page, inside any Suspense boundary around the content. It changes
 * the DOM, so it must hydrate with the page: from the root layout it would run first and break hydration.
 * The abort signal removes every listener on leaving, so nothing is bound twice.
 */
export default function SiteEffects() {
  const pathname = usePathname();

  useEffect(() => {
    (window as TrackWindow).anTrack = track;
    captureAttribution();
    const channel = channels.find((c) => c.href === pathname)?.slug;
    if (channel) document.body.setAttribute("data-channel", channel);
    else document.body.removeAttribute("data-channel");
    const ac = new AbortController();
    const { signal } = ac;
    const timers: number[] = [];
    const observers: IntersectionObserver[] = [];
    const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    const on = <E extends Event = Event>(el: EventTarget, type: string, fn: (e: E) => void) =>
      el.addEventListener(type, fn as EventListener, { signal });

    on<MouseEvent>(document, "click", (e) => {
      const target = e.target instanceof Element ? e.target : null;
      const el = target?.closest<HTMLElement>("[data-track]");
      if (el) {
        track(el.getAttribute("data-track") || "", {
          location: el.getAttribute("data-track-location") || "",
          channel: el.getAttribute("data-track-channel") || document.body.getAttribute("data-channel") || "",
          rep: el.getAttribute("data-track-rep") || "",
          href: el.getAttribute("href") || "",
        });
      }
      const a = target?.closest<HTMLAnchorElement>("a[href]");
      if (a) {
        storeCtaFromClick(
          window.location.pathname,
          a.getAttribute("href") || "",
          a.getAttribute("data-track-location") || "",
        );
        // A link to the page you are on changes no route, so Next does nothing: go back to the top instead.
        const url = new URL(a.href, window.location.href);
        const plain = e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey && !a.target && !a.hasAttribute("download");
        if (plain && !url.hash && url.origin === window.location.origin && url.pathname === window.location.pathname && url.search === window.location.search) {
          window.scrollTo({ top: 0, behavior: reduce ? "auto" : "smooth" });
        }
        // A native #section jump adds a history entry without Next's state, and Next ignores Back onto it, leaving
        // the previous page on screen. Push it through history.pushState, which Next patches to copy its state in.
        const hash = a.getAttribute("href") || "";
        const id = hash.length > 1 && hash.startsWith("#") ? decodeURIComponent(hash.slice(1)) : "";
        // Visited pages stay in the DOM, so take the copy that is on screen.
        const section = id ? all(`[id="${CSS.escape(id)}"]`).find((el) => el.getClientRects().length > 0) : undefined;
        if (plain && section) {
          e.preventDefault();
          if (window.location.hash !== hash) window.history.pushState(null, "", hash);
          section.scrollIntoView();
          if (!section.matches("a[href], button, input, select, textarea, [tabindex]")) {
            section.setAttribute("tabindex", "-1");
            section.addEventListener("blur", () => section.removeAttribute("tabindex"), { once: true, signal });
          }
          section.focus({ preventScroll: true });
        }
      }
    });

    all("[data-year]").forEach((el) => { el.textContent = String(new Date().getFullYear()); });

    /* dropdown */
    const dds = all("[data-an-dd]");
    const toggleOf = (d: Element) => d.querySelector<HTMLElement>(".an-dd__toggle")!;
    const closeDds = (except?: Element) => dds.forEach((d) => {
      if (d !== except) { d.classList.remove("is-open"); toggleOf(d).setAttribute("aria-expanded", "false"); }
    });
    closeDds();
    dds.forEach((dd) => {
      const btn = toggleOf(dd);
      let timer = 0;
      let hoverAt = 0;
      const desktop = () => window.matchMedia("(min-width: 1100px)").matches;
      on(btn, "click", () => {
        if (desktop() && Date.now() - hoverAt < 400) return; // hover already opened it
        const open = !dd.classList.contains("is-open");
        closeDds(dd);
        dd.classList.toggle("is-open", open);
        btn.setAttribute("aria-expanded", String(open));
      });
      on(dd, "mouseenter", () => {
        if (!desktop()) return;
        clearTimeout(timer);
        if (!dd.classList.contains("is-open")) hoverAt = Date.now();
        closeDds(dd);
        dd.classList.add("is-open");
        btn.setAttribute("aria-expanded", "true");
      });
      on(dd, "mouseleave", () => {
        if (!desktop()) return;
        timer = window.setTimeout(() => { dd.classList.remove("is-open"); btn.setAttribute("aria-expanded", "false"); }, 160);
      });
      on<KeyboardEvent>(dd, "keydown", (e) => {
        if (e.key === "Escape") { dd.classList.remove("is-open"); btn.setAttribute("aria-expanded", "false"); btn.focus(); }
      });
    });
    on<MouseEvent>(document, "click", (e) => {
      const target = e.target instanceof Element ? e.target : null;
      if (!target?.closest("[data-an-dd]")) closeDds();
      else if (target.closest("a[href]")) closeDds();
    });

    /* mobile menu: a route change always closes it */
    const burger = document.querySelector<HTMLElement>("[data-an-burger]");
    const nav = document.querySelector<HTMLElement>("[data-an-nav]");
    if (burger && nav) {
      const setMenu = (open: boolean) => {
        nav.classList.toggle("is-open", open);
        burger.setAttribute("aria-expanded", String(open));
        document.body.classList.toggle("an-menu-open", open);
        const label = burger.querySelector(".an-sr");
        if (label) label.textContent = open ? "Close menu" : "Open menu";
      };
      setMenu(false);
      on(burger, "click", () => setMenu(!nav.classList.contains("is-open")));
      // A link to the current page changes no route, so close on the tap too.
      on<MouseEvent>(nav, "click", (e) => {
        if (e.target instanceof Element && e.target.closest("a[href]")) setMenu(false);
      });
      on<KeyboardEvent>(document, "keydown", (e) => {
        if (e.key === "Escape" && nav.classList.contains("is-open")) { setMenu(false); burger.focus(); }
      });
    }

    /* tabs */
    const selectTab = (root: ParentNode, tabs: HTMLElement[], tab: HTMLElement, focus?: boolean) => {
      tabs.forEach((t) => {
        const selected = t === tab;
        t.setAttribute("aria-selected", String(selected));
        t.tabIndex = selected ? 0 : -1;
        const panel = byId(root, t.getAttribute("aria-controls"));
        if (panel) panel.hidden = !selected;
      });
      if (focus) tab.focus();
    };
    all("[data-an-tabs]").forEach((root) => {
      const tabs = all('[role="tab"]', root);
      tabs.forEach((t, i) => {
        on(t, "click", () => selectTab(root, tabs, t));
        on<KeyboardEvent>(t, "keydown", (e) => {
          let n: HTMLElement | null = null;
          if (e.key === "ArrowRight") n = tabs[(i + 1) % tabs.length];
          if (e.key === "ArrowLeft") n = tabs[(i - 1 + tabs.length) % tabs.length];
          if (e.key === "Home") n = tabs[0];
          if (e.key === "End") n = tabs[tabs.length - 1];
          if (n) { e.preventDefault(); selectTab(root, tabs, n, true); }
        });
      });
    });

    /* channel explorer filter */
    const hasGoal = (el: Element, goal: string) => ` ${el.getAttribute("data-goals")} `.includes(` ${goal} `);
    all("[data-an-filter]").forEach((root) => {
      const target = byId(root.parentElement ?? document, root.getAttribute("data-an-filter"));
      if (!target) return;
      const btns = all("button", root);
      btns.forEach((b) => on(b, "click", () => {
        const goal = b.getAttribute("data-goal") || "all";
        btns.forEach((o) => o.setAttribute("aria-pressed", String(o === b)));
        all("[data-goals]", target).forEach((card) => { card.hidden = goal !== "all" && !hasGoal(card, goal); });
        all("[data-group]", target).forEach((g) => {
          const shown = all("[data-goals]:not([hidden])", g).length;
          g.hidden = shown === 0;
          const count = g.querySelector(".an-xgroup__count");
          if (count) count.textContent = `${shown} ${shown === 1 ? "channel" : "channels"}`;
        });
        const live = document.querySelector("[data-an-filter-status]");
        if (live) live.textContent = `${all("[data-goals]:not([hidden])", target).length} channels shown`;
        track("channel_filter", { goal });
      }));
    });

    /* homepage channel showcase */
    all("[data-an-showcase]").forEach((root) => {
      const tabs = all('[role="tab"]', root);
      const count = root.querySelector("[data-showcase-count]");
      const visible = () => tabs.filter((t) => !t.hidden);
      const select = (tab: HTMLElement, focus?: boolean) => {
        selectTab(root, tabs, tab, focus);
        if (window.matchMedia("(max-width: 991px)").matches) {
          tab.scrollIntoView({ block: "nearest", inline: "center", behavior: reduce ? "auto" : "smooth" });
        }
      };
      tabs.forEach((t) => {
        on(t, "click", () => { select(t); track("channel_preview", { channel: t.id.replace("sct-", "") }); });
        on<KeyboardEvent>(t, "keydown", (e) => {
          const v = visible();
          const i = v.indexOf(t);
          let n: HTMLElement | null = null;
          if (e.key === "ArrowDown" || e.key === "ArrowRight") n = v[(i + 1) % v.length];
          if (e.key === "ArrowUp" || e.key === "ArrowLeft") n = v[(i - 1 + v.length) % v.length];
          if (e.key === "Home") n = v[0];
          if (e.key === "End") n = v[v.length - 1];
          if (n) { e.preventDefault(); select(n, true); }
        });
      });
      const btns = all("[data-showcase-filter] button", root);
      btns.forEach((b) => on(b, "click", () => {
        const goal = b.getAttribute("data-goal") || "all";
        btns.forEach((o) => o.setAttribute("aria-pressed", String(o === b)));
        tabs.forEach((t) => { t.hidden = goal !== "all" && !hasGoal(t, goal); });
        all("[data-sc-group]", root).forEach((g) => {
          g.hidden = !tabs.some((t) => !t.hidden && t.getAttribute("data-group") === g.getAttribute("data-sc-group"));
        });
        const v = visible();
        if (count) count.textContent = String(v.length);
        const cur = tabs.find((t) => t.getAttribute("aria-selected") === "true");
        if (v.length && (!cur || cur.hidden)) select(v[0]);
        track("channel_filter", { goal });
      }));
    });

    /* fit the selected channel's mock-up into the panel (desktop "one screen" layout) */
    all("[data-an-showcase]").forEach((root) => {
      const mq = window.matchMedia("(min-width: 992px)");
      const fit = () => {
        const panel = root.querySelector(".an-showcase__panel:not([hidden])");
        const stage = panel?.querySelector<HTMLElement>(".an-stage");
        const vis = stage?.querySelector<HTMLElement>(":scope > :not(.an-stage__label)");
        if (!stage || !vis || !stage.clientHeight) return;
        vis.style.zoom = "1";
        vis.style.width = "";
        vis.style.margin = "";
        if (!mq.matches) return;
        let z = Math.min(1, (stage.clientHeight - 16) / vis.scrollHeight, (stage.clientWidth - 16) / vis.scrollWidth);
        for (let i = 0; i < 4; i += 1) { // re-check: some mock-ups size themselves from their width
          vis.style.zoom = String(Math.max(z, 0.35));
          const r = vis.getBoundingClientRect();
          const sr = stage.getBoundingClientRect();
          const over = Math.max(r.height / (sr.height - 16), r.width / (sr.width - 16));
          if (over <= 1.001) break;
          z /= over;
        }
        // Full-width mock-ups (e.g. the TV frame) ignore zoom: cap their width so the height follows.
        const r2 = vis.getBoundingClientRect();
        const s2 = stage.getBoundingClientRect();
        if (r2.height > s2.height - 15) {
          vis.style.zoom = "1";
          vis.style.width = `${Math.floor((s2.height - 16) * (vis.offsetWidth / vis.offsetHeight))}px`;
          vis.style.margin = "0 auto";
        }
      };
      on(root, "click", () => requestAnimationFrame(fit));
      on(root, "keyup", () => requestAnimationFrame(fit));
      on(window, "resize", fit);
      on(window, "load", fit);
      fit();
    });

    /* How It Works: planner goal tabs */
    all("[data-hiw-plan]").forEach((el) => {
      const data = JSON.parse(el.getAttribute("data-hiw-plan") || "{}") as Record<string, Plan>;
      const tabs = all(".an-ui__goal", el);
      const mix = el.querySelector(".an-ui__mix");
      const show = (k: string, focus = false) => {
        const d = data[k];
        if (!d || !mix) return;
        tabs.forEach((t) => {
          const selected = t.getAttribute("data-goal") === k;
          t.classList.toggle("is-on", selected);
          t.setAttribute("aria-selected", String(selected));
          t.tabIndex = selected ? 0 : -1;
          if (selected) {
            mix.setAttribute("aria-labelledby", t.id);
            if (focus) t.focus();
          }
        });
        const rows = all(".an-ui__mixrow", mix);
        d.rows.forEach((r, i) => {
          const row = rows[i];
          if (!row) return;
          row.querySelector(".an-ui__ico")!.innerHTML = r.icon;
          row.querySelector(".an-ui__name")!.textContent = r.name;
          const bar = row.querySelector(".an-ui__track i")!;
          bar.className = `${bar.className.replace(/\bw-p-\d+\b/, "").trim()} w-p-${Math.round(r.pct * 2.4)}`;
          row.querySelector("b")!.textContent = `${r.pct}%`;
        });
        (["budget", "kpiLabel", "kpi"] as const).forEach((f) => {
          const out = el.querySelector(`[data-f="${f}"]`);
          if (out) out.textContent = d[f];
        });
      };
      tabs.forEach((t, i) => {
        t.tabIndex = t.getAttribute("aria-selected") === "true" ? 0 : -1;
        on(t, "click", () => show(t.getAttribute("data-goal") || ""));
        on<KeyboardEvent>(t, "keydown", (e) => {
          let n: HTMLElement | null = null;
          if (e.key === "ArrowRight") n = tabs[(i + 1) % tabs.length];
          if (e.key === "ArrowLeft") n = tabs[(i - 1 + tabs.length) % tabs.length];
          if (e.key === "Home") n = tabs[0];
          if (e.key === "End") n = tabs[tabs.length - 1];
          if (n) { e.preventDefault(); show(n.getAttribute("data-goal") || "", true); }
        });
      });
    });

    /* React does not render the muted attribute on the server, so start autoplay videos here. */
    all<HTMLVideoElement>("video[autoplay]").forEach((v) => {
      v.muted = true;
      v.play().catch(() => {});
    });

    /* AI layer toggle */
    all("[data-ai-toggle]").forEach((btn) => {
      const scope = btn.closest("section") ?? document;
      const stage = byId(scope, btn.getAttribute("aria-controls"));
      const legend = scope.querySelector("[data-ai-legend]");
      on(btn, "click", () => {
        const pressed = btn.getAttribute("aria-pressed") !== "true";
        btn.setAttribute("aria-pressed", String(pressed));
        stage?.classList.toggle("an-ailayer-on", pressed);
        legend?.classList.toggle("is-on", pressed);
        if (pressed) track("ai_layer_view");
      });
    });

    /* reveal */
    const rev = all(".an-reveal");
    if ("IntersectionObserver" in window && !reduce) {
      const io = new IntersectionObserver((entries) => entries.forEach((en) => {
        if (en.isIntersecting) { en.target.classList.add("is-in"); io.unobserve(en.target); }
      }), { rootMargin: "0px 0px -8% 0px" });
      rev.forEach((el) => io.observe(el));
      observers.push(io);
    } else {
      rev.forEach((el) => el.classList.add("is-in"));
    }

    /* campaign journey auto-highlight */
    all("[data-an-flow]").forEach((flow) => {
      const nodes = all(".an-flow__node", flow);
      const detail = byId(flow.closest("section") ?? document, flow.getAttribute("data-an-flow"));
      let i = 0;
      let t = 0;
      const show = (n: number) => {
        nodes.forEach((x, k) => x.classList.toggle("is-active", k === n));
        if (detail) detail.textContent = nodes[n].getAttribute("data-detail") || "";
        i = n;
      };
      nodes.forEach((n, k) => {
        on(n, "mouseenter", () => { clearInterval(t); show(k); });
        on(n, "focus", () => { clearInterval(t); show(k); });
      });
      if (nodes.length) show(0);
      if (!reduce && nodes.length) {
        t = window.setInterval(() => show((i + 1) % nodes.length), 2600);
        timers.push(t);
      }
    });

    /* mock-up rotators: each starts on its first tab and loops */
    all("[data-amk-rotate]").forEach((box) => {
      const inputs = all<HTMLInputElement>(".amk-rot__in", box);
      if (!inputs.length) return;
      scopeRotator(box, inputs);
      inputs[0].checked = true;
      // A decorative mock-up is hidden from assistive tech, so its radios must stay out of the tab order too.
      if (box.closest("[aria-hidden='true']")) inputs.forEach((input) => { input.tabIndex = -1; });
      if (reduce || inputs.length < 2) return;
      const delay = parseInt(box.getAttribute("data-amk-rotate") || "", 10) || 5500;
      let i = 0;
      let t = 0;
      const stop = () => clearInterval(t);
      const start = () => {
        stop();
        t = window.setInterval(() => { i = (i + 1) % inputs.length; inputs[i].checked = true; }, delay);
        timers.push(t);
      };
      inputs.forEach((inp, n) => on(inp, "change", () => { i = n; start(); }));
      on(box, "mouseenter", stop);
      on(box, "mouseleave", start);
      start();
    });

    /* FAQ: one answer open at a time, sliding open and shut together */
    all(".an-faq").forEach((faq) => {
      const items = all<HTMLDetailsElement>("details", faq);
      const running = new Map<HTMLDetailsElement, Animation>();
      const collapsedHeight = (d: HTMLDetailsElement) =>
        d.querySelector("summary")!.offsetHeight + d.offsetHeight - d.clientHeight;
      const slide = (d: HTMLDetailsElement, from: number, to: number, done?: () => void) => {
        running.get(d)?.cancel();
        d.style.overflow = "hidden";
        const animation = d.animate({ height: [`${from}px`, `${to}px`] }, { duration: 260, easing: "ease" });
        running.set(d, animation);
        animation.onfinish = () => {
          running.delete(d);
          d.style.overflow = "";
          done?.();
        };
      };
      const close = (d: HTMLDetailsElement) => {
        if (reduce) { d.open = false; return; }
        d.classList.add("is-closing");
        slide(d, d.offsetHeight, collapsedHeight(d), () => {
          d.open = false;
          d.classList.remove("is-closing");
        });
      };
      const open = (d: HTMLDetailsElement) => {
        const from = d.open ? d.offsetHeight : collapsedHeight(d);
        d.classList.remove("is-closing");
        running.get(d)?.cancel();
        d.open = true;
        if (!reduce) slide(d, from, d.offsetHeight);
      };
      items.forEach((d) => on<MouseEvent>(d.querySelector("summary")!, "click", (e) => {
        e.preventDefault();
        const opening = !d.open || d.classList.contains("is-closing");
        items.forEach((o) => { if (o !== d && o.open && !o.classList.contains("is-closing")) close(o); });
        if (opening) open(d);
        else close(d);
      }));
    });

    /* blog article: copy link and current section in "On this page" */
    all("[data-copy]").forEach((b) => on(b, "click", () => {
      const done = () => {
        b.classList.add("is-copied");
        b.setAttribute("aria-label", "Link copied");
        timers.push(window.setTimeout(() => { b.classList.remove("is-copied"); b.setAttribute("aria-label", "Copy link"); }, 1800));
      };
      if (navigator.clipboard) navigator.clipboard.writeText(b.getAttribute("data-copy") || "").then(done, done);
      else done();
    }));
    const tocLinks = all(".an-article-toc a");
    if (tocLinks.length && "IntersectionObserver" in window) {
      const io = new IntersectionObserver((entries) => entries.forEach((e) => {
        if (!e.isIntersecting) return;
        tocLinks.forEach((l) => l.classList.toggle("is-on", l.getAttribute("href") === `#${e.target.id}`));
        // A long list scrolls on its own: keep the current entry visible by moving the list, never the page.
        const on = tocLinks.find((l) => l.classList.contains("is-on"));
        const list = on?.closest("ol");
        if (on && list && list.scrollHeight > list.clientHeight) {
          const top = on.offsetTop - list.offsetTop;
          if (top < list.scrollTop || top + on.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = top - list.clientHeight / 3;
        }
      }), { rootMargin: "-90px 0px -70% 0px" });
      tocLinks.forEach((a) => {
        const h = document.getElementById((a.getAttribute("href") || "").slice(1));
        if (h) io.observe(h);
      });
      observers.push(io);
    }

    return () => {
      ac.abort();
      timers.forEach((t) => clearInterval(t));
      observers.forEach((o) => o.disconnect());
    };
  }, [pathname]);

  return null;
}
