/* global React, Sparkle, SiteIcon, useScrollProgress, usePassedThreshold, Magnetic */

// Detect whether the nav band currently sits over a dark section, by sampling
// the background luminance of the full-width block under the nav. Works on every
// page automatically, no manual tagging needed.
function useOnDark(navMid = 34) {
  const [dark, setDark] = React.useState(false);
  React.useEffect(() => {
    const isDark = (c) => {
      const m = c && c.match(/rgba?\(([^)]+)\)/);
      if (!m) return false;
      const p = m[1].split(",").map(Number);
      const [r, g, b, a = 1] = p;
      if (a === 0) return false;
      return 0.2126 * r + 0.7152 * g + 0.0722 * b < 110;
    };
    const check = () => {
      let result = false;
      const blocks = document.querySelectorAll("header, section, footer");
      for (const el of blocks) {
        const r = el.getBoundingClientRect();
        if (r.top <= navMid && r.bottom > navMid && r.width > window.innerWidth * 0.8) {
          let node = el;
          let bg = getComputedStyle(node).backgroundColor;
          while ((!bg || bg === "rgba(0, 0, 0, 0)" || bg === "transparent") && node.parentElement) {
            node = node.parentElement;
            bg = getComputedStyle(node).backgroundColor;
          }
          result = isDark(bg);
          break;
        }
      }
      setDark(result);
    };
    check();
    window.addEventListener("scroll", check, { passive: true });
    window.addEventListener("resize", check);
    return () => {
      window.removeEventListener("scroll", check);
      window.removeEventListener("resize", check);
    };
  }, [navMid]);
  return dark;
}

function Nav() {
  const progress = useScrollProgress();
  const scrolled = usePassedThreshold(40);
  const onDark = useOnDark();
  const [open, setOpen] = React.useState(false);
  const logoLight = (window.__resources && window.__resources.logoHorizontal) || "assets/logo-horizontal.png";
  const logoDark = (window.__resources && window.__resources.logoHorizontalDark) || "assets/logo-horizontal-dark.png";
  const base = window.__SITE_HOME__ || "";

  // lock body scroll while the mobile menu is open
  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  const links = [
    { label: "Why DealAgent", href: "why-dealagent.html", icon: "shield" },
    { label: "How it works", href: "how-it-works.html", icon: "gauge" },
    { label: "AI Shopping", href: "agentic-api.html", icon: "sparkles" },
    { label: "Integrations", href: "integrations.html", icon: "package" },
    { label: "Pricing", href: "pricing.html", icon: "tag" },
  ];

  return (
    <nav className={`nav ${scrolled ? "scrolled" : "top"} ${onDark ? "on-dark" : "on-light"} ${open ? "menu-open" : ""}`}>
      <div className="nav-inner">
        <a className="nav-logo" href={base || "#top"} aria-label="DealAgent home">
          <img src={onDark ? logoDark : logoLight} alt="DealAgent"/>
        </a>
        <div className="nav-links">
          {links.map((l) => <a key={l.label} href={l.href}>{l.label}</a>)}
        </div>
        <div className="spacer"></div>
        <div className="nav-cta">
          <Magnetic strength={0.25}>
            <a className="btn btn-primary" href="https://apps.shopify.com/dealagent-ai" target="_blank" rel="noopener">Install on Shopify</a>
          </Magnetic>
        </div>
        <button className="nav-toggle" aria-label={open ? "Close menu" : "Open menu"} aria-expanded={open} onClick={() => setOpen(!open)}>
          <span className={`nav-burger ${open ? "x" : ""}`}><i></i><i></i><i></i></span>
        </button>
      </div>
      <div className="nav-progress" style={{ width: "100%", transform: `scaleX(${progress})`, opacity: scrolled ? 1 : 0 }}></div>

      <div className={`nav-sheet ${open ? "open" : ""}`} onClick={() => setOpen(false)}>
        <div className="nav-sheet-panel" onClick={(e) => e.stopPropagation()}>
          <div className="nav-sheet-head">
            <a className="nav-sheet-logo" href={base || "#top"} aria-label="DealAgent home" onClick={() => setOpen(false)}>
              <img src={logoLight} alt="DealAgent"/>
            </a>
            <button className="nav-sheet-close" aria-label="Close menu" onClick={() => setOpen(false)}>
              <SiteIcon name="x" size={22}/>
            </button>
          </div>
          <div className="nav-sheet-links">
            {links.map((l) => <a key={l.label} href={l.href} onClick={() => setOpen(false)}><span className="nsi"><SiteIcon name={l.icon} size={18}/></span>{l.label}</a>)}
          </div>
          <div className="nav-sheet-cta">
            <a className="btn btn-primary btn-lg" href="https://apps.shopify.com/dealagent-ai" target="_blank" rel="noopener">Install on Shopify</a>
          </div>
        </div>
      </div>
    </nav>
  );
}

window.Nav = Nav;
