"use client";

import { usePathname, useRouter } from "next/navigation";
import { useEffect, useRef } from "react";
import { isHubPath } from "./SiteFrame";

/*
 * The design's behavior lives in plain scripts (public/js, copied from the design source) that bind to the
 * page DOM once on load. Next.js swaps the page DOM on client-side navigation instead of reloading, so this
 * component runs them for each page and undoes everything they registered when the visitor navigates away.
 *
 * `base` runs on every page (header, "Add to application" picks, application form); the rest are per page.
 * The signed-in Hub (/hub/*) runs only its dashboard script.
 */
const base = ["monetize"];
const byPath: Record<string, string[]> = {
  "/": ["monetize-home", "mz-ai"],
  // Pages that include the AI demo script in the design
  "/ai-search": ["monetize-pages", "mz-ai"],
  "/ai-site-search": ["monetize-pages", "mz-ai"],
  "/ai-app-monetization": ["monetize-pages", "mz-ai"],
};
const defaultPage = ["monetize-pages"];
const hub = ["dashboard"];

const sources = new Map<string, Promise<string>>();
function load(name: string) {
  if (!sources.has(name)) sources.set(name, fetch(`/js/${name}.js`).then((r) => r.text()));
  return sources.get(name)!;
}

type Cleanup = () => void;

/** Runs `fn` while recording every listener, timer, frame and observer it creates; returns a function that removes them. */
function runTracked(fn: () => void): Cleanup {
  const listeners: [EventTarget, string, EventListenerOrEventListenerObject, boolean | AddEventListenerOptions | undefined][] = [];
  const intervals: number[] = [];
  const timeouts: number[] = [];
  const frames: number[] = [];
  const observers: IntersectionObserver[] = [];

  const add = EventTarget.prototype.addEventListener;
  const setI = window.setInterval;
  const setT = window.setTimeout;
  const raf = window.requestAnimationFrame;
  const IO = window.IntersectionObserver;

  EventTarget.prototype.addEventListener = function (this: EventTarget, type, listener, options) {
    if (listener) listeners.push([this, type, listener, options]);
    return add.call(this, type, listener, options);
  };
  window.setInterval = ((...a: Parameters<typeof setInterval>) => {
    const id = setI(...a) as unknown as number;
    intervals.push(id);
    return id;
  }) as typeof setInterval;
  window.setTimeout = ((...a: Parameters<typeof setTimeout>) => {
    const id = setT(...a) as unknown as number;
    timeouts.push(id);
    return id;
  }) as typeof setTimeout;
  window.requestAnimationFrame = (cb) => {
    const id = raf(cb);
    frames.push(id);
    return id;
  };
  if (IO) {
    window.IntersectionObserver = class extends IO {
      constructor(cb: IntersectionObserverCallback, opts?: IntersectionObserverInit) {
        super(cb, opts);
        observers.push(this);
      }
    };
  }

  try {
    fn();
  } finally {
    EventTarget.prototype.addEventListener = add;
    window.setInterval = setI;
    window.setTimeout = setT;
    window.requestAnimationFrame = raf;
    if (IO) window.IntersectionObserver = IO;
  }

  return () => {
    listeners.forEach(([t, type, l, o]) => t.removeEventListener(type, l, o));
    intervals.forEach((id) => clearInterval(id));
    timeouts.forEach((id) => clearTimeout(id));
    frames.forEach((id) => cancelAnimationFrame(id));
    observers.forEach((o) => o.disconnect());
    // Put the persistent header back to its closed state
    document.body.classList.remove("nav-open");
    document.querySelectorAll(".mz-nav.is-open, [data-mz-dd].is-open").forEach((el) => el.classList.remove("is-open"));
    // Scroll-spy highlight (e.g. "Live Demos" on the home page) must not outlive the page that set it
    document.querySelectorAll(".mz-nav__link.is-active").forEach((el) => el.classList.remove("is-active"));
    document.querySelectorAll(".mz-nav [aria-expanded], .mz-burger").forEach((el) => el.setAttribute("aria-expanded", "false"));
    document.querySelector(".mz-burger")?.setAttribute("aria-label", "Open menu");
    delete (window as unknown as { MZ?: unknown }).MZ;
    // The Hub's header persists too: close its menus
    document.querySelectorAll(".db-dd__menu").forEach((el) => ((el as HTMLElement).hidden = true));
    document.querySelectorAll(".db-dd [aria-haspopup], .db-menu-toggle").forEach((el) => el.setAttribute("aria-expanded", "false"));
    document.querySelector("#db-nav")?.classList.remove("is-open");
  };
}

/**
 * Glides to a #section and keeps it there while the page settles. Safari has no scroll anchoring, so when content
 * above the section changes height after the glide starts (a stylesheet or image arriving late, a demo expanding),
 * it would leave the visitor short of or past the section. Stops once the visitor scrolls themselves.
 */
function glideTo(id: string) {
  const el = document.getElementById(id);
  if (!el) return;
  el.scrollIntoView({ behavior: "smooth", block: "start" });

  const position = () => el.getBoundingClientRect().top + window.scrollY;
  let last = position();
  let frame = 0;
  const until = performance.now() + 4000;
  const userEvents = ["wheel", "touchstart", "keydown", "pointerdown"];
  const stop = () => {
    cancelAnimationFrame(frame);
    userEvents.forEach((ev) => window.removeEventListener(ev, stop));
  };
  const watch = () => {
    if (!el.isConnected || performance.now() > until) return stop();
    const now = position();
    if (Math.abs(now - last) > 1) {
      last = now;
      el.scrollIntoView({ behavior: "smooth", block: "start" });
    }
    frame = requestAnimationFrame(watch);
  };
  userEvents.forEach((ev) => window.addEventListener(ev, stop, { passive: true }));
  frame = requestAnimationFrame(watch);
}

export default function LegacyScripts() {
  const pathname = usePathname().replace(/\/$/, "") || "/";
  const router = useRouter();

  // The design sets scroll-behavior: smooth. A plain page change would glide to the top and can stop partway,
  // so it jumps to the top instead. A link to a #section starts from the top too (like a fresh page load, and
  // so the old scroll depth doesn't trigger scroll-driven demos on the new page) and then glides to the section.
  // Back/forward keep the browser's restored position.
  const previousPath = useRef(pathname);
  const viaHistory = useRef(false);
  useEffect(() => {
    const onPop = () => {
      viaHistory.current = true;
    };
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);
  useEffect(() => {
    if (previousPath.current !== pathname && !viaHistory.current) {
      window.scrollTo({ top: 0, left: 0, behavior: "instant" });
      const id = decodeURIComponent(window.location.hash.slice(1));
      // Next may still start its own (smooth) scroll for this navigation; repeat the jump on the next frame to win
      if (!id) requestAnimationFrame(() => window.scrollTo({ top: 0, left: 0, behavior: "instant" }));
      if (id) {
        // Next is still finishing its own scroll for this navigation; start ours once that has settled
        setTimeout(() => glideTo(id), 80);
      }
    }
    previousPath.current = pathname;
    viaHistory.current = false;
  }, [pathname]);

  // Every #section link on the same page glides there and keeps the section in place while lazy content above it
  // settles (CTA QA BUG-16, BUG-17: "Explore AI & search" and "Integration & support" landed mid-section or short).
  // This also covers a link to the #section already in the address bar, which does nothing in iOS Safari.
  useEffect(() => {
    const onClick = (e: MouseEvent) => {
      if (e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
      const a = (e.target as Element | null)?.closest?.("a[href]");
      if (!(a instanceof HTMLAnchorElement) || (a.target && a.target !== "_self") || !a.hash) return;
      const here = window.location;
      if (a.origin !== here.origin || a.pathname !== here.pathname || a.search !== here.search) return;
      const id = decodeURIComponent(a.hash.slice(1));
      if (!document.getElementById(id)) return;
      e.preventDefault();
      if (a.hash !== here.hash) window.history.pushState(window.history.state, "", a.hash);
      glideTo(id);
    };
    document.addEventListener("click", onClick);
    return () => document.removeEventListener("click", onClick);
  }, []);

  // Opened directly at a #section (/#support): the browser jumps before late content has its height, so glide there
  // once the page has loaded (BUG-17)
  useEffect(() => {
    const id = decodeURIComponent(window.location.hash.slice(1));
    if (!id) return;
    const go = () => setTimeout(() => glideTo(id), 80);
    if (document.readyState === "complete") go();
    else window.addEventListener("load", go, { once: true });
    return () => window.removeEventListener("load", go);
  }, []);

  // monetize.js navigates to the application form through this, so it is a client-side navigation
  useEffect(() => {
    const w = window as unknown as { __mzNavigate?: (url: string) => void };
    w.__mzNavigate = (url) => router.push(url);
    return () => {
      delete w.__mzNavigate;
    };
  }, [router]);

  useEffect(() => {
    // Where monetize.js posts applications: this app's /api/apply unless NEXT_PUBLIC_INTAKE_URL points elsewhere
    (window as unknown as { __mzIntakeUrl?: string }).__mzIntakeUrl = process.env.NEXT_PUBLIC_INTAKE_URL || "/api/apply";
    const names = isHubPath(pathname) ? hub : [...base, ...(byPath[pathname] ?? defaultPage)];
    let cleanup: Cleanup | undefined;
    let cancelled = false;

    // Fetch first, then execute all scripts in one synchronous block so nothing else is recorded
    Promise.all(names.map(load)).then((texts) => {
      if (cancelled) return;
      cleanup = runTracked(() => texts.forEach((src) => new Function(src)()));
    });

    return () => {
      cancelled = true;
      cleanup?.();
    };
  }, [pathname]);

  return null;
}
