"use client";

import { useEffect } from "react";

/**
 * Page behaviour ported from the static site's assets/js/script.js and the inline
 * <script> blocks of individual pages. Logic and timings are unchanged; the only
 * differences are that everything is scoped to the current page's root element
 * (Next keeps visited pages mounted but hidden) and cleaned up when it unmounts.
 *
 * The site header's menu / dropdown / scroll shadow live in SiteHeader.tsx.
 */
export function useSiteScripts(root: HTMLElement | null) {
  useEffect(() => {
    if (!root) return;
    const cleanups: (() => void)[] = [];
    const on = <K extends keyof WindowEventMap>(t: Window, type: K, fn: (e: WindowEventMap[K]) => void, opts?: AddEventListenerOptions) => {
      t.addEventListener(type, fn, opts);
      cleanups.push(() => t.removeEventListener(type, fn, opts));
    };
    const $ = <T extends Element = HTMLElement>(sel: string) => root.querySelector<T & Element>(sel);
    const $$ = <T extends Element = HTMLElement>(sel: string) => Array.from(root.querySelectorAll<T & Element>(sel));

    cleanups.push(heroNetwork(root));
    homeTopBackground(root, $, on);
    cleanups.push(scrollReveal($$, on));
    staggerChildren($$);
    cleanups.push(statCounters($$));
    cleanups.push(progressBars($$));
    productDetails(root, $, $$);
    cleanups.push(delegatedClicks(root));
    cleanups.push(legacyInlineHandlers(root));

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

type Q = <T extends Element = HTMLElement>(sel: string) => (T & Element) | null;
type QA = <T extends Element = HTMLElement>(sel: string) => (T & Element)[];
type On = <K extends keyof WindowEventMap>(t: Window, type: K, fn: (e: WindowEventMap[K]) => void, opts?: AddEventListenerOptions) => void;

/* 2. Hero plexus network ------------------------------------------------- */
function heroNetwork(root: HTMLElement): () => void {
  const canvas = root.querySelector<HTMLCanvasElement>("#hero-network");
  const hero = canvas?.closest<HTMLElement>(".hero");
  if (!canvas || !hero) return () => {};
  const ctx = canvas.getContext("2d")!;
  const reducedMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
  type P = { x: number; y: number; vx: number; vy: number; r: number; pulse: number };
  let particles: P[] = [];
  let width = 0;
  let height = 0;
  let dpr = 1;
  let rafId = 0;

  const particleCount = () => (width < 520 ? 48 : width < 900 ? 72 : width < 1280 ? 95 : 120);
  const connectDistance = () => (width < 520 ? 105 : width < 900 ? 130 : 155);

  function createParticles() {
    particles = Array.from({ length: particleCount() }, () => ({
      x: Math.random() * width,
      y: Math.random() * height,
      vx: (Math.random() - 0.5) * 0.28,
      vy: (Math.random() - 0.5) * 0.28,
      r: Math.random() * 1.1 + 1.1,
      pulse: Math.random() * Math.PI * 2,
    }));
  }
  function resize() {
    const rect = hero!.getBoundingClientRect();
    dpr = Math.min(window.devicePixelRatio || 1, 2);
    width = rect.width;
    height = rect.height;
    canvas!.width = Math.round(width * dpr);
    canvas!.height = Math.round(height * dpr);
    canvas!.style.width = `${width}px`;
    canvas!.style.height = `${height}px`;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    createParticles();
  }
  function draw() {
    ctx.clearRect(0, 0, width, height);
    const maxDist = connectDistance();
    for (let i = 0; i < particles.length; i += 1) {
      for (let j = i + 1; j < particles.length; j += 1) {
        const dx = particles[i].x - particles[j].x;
        const dy = particles[i].y - particles[j].y;
        const dist = Math.hypot(dx, dy);
        if (dist < maxDist) {
          const alpha = (1 - dist / maxDist) * 0.42;
          ctx.beginPath();
          ctx.strokeStyle = `rgba(210, 230, 255, ${alpha})`;
          ctx.lineWidth = 0.75;
          ctx.moveTo(particles[i].x, particles[i].y);
          ctx.lineTo(particles[j].x, particles[j].y);
          ctx.stroke();
        }
      }
    }
    particles.forEach((p) => {
      const glow = 0.55 + Math.sin(p.pulse) * 0.35;
      ctx.beginPath();
      ctx.arc(p.x, p.y, p.r, 0, Math.PI * 2);
      ctx.fillStyle = `rgba(255, 255, 255, ${glow})`;
      ctx.fill();
      if (!reducedMotion) {
        p.x += p.vx;
        p.y += p.vy;
        p.pulse += 0.018;
        if (p.x <= 0 || p.x >= width) p.vx *= -1;
        if (p.y <= 0 || p.y >= height) p.vy *= -1;
        p.x = Math.max(0, Math.min(width, p.x));
        p.y = Math.max(0, Math.min(height, p.y));
      }
    });
    rafId = requestAnimationFrame(draw);
  }

  resize();
  draw();
  let resizeTimer: ReturnType<typeof setTimeout>;
  const onResize = () => {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resize, 120);
  };
  const onVis = () => {
    if (document.hidden) {
      cancelAnimationFrame(rafId);
      rafId = 0;
    } else draw();
  };
  window.addEventListener("resize", onResize);
  document.addEventListener("visibilitychange", onVis);
  return () => {
    cancelAnimationFrame(rafId);
    clearTimeout(resizeTimer);
    window.removeEventListener("resize", onResize);
    document.removeEventListener("visibilitychange", onVis);
  };
}

/* 3. Home: background behind header + hero -------------------------------- */
function homeTopBackground(root: HTMLElement, $: Q, on: On) {
  const homeTopBg = $("#home-top-bg");
  const siteHeader = $(".site-header");
  const homeHero = root.matches(".page-home") ? $(".hero") : null;
  if (!homeTopBg || !siteHeader || !homeHero) return;
  const sync = () => {
    homeTopBg.style.height = `${siteHeader.offsetHeight + homeHero.offsetHeight}px`;
  };
  sync();
  on(window, "resize", sync, { passive: true });
  on(window, "load", sync);
}

/* 3. Scroll reveal ------------------------------------------------------- */
function scrollReveal($$: QA, on: On): () => void {
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          entry.target.classList.add("revealed");
          observer.unobserve(entry.target);
        }
      });
    },
    { threshold: 0.12, rootMargin: "0px 0px -40px 0px" },
  );
  const inView = (el: Element) => {
    const rect = el.getBoundingClientRect();
    return rect.top < window.innerHeight && rect.bottom > 0;
  };
  $$("[data-reveal]").forEach((el) => {
    if (inView(el)) el.classList.add("revealed");
    else observer.observe(el);
  });
  on(window, "load", () => {
    $$("[data-reveal]:not(.revealed)").forEach((el) => {
      if (inView(el)) {
        el.classList.add("revealed");
        observer.unobserve(el);
      }
    });
  });
  return () => observer.disconnect();
}

/* 4. Staggered reveal for grid children ---------------------------------- */
function staggerChildren($$: QA) {
  $$(
    ".business-network-banner, .stats-grid, .highlights-grid, .offers-grid, .case-study-checks, .impact-offers-grid, .campaigns-grid, .commitment-grid, .magazine-feature-grid",
  ).forEach((parent) => {
    parent.querySelectorAll<HTMLElement>("[data-reveal], li").forEach((child, i) => {
      child.style.transitionDelay = `${i * 0.08}s`;
    });
  });
}

/* 5. Animated stat counter ----------------------------------------------- */
function parseStatValue(str: string) {
  const target = str.trim();
  const prefix = target.startsWith("€") ? "€" : "";
  const body = prefix ? target.slice(1) : target;
  const hasPlus = body.endsWith("+");
  const core = hasPlus ? body.slice(0, -1) : body;
  const match = core.match(/^([\d,]+)([BMK])?$/);
  if (!match) return { target, end: 0, prefix: "", suffix: "" };
  return { target, end: parseInt(match[1].replace(/,/g, ""), 10), prefix, suffix: `${match[2] || ""}${hasPlus ? "+" : ""}` };
}
function formatStatValue(value: number, prefix: string, suffix: string) {
  const unit = suffix.match(/^[BMK]/)?.[0] || "";
  const plus = suffix.includes("+") ? "+" : "";
  const rounded = Math.round(value);
  if (unit === "B") return `${prefix}${rounded}B${plus}`;
  if (unit === "M") return `${prefix}${rounded.toLocaleString()}M${plus}`;
  if (unit === "K") return `${prefix}${rounded}K${plus}`;
  return `${prefix}${rounded >= 1000 ? rounded.toLocaleString() : rounded}${plus}`;
}
function statCounters($$: QA): () => void {
  const frames = new Set<number>();
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        const el = entry.target as HTMLElement;
        const raw = el.dataset.stat || el.textContent!.trim();
        const { target, end, prefix, suffix } = parseStatValue(raw);
        observer.unobserve(el);
        if (!end) {
          el.textContent = target;
          return;
        }
        const duration = 1600;
        const start = performance.now();
        const tick = (now: number) => {
          const progress = Math.min((now - start) / duration, 1);
          const eased = 1 - Math.pow(1 - progress, 3);
          el.textContent = formatStatValue(eased * end, prefix, suffix);
          if (progress < 1) frames.add(requestAnimationFrame(tick));
          else el.textContent = target;
        };
        frames.add(requestAnimationFrame(tick));
      });
    },
    { threshold: 0.5 },
  );
  $$(".stat-number").forEach((el) => observer.observe(el));
  return () => {
    observer.disconnect();
    frames.forEach(cancelAnimationFrame);
  };
}

/* 6. Contact forms: sent by InquiryForm.tsx (POST /public/inquiries). */

/* 10. Campaign progress bars --------------------------------------------- */
function progressBars($$: QA): () => void {
  const cards = $$(".campaign-card, .campaign-detail-panel");
  if (!cards.length) return () => {};
  const frames = new Set<number>();
  const observer = new IntersectionObserver(
    (entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;
        const card = entry.target;
        card.querySelectorAll<HTMLElement>(".progress-fill").forEach((bar) => {
          const pct = parseFloat(bar.dataset.progress!) || 0;
          bar.style.width = `${pct}%`;
          bar.classList.add("animated");
        });
        card.querySelectorAll<HTMLElement>(".progress-label").forEach((label) => {
          const target = parseFloat(label.dataset.target!) || 0;
          const duration = 1400;
          const start = performance.now();
          const tick = (now: number) => {
            const progress = Math.min((now - start) / duration, 1);
            const eased = 1 - Math.pow(1 - progress, 3);
            label.textContent = `${(eased * target).toFixed(2)}%`;
            if (progress < 1) frames.add(requestAnimationFrame(tick));
            else label.textContent = `${target.toFixed(2)}%`;
          };
          frames.add(requestAnimationFrame(tick));
        });
        observer.unobserve(card);
      });
    },
    { threshold: 0.35 },
  );
  cards.forEach((card) => observer.observe(card));
  return () => {
    observer.disconnect();
    frames.forEach(cancelAnimationFrame);
  };
}

/* 12. Product details: show the product picked on the catalogue ------------ */
function productDetails(root: HTMLElement, $: Q, $$: QA) {
  // /products/<slug> (data-product-live) runs its gallery in React; this is for the static /product-details.
  if (!root.matches(".product-details-page") || $("[data-product-live]")) return;
  const params = new URLSearchParams(window.location.search);
  const name = params.get("name");
  const image = params.get("image");
  const alt = params.get("alt");
  const mainImage = $<HTMLImageElement>("#product-main-image");
  const thumbs = $$<HTMLButtonElement>(".product-detail-thumb");
  const prevBtn = $<HTMLButtonElement>("#thumb-prev");
  const nextBtn = $<HTMLButtonElement>("#thumb-next");
  const titleEl = $(".product-detail-title");
  const breadcrumbCurrent = $('.product-detail-breadcrumb [aria-current="page"]');
  let activeIndex = 0;

  if (image && mainImage) {
    mainImage.src = image;
    if (alt) mainImage.alt = alt;
    thumbs.forEach((thumb) => {
      thumb.dataset.src = image;
      const img = thumb.querySelector("img");
      if (img) img.src = image;
    });
  }
  if (name) {
    if (titleEl) titleEl.textContent = name;
    if (breadcrumbCurrent) breadcrumbCurrent.textContent = name;
    document.title = `${name} — Product Details — Unionists Group`;
  }
  const setActive = (index: number) => {
    if (!thumbs.length || !mainImage) return;
    activeIndex = index;
    thumbs.forEach((thumb, i) => {
      thumb.classList.toggle("is-active", i === activeIndex);
      thumb.setAttribute("aria-pressed", i === activeIndex ? "true" : "false");
    });
    mainImage.src = thumbs[activeIndex].dataset.src!;
    if (prevBtn) prevBtn.disabled = activeIndex === 0;
    if (nextBtn) nextBtn.disabled = activeIndex === thumbs.length - 1;
  };
  thumbs.forEach((thumb, index) => (thumb.onclick = () => setActive(index)));
  if (prevBtn) prevBtn.onclick = () => activeIndex > 0 && setActive(activeIndex - 1);
  if (nextBtn) nextBtn.onclick = () => activeIndex < thumbs.length - 1 && setActive(activeIndex + 1);
}

/**
 * Click behaviours, delegated from the page root:
 *  7. in-page anchors scroll with an offset for the sticky header
 *  9. ripple on buttons
 *  + pagination / filter pills / catalogue filter toggle (inline scripts of
 *    active-campaigns, global-agriculture and thought-leadership-articles)
 */
function delegatedClicks(root: HTMLElement): () => void {
  const onClick = (e: MouseEvent) => {
    const t = e.target as Element | null;
    if (!t?.closest) return;

    const anchor = t.closest<HTMLAnchorElement>('a[href^="#"]');
    if (anchor && root.contains(anchor)) {
      const id = anchor.getAttribute("href")!;
      const target = id === "#" ? null : root.querySelector(id);
      if (target) {
        e.preventDefault();
        const header = root.querySelector<HTMLElement>(".site-header");
        const offset = (header ? header.offsetHeight : 0) + 16;
        window.scrollTo({ top: target.getBoundingClientRect().top + window.scrollY - offset, behavior: "smooth" });
      }
    }

    const btn = t.closest<HTMLElement>(".btn, .btn-primary, .btn-outline-navy");
    if (btn && root.contains(btn)) ripple(btn, e);

    const page = t.closest(".pagination-btn:not(.pagination-arrow):not(.pagination-ellipsis)");
    const pagination = page?.closest(".pagination");
    if (page && pagination) {
      pagination.querySelectorAll(".pagination-btn").forEach((b) => {
        b.classList.remove("is-active");
        b.removeAttribute("aria-current");
      });
      page.classList.add("is-active");
      page.setAttribute("aria-current", "page");
    }

    const pill = t.closest(".articles-filter-pill");
    const track = pill?.closest("#articles-filter-track");
    if (pill && track) {
      track.querySelectorAll(".articles-filter-pill").forEach((b) => {
        b.classList.remove("is-active");
        b.setAttribute("aria-selected", "false");
      });
      pill.classList.add("is-active");
      pill.setAttribute("aria-selected", "true");
    }
    const navBtn = t.closest(".articles-filter-nav");
    if (navBtn) {
      const all = Array.from(root.querySelectorAll(".articles-filter-nav"));
      root.querySelector("#articles-filter-track")?.scrollBy({ left: all.indexOf(navBtn) === 0 ? -180 : 180, behavior: "smooth" });
    }

    const filterToggle = t.closest("#catalog-filter-toggle");
    const sidebar = root.querySelector("#catalog-sidebar");
    if (filterToggle && sidebar) {
      const isOpen = sidebar.classList.toggle("is-open");
      filterToggle.setAttribute("aria-expanded", String(isOpen));
    }
  };
  root.addEventListener("click", onClick);
  return () => root.removeEventListener("click", onClick);
}

function ripple(btn: HTMLElement, e: MouseEvent) {
  if (!document.getElementById("ripple-style")) {
    const s = document.createElement("style");
    s.id = "ripple-style";
    s.textContent = "@keyframes ripple{to{transform:scale(2.5);opacity:0;}}";
    document.head.appendChild(s);
  }
  const span = document.createElement("span");
  const rect = btn.getBoundingClientRect();
  const size = Math.max(rect.width, rect.height);
  span.style.cssText = `
    position:absolute;
    border-radius:50%;
    background:rgba(255,255,255,0.3);
    width:${size}px;height:${size}px;
    left:${e.clientX - rect.left - size / 2}px;
    top:${e.clientY - rect.top - size / 2}px;
    transform:scale(0);
    animation:ripple .55s linear;
    pointer-events:none;
  `;
  const prev = btn.style.position;
  btn.style.position = "relative";
  btn.style.overflow = "hidden";
  btn.appendChild(span);
  span.addEventListener("animationend", () => {
    span.remove();
    if (!prev) btn.style.position = "";
  });
}

/**
 * The login / sign-up pages used inline handlers (onclick="togglePwd('pwd1', this)",
 * onmouseover="this.style.color='…'", onsubmit="goToStep2(event)"). The converted
 * markup keeps them as data-legacy-on* attributes; this runs the same functions.
 */
function legacyInlineHandlers(root: HTMLElement): () => void {
  if (!root.querySelector("[data-legacy-onclick],[data-legacy-onsubmit],[data-legacy-onmouseover],select#industry-select")) return () => {};
  const timers: ReturnType<typeof setTimeout>[] = [];
  const byId = <T extends HTMLElement>(id: string) => root.querySelector<T>(`#${id}`);

  const togglePwd = (inputId: string, btn: Element) => {
    const input = byId<HTMLInputElement>(inputId);
    if (!input) return;
    const isHidden = input.type === "password";
    input.type = isHidden ? "text" : "password";
    btn.querySelector(".eye-open")?.classList.toggle("hidden", isHidden);
    btn.querySelector(".eye-closed")?.classList.toggle("hidden", !isHidden);
  };
  const showStep = (n: 1 | 2) => {
    const s1 = byId("step1"), s2 = byId("step2"), d1 = byId("dot-1"), d2 = byId("dot-2");
    if (!s1 || !s2 || !d1 || !d2) return;
    const [show, hide, on, off] = n === 2 ? [s2, s1, d2, d1] : [s1, s2, d1, d2];
    hide.classList.replace("active-step", "hidden-step");
    show.classList.replace("hidden-step", "active-step");
    off.style.width = "6px";
    off.style.background = "rgba(255,255,255,0.2)";
    on.style.width = "28px";
    on.style.background = "#00FFC7";
  };
  const fakeSubmit = (form: HTMLFormElement, busyText: string) => {
    const btn = form.querySelector<HTMLButtonElement>('[type="submit"]');
    if (!btn) return;
    const orig = btn.textContent;
    btn.textContent = busyText;
    btn.disabled = true;
    btn.style.opacity = ".7";
    timers.push(
      setTimeout(() => {
        btn.textContent = orig;
        btn.disabled = false;
        btn.style.opacity = "";
      }, 2000),
    );
  };

  const run = (code: string, el: Element, e: Event) => {
    let m: RegExpMatchArray | null;
    if ((m = code.match(/^togglePwd\('([^']+)',\s*this\)$/))) return togglePwd(m[1], el);
    if (code === "goBack()") return showStep(1);
    if (code === "goToStep2(event)") {
      e.preventDefault();
      const p1 = byId<HTMLInputElement>("pwd1")?.value;
      const p2 = byId<HTMLInputElement>("pwd2")?.value;
      const err = byId("pwd-error");
      if (p1 !== p2) return err?.classList.remove("hidden");
      err?.classList.add("hidden");
      return showStep(2);
    }
    if (code === "handleSignup(event)") {
      e.preventDefault();
      return fakeSubmit(el as HTMLFormElement, "Creating account…");
    }
    if ((m = code.match(/^this\.style\.(\w+)='([^']*)'$/))) {
      (el as HTMLElement).style.setProperty(m[1].replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()), m[2]);
      return;
    }
    console.warn("Unhandled legacy handler:", code);
  };

  const handler = (attr: string) => (e: Event) => {
    const t = e.target as Element | null;
    const el = t?.closest?.(`[${attr}]`);
    if (!el || !root.contains(el)) return;
    // mouseover/mouseout bubble from children; only react when entering/leaving el itself
    if (e instanceof MouseEvent && (e.type === "mouseover" || e.type === "mouseout") && e.relatedTarget instanceof Node && el.contains(e.relatedTarget)) return;
    run(el.getAttribute(attr)!, el, e);
  };
  const map: [string, string][] = [
    ["click", "data-legacy-onclick"],
    ["submit", "data-legacy-onsubmit"],
    ["mouseover", "data-legacy-onmouseover"],
    ["mouseout", "data-legacy-onmouseout"],
  ];
  const fns = map.map(([type, attr]) => [type, handler(attr)] as const);
  fns.forEach(([type, fn]) => root.addEventListener(type, fn));

  // signup: selects turn white once a value is chosen
  const selects = ["industry-select", "country-select"].map((id) => byId<HTMLSelectElement>(id)).filter(Boolean) as HTMLSelectElement[];
  const onChange = (e: Event) => ((e.currentTarget as HTMLSelectElement).style.color = "#fff");
  selects.forEach((s) => s.addEventListener("change", onChange));

  return () => {
    fns.forEach(([type, fn]) => root.removeEventListener(type, fn));
    selects.forEach((s) => s.removeEventListener("change", onChange));
    timers.forEach(clearTimeout);
  };
}
