(() => {
  const win = window as Window & { __gcMotionMounted?: boolean };
  if (win.__gcMotionMounted) return;
  win.__gcMotionMounted = true;

  const html = document.documentElement;
  const reduceQuery = window.matchMedia("(prefers-reduced-motion: reduce)");

  function storedMotionPref(): string | null {
    try {
      return window.localStorage.getItem("gc-motion-pref");
    } catch {
      return null;
    }
  }

  function setStoredMotionPref(value: string | null) {
    try {
      if (value) window.localStorage.setItem("gc-motion-pref", value);
      else window.localStorage.removeItem("gc-motion-pref");
    } catch {
      /* localStorage can be blocked; motion still works without persistence. */
    }
  }

  function applyMotionPref() {
    const pref = storedMotionPref();
    if (pref === "off") html.setAttribute("data-motion-pref", "off");
    else html.removeAttribute("data-motion-pref");
  }

  function connectionDisallowsVideo() {
    const nav = navigator as Navigator & {
      connection?: { saveData?: boolean; effectiveType?: string };
    };
    const connection = nav.connection;
    if (!connection) return false;
    return connection.saveData === true || /(^|-)2g$/i.test(connection.effectiveType || "");
  }

  function videoAllowed() {
    return !reduceQuery.matches && html.getAttribute("data-motion-pref") !== "off" && !connectionDisallowsVideo();
  }

  function demoteVideo(video: HTMLVideoElement) {
    video.pause();
    video.classList.remove("is-loaded");
    video.querySelectorAll("source").forEach((source) => source.removeAttribute("src"));
    video.removeAttribute("src");
    video.load();
  }

  function promoteVideo(video: HTMLVideoElement) {
    let promoted = false;
    video.querySelectorAll<HTMLSourceElement>("source[data-src]").forEach((source) => {
      if (!source.getAttribute("src")) {
        source.setAttribute("src", source.dataset.src || "");
        promoted = true;
      }
    });
    if (promoted) video.load();

    const markLoaded = () => video.classList.add("is-loaded");
    video.addEventListener("loadeddata", markLoaded, { once: true });
    video.addEventListener("playing", markLoaded, { once: true });

    const attempt = video.play();
    if (attempt && "catch" in attempt) attempt.catch(() => {});
  }

  function syncHeroVideos() {
    document.querySelectorAll<HTMLVideoElement>("[data-gc-hero-video]").forEach((video) => {
      if (videoAllowed()) promoteVideo(video);
      else demoteVideo(video);
    });
  }

  function setHeroVisible() {
    document.body.classList.add("motion-ready");
    requestAnimationFrame(() => {
      document.querySelectorAll(".gc-hero").forEach((hero) => hero.classList.add("is-visible"));
    });
  }

  function mountRevealObserver() {
    const targets = Array.from(document.querySelectorAll<HTMLElement>(".reveal-target"));
    if (!targets.length) return;
    if (!("IntersectionObserver" in window)) {
      targets.forEach((target) => target.classList.add("is-visible"));
      return;
    }
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return;
          entry.target.classList.add("is-visible");
          observer.unobserve(entry.target);
        });
      },
      { rootMargin: "0px 0px -12% 0px", threshold: 0.12 }
    );
    targets.forEach((target, index) => {
      target.style.transitionDelay = `${Math.min(index, 6) * 55}ms`;
      observer.observe(target);
    });
  }

  function mountCountUps() {
    const targets = Array.from(document.querySelectorAll<HTMLElement>("[data-count-up]"));
    if (!targets.length) return;

    const showFinal = (el: HTMLElement) => {
      const finalText = el.dataset.final || el.dataset.countUp || el.textContent || "";
      el.textContent = finalText;
    };

    if (reduceQuery.matches || html.getAttribute("data-motion-pref") === "off" || !("IntersectionObserver" in window)) {
      targets.forEach(showFinal);
      return;
    }

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return;
          const el = entry.target as HTMLElement;
          const finalText = el.dataset.final || el.dataset.countUp || "0";
          const numeric = Number(finalText.replace(/[^\d.-]/g, ""));
          if (!Number.isFinite(numeric)) {
            showFinal(el);
            observer.unobserve(el);
            return;
          }
          const start = performance.now();
          const duration = Number(el.dataset.duration || 900);
          const prefix = finalText.match(/^[^\d.-]*/)?.[0] || "";
          const suffix = finalText.match(/[^\d.]*$/)?.[0] || "";
          const decimals = finalText.includes(".") ? finalText.split(".")[1].replace(/[^\d].*$/, "").length : 0;
          const tick = (now: number) => {
            const t = Math.min(1, (now - start) / duration);
            const eased = 1 - Math.pow(1 - t, 3);
            el.textContent = `${prefix}${(numeric * eased).toFixed(decimals)}${suffix}`;
            if (t < 1) requestAnimationFrame(tick);
            else showFinal(el);
          };
          requestAnimationFrame(tick);
          observer.unobserve(el);
        });
      },
      { threshold: 0.35 }
    );
    targets.forEach((target) => observer.observe(target));
  }

  function updateScrollState() {
    const progress = Math.min(1, window.scrollY / 420);
    document.querySelectorAll<HTMLElement>(".gc-hero").forEach((hero) => {
      hero.style.setProperty("--gc-hero-shift", `${Math.round(progress * 18)}px`);
    });
    document.querySelectorAll("header").forEach((header) => {
      header.classList.toggle("is-condensed", window.scrollY > 48);
    });
  }

  function mountFormFeedback() {
    document.querySelectorAll<HTMLFormElement>("form").forEach((form) => {
      form.addEventListener("submit", () => {
        form.classList.add("form-sent");
      });
    });
  }

  function mountMotionToggles() {
    document.querySelectorAll<HTMLElement>("[data-motion-toggle]").forEach((toggle) => {
      toggle.addEventListener("click", () => {
        const next = html.getAttribute("data-motion-pref") === "off" ? null : "off";
        setStoredMotionPref(next);
        applyMotionPref();
        syncHeroVideos();
      });
    });
  }

  applyMotionPref();
  setHeroVisible();
  syncHeroVideos();
  mountRevealObserver();
  mountCountUps();
  mountFormFeedback();
  mountMotionToggles();
  updateScrollState();

  window.addEventListener("scroll", updateScrollState, { passive: true });
  reduceQuery.addEventListener?.("change", () => {
    syncHeroVideos();
    mountCountUps();
  });
})();
