// Nav: sticky shrinking pill nav + mega menu for Services (Notion-style smooth height anim)

(function () {
const { useState, useEffect, useRef, useCallback } = React;

function Nav({ route, onNavigate, navStyle = "mega", theme, onToggleTheme }) {
  const [scrolled, setScrolled] = useState(false);
  const [megaOpen, setMegaOpen] = useState(false);
  const [mobileOpen, setMobileOpen] = useState(false);
  const closeTimer = useRef(null);

  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 24);
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  useEffect(() => {
    setMegaOpen(false);
    setMobileOpen(false);
  }, [route]);

  useEffect(() => {
    if (!mobileOpen) return;
    const onKeyDown = (e) => {
      if (e.key === "Escape") setMobileOpen(false);
    };
    window.addEventListener("keydown", onKeyDown);
    return () => window.removeEventListener("keydown", onKeyDown);
  }, [mobileOpen]);

  const openMega = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    if (navStyle !== "off") setMegaOpen(true);
  };
  const queueClose = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setMegaOpen(false), 140);
  };

  const N = window.NODESTONE;
  const services = N.services;
  const navItems = N.nav;

  const go = useCallback((e, path) => {
    e.preventDefault();
    setMegaOpen(false);
    setMobileOpen(false);
    if (path.startsWith("#/")) {
      window.location.hash = path.slice(1); // store as "/..."
    } else {
      window.location.href = path;
    }
  }, []);

  const isActive = (item) => route === item.path.slice(1) ||
    (item.path === "#/" && (route === "" || route === "/"));
  const mobileTabIndex = mobileOpen ? 0 : -1;

  return (
    <header className={"nav " + (scrolled ? "scrolled " : "") + (mobileOpen ? "mobile-open" : "")}>
      <button
        className="mobile-nav-backdrop"
        type="button"
        aria-label="Close navigation"
        aria-hidden={mobileOpen ? "false" : "true"}
        tabIndex={mobileTabIndex}
        onClick={() => setMobileOpen(false)}
      />

      <div className="nav-shell" onMouseLeave={queueClose}>
        <a href="#/" onClick={(e) => go(e, "#/")} className="nav-brand">
          <span className="nav-brand-dot" />
          Nodestone
        </a>

        <nav className="nav-links" aria-label="Primary">
          {navItems.map((item) => {
            if (item.mega && navStyle !== "simple") {
              return (
                <div
                  key={item.id}
                  style={{ position: "relative" }}
                  onMouseEnter={openMega}
                  onMouseLeave={queueClose}
                >
                  <a
                    href={item.path}
                    className={"nav-link " + (route.startsWith("/services") ? "active" : "")}
                    onClick={(e) => { go(e, item.path); setMegaOpen(false); }}
                  >
                    {item.label}
                    <span style={{ marginLeft: 4, fontSize: 9, opacity: 0.55, transform: megaOpen ? "rotate(180deg)" : "none", display: "inline-block", transition: "transform 220ms" }}>▾</span>
                  </a>
                </div>
              );
            }
            return (
              <a
                key={item.id}
                href={item.path}
                className={"nav-link " + (isActive(item) ? "active" : "")}
                onClick={(e) => go(e, item.path)}
              >
                {item.label}
              </a>
            );
          })}
        </nav>

        <button
          className="nav-theme-toggle"
          aria-label="Toggle theme"
          title={theme === "dark" ? "Switch to light" : "Switch to dark"}
          onClick={onToggleTheme}
        >
          {theme === "dark" ? (
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <circle cx="12" cy="12" r="4" />
              <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M4.93 19.07l1.41-1.41M17.66 6.34l1.41-1.41" />
            </svg>
          ) : (
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
            </svg>
          )}
        </button>

        <a href="#/contact" className="nav-cta" onClick={(e) => go(e, "#/contact")}>
          <span className="nav-cta-full">Start a conversation</span>
          <span className="nav-cta-short">Contact</span>
        </a>

        <button
          className="nav-menu-toggle"
          type="button"
          aria-label={mobileOpen ? "Close navigation" : "Open navigation"}
          aria-expanded={mobileOpen ? "true" : "false"}
          aria-controls="mobile-nav-menu"
          onClick={() => setMobileOpen((open) => !open)}
        >
          <span />
          <span />
          <span />
        </button>

        <div className="mobile-nav-panel" id="mobile-nav-menu" aria-hidden={mobileOpen ? "false" : "true"}>
          <nav className="mobile-nav-links" aria-label="Mobile primary">
            {navItems.map((item) => (
              <div key={item.id} className={item.mega ? "mobile-nav-group" : ""}>
                <a
                  href={item.path}
                  className={"mobile-nav-link " + (isActive(item) || (item.mega && route.startsWith("/services")) ? "active" : "")}
                  tabIndex={mobileTabIndex}
                  onClick={(e) => go(e, item.path)}
                >
                  <span>{item.label}</span>
                  <span className="arr">→</span>
                </a>

                {item.mega && (
                  <div className="mobile-service-links">
                    {services.map((s) => (
                      <a
                        key={s.slug}
                        href={"#/services/" + s.slug}
                        className={"mobile-service-link " + (route === "/services/" + s.slug ? "active" : "")}
                        tabIndex={mobileTabIndex}
                        onClick={(e) => go(e, "#/services/" + s.slug)}
                      >
                        {s.label}
                      </a>
                    ))}
                  </div>
                )}
              </div>
            ))}
          </nav>
        </div>

        {navStyle !== "simple" && (
          <div
            className={"mega " + (megaOpen ? "open" : "")}
            onMouseEnter={openMega}
            onMouseLeave={queueClose}
          >
            <div className="mega-grid">
              <div className="mega-intro">
                <div>
                  <div className="mono">Services</div>
                  <h4 style={{ marginTop: 10 }}>The full modernisation stack, without the costume drama.</h4>
                </div>
                <p>
                  Each engagement is shaped around the outcome. These are the areas clients usually bring us in to fix, build or lead.
                </p>
                <a
                  href="#/services"
                  className="nav-link"
                  style={{ padding: 0, color: "var(--fg)", fontWeight: 500 }}
                  onClick={(e) => { go(e, "#/services"); setMegaOpen(false); }}
                >
                  See all services →
                </a>
              </div>

              <div className="mega-col">
                <h5>Modernise</h5>
                {services.slice(0, 4).map((s) => (
                  <a
                    key={s.slug}
                    href={"#/services/" + s.slug}
                    className="mega-item"
                    onClick={(e) => { go(e, "#/services/" + s.slug); setMegaOpen(false); }}
                  >
                    <span className="mega-item-title">
                      {s.label}
                      <span className="arr">→</span>
                    </span>
                    <span className="mega-item-sub">{s.short}</span>
                  </a>
                ))}
              </div>

              <div className="mega-col">
                <h5>Build</h5>
                {services.slice(4).map((s) => (
                  <a
                    key={s.slug}
                    href={"#/services/" + s.slug}
                    className="mega-item"
                    onClick={(e) => { go(e, "#/services/" + s.slug); setMegaOpen(false); }}
                  >
                    <span className="mega-item-title">
                      {s.label}
                      <span className="arr">→</span>
                    </span>
                    <span className="mega-item-sub">{s.short}</span>
                  </a>
                ))}
              </div>
            </div>
          </div>
        )}
      </div>
    </header>
  );
}

window.Nav = Nav;
})();
