/* eslint-disable */
const { useState: useStateRtr, useEffect: useEffectRtr, useCallback: useCallbackRtr } = React;

// Take over scroll restoration so the browser doesn't fight our manual scrolls.
if ("scrollRestoration" in history) {
  history.scrollRestoration = "manual";
}

function parseLocation() {
  const path = window.location.pathname.replace(/^\/+|\/+$/g, "");
  const parts = path.split("/").filter(Boolean);
  if (parts.length === 0) return { name: "home" };
  if (parts[0] === "capabilities") {
    if (parts.length === 1) return { name: "capabilities-index" };
    return { name: "capability", id: parts[1] };
  }
  if (parts[0] === "brands") {
    if (parts.length === 1) return { name: "brands-index" };
    return { name: "brand", id: parts[1] };
  }
  return { name: "not-found", path };
}

function useRoute() {
  const [route, setRoute] = useStateRtr(parseLocation());
  useEffectRtr(() => {
    const onPop = () => setRoute(parseLocation());
    window.addEventListener("popstate", onPop);
    return () => window.removeEventListener("popstate", onPop);
  }, []);
  return route;
}

function navigate(to, opts = {}) {
  const url = new URL(to, window.location.origin);
  const samePath = url.pathname === window.location.pathname;
  const hash = url.hash ? url.hash.slice(1) : null;

  if (samePath) {
    if (hash) scrollToAnchor(hash);
    return;
  }
  history.pushState({}, "", url.pathname + url.search + url.hash);
  window.dispatchEvent(new PopStateEvent("popstate"));
  if (hash) {
    // Poll for the anchor to appear in the new page's React tree, then scroll.
    // We compute absolute position and use window.scrollTo because some
    // browsers ignore scrollIntoView when the URL hash matches (treating it
    // as "already at the anchor").
    const start = performance.now();
    const tryScroll = () => {
      const el = document.getElementById(hash);
      if (el) {
        const rect = el.getBoundingClientRect();
        const offset = 80; // scroll-margin-top
        window.scrollTo({ top: rect.top + window.scrollY - offset, behavior: "auto" });
        return;
      }
      if (performance.now() - start < 1500) setTimeout(tryScroll, 32);
    };
    setTimeout(tryScroll, 32);
  } else if (!opts.preserveScroll) {
    window.scrollTo({ top: 0, behavior: "auto" });
  }
}

function scrollToAnchor(id) {
  const el = document.getElementById(id);
  if (!el) return;
  const r = el.getBoundingClientRect();
  const target = Math.max(0, Math.round(r.top + window.scrollY - 80));
  // Use 'auto' instead of 'smooth' — smooth-scroll is unreliable in some embed
  // contexts (we apply our own transition via CSS scroll-behavior on supporting
  // browsers).
  window.scrollTo({ top: target, behavior: "auto" });
}

function Link({ to, children, className, onClick, style, "aria-label": ariaLabel }) {
  const handle = (e) => {
    if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;
    e.preventDefault();
    // Fire any consumer-supplied onClick first (e.g. drawer onClose) so that
    // body scroll-locks etc. are released before we attempt scrolling.
    if (onClick) onClick(e);
    // Defer navigate to the next tick so React has flushed the unlock.
    setTimeout(() => navigate(to), 0);
  };
  return (
    <a href={to} className={className} style={style} aria-label={ariaLabel} onClick={handle}>
      {children}
    </a>
  );
}

function useIsMobile(bp = 760) {
  const [m, setM] = useStateRtr(() => (typeof window !== "undefined" ? window.innerWidth <= bp : false));
  useEffectRtr(() => {
    const onR = () => setM(window.innerWidth <= bp);
    window.addEventListener("resize", onR);
    return () => window.removeEventListener("resize", onR);
  }, [bp]);
  return m;
}

// On initial load, if URL has a hash, scroll to it once layout has settled.
// The browser tries to auto-scroll to #anchor before images/React content has
// finished loading — that lands in the wrong place. We override by forcing
// scroll back to top, then re-scrolling once layout is stable.
function useInitialHashScroll() {
  useEffectRtr(() => {
    const hash = window.location.hash ? window.location.hash.slice(1) : null;
    if (!hash) return;
    // Take over from any browser-initiated scroll
    window.scrollTo(0, 0);
    let cancelled = false;
    let lastY = -1;
    let stableCount = 0;
    const offset = 80;
    const doScroll = () => {
      const el = document.getElementById(hash);
      if (!el) return false;
      const r = el.getBoundingClientRect();
      const target = Math.max(0, Math.round(r.top + window.scrollY - offset));
      window.scrollTo(0, target);
      return Math.abs(window.scrollY - target) < 4;
    };
    // Poll for stability: scroll to anchor each frame until the target stops moving.
    const tick = () => {
      if (cancelled) return;
      const el = document.getElementById(hash);
      if (el) {
        const r = el.getBoundingClientRect();
        const target = Math.round(r.top + window.scrollY - offset);
        if (target === lastY) {
          stableCount++;
        } else {
          stableCount = 0;
          lastY = target;
          window.scrollTo(0, Math.max(0, target));
        }
      }
      // Stop after layout settles (5 stable frames) or after 3 seconds
      if (stableCount < 5 && performance.now() < startTime + 3000) {
        requestAnimationFrame(tick);
      }
    };
    const startTime = performance.now();
    requestAnimationFrame(tick);
    return () => { cancelled = true; };
  }, []);
}

Object.assign(window, { useRoute, navigate, Link, useIsMobile, useInitialHashScroll });
