/* Global styles object naming rule: unique per component. */
const { Button } = window.NRTRDesignSystem_47db9c;

const NAV_LINKS = [
  ["Services", "services.html"],
  ["The Space", "experience.html"],
  ["The Science", "science.html"],
  ["Membership", "membership.html"],
  ["FAQ", "faq.html"],
  ["About", "about.html"],
  ["Contact", "contact.html"],
];

function currentPage() {
  const p = window.location.pathname.split("/").pop();
  return !p || p === "" ? "index.html" : p;
}

function SiteNav({ onBook, dark = true, stickyCta = true }) {
  const [open, setOpen] = React.useState(false);
  const [scrolled, setScrolled] = React.useState(false);
  const [pastHero, setPastHero] = React.useState(false);
  const [isMobile, setIsMobile] = React.useState(false);
  const here = currentPage();

  React.useEffect(() => {
    const mq = window.matchMedia("(max-width: 560px)");
    const apply = () => setIsMobile(mq.matches);
    apply();
    mq.addEventListener ? mq.addEventListener("change", apply) : mq.addListener(apply);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", apply) : mq.removeListener(apply); };
  }, []);

  React.useEffect(() => {
    document.body.style.paddingBottom = (stickyCta && isMobile && pastHero) ? "76px" : "";
    return () => { document.body.style.paddingBottom = ""; };
  }, [isMobile, pastHero, stickyCta]);

  React.useEffect(() => {
    const onScroll = () => { setScrolled(window.pageYOffset > 24); setPastHero(window.pageYOffset > 480); };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);
  const fg = dark ? "var(--linen)" : "var(--text-strong)";
  const barColor = dark ? "var(--linen)" : "var(--text-strong)";

  // Same-page hash links scroll smoothly; cross-page links navigate normally.
  const handleNav = (e, target) => {
    setOpen(false);
    const [page, hash] = target.split("#");
    if (hash && (page === "" || page === here)) {
      e.preventDefault();
      const el = document.getElementById(hash);
      if (el) {
        const hdr = document.querySelector("header");
        const off = hdr ? hdr.offsetHeight : 74;
        const y = el.getBoundingClientRect().top + window.pageYOffset - off;
        window.scrollTo({ top: y, behavior: "smooth" });
      }
    }
    // otherwise: default navigation (cross-page)
  };

  const isActive = (target) => target.split("#")[0] === here;

  return (
    <React.Fragment>
    <header
      style={{
        position: "sticky",
        top: 0,
        zIndex: 40,
        background: dark
          ? (scrolled ? "var(--nav-fill-dark-scrolled)" : "var(--nav-fill-dark)")
          : (scrolled ? "var(--nav-fill-light-scrolled)" : "var(--nav-fill-light)"),
        backdropFilter: "blur(16px)",
        WebkitBackdropFilter: "blur(16px)",
        borderBottom: `1px solid ${dark ? "var(--line-on-dark)" : "var(--line-soft)"}`,
        boxShadow: scrolled ? "0 8px 30px rgba(20,14,9,0.22)" : "0 0 0 rgba(0,0,0,0)",
        transition: "background 320ms var(--ease-standard), box-shadow 320ms var(--ease-standard)",
      }}
    >
      <div
        style={{
          maxWidth: "var(--container)",
          margin: "0 auto",
          padding: "0 var(--space-6)",
          height: scrolled ? 60 : "var(--nav-h)",
          transition: "height 320ms var(--ease-standard)",
          display: "flex",
          alignItems: "center",
          justifyContent: "space-between",
        }}
      >
        <a href="index.html" style={{ display: "flex", alignItems: "center", gap: "11px" }}>
          <img
            src={dark ? "assets/icons/mark-inverted-ivory.svg" : "assets/icons/mark-inverted-terracotta.svg"}
            alt=""
            aria-hidden="true"
            style={{ height: 27, width: 27 }}
          />
          <img
            src={dark ? "assets/logos/primary-logo-ivory.svg" : "assets/logos/primary-logo-terracotta.svg"}
            alt="NRTR"
            style={{ height: 22 }}
          />
        </a>

        <nav style={{ display: "flex", gap: "30px", alignItems: "center" }} className="nrtr-nav-links">
          {NAV_LINKS.map(([l, target]) => {
            const active = isActive(target);
            return (
              <a
                key={l}
                href={target}
                className="nrtr-navlink"
                data-active={active ? "true" : "false"}
                onClick={(e) => handleNav(e, target)}
                style={{
                  fontFamily: "var(--font-label)",
                  fontSize: "11px",
                  fontWeight: 500,
                  textTransform: "uppercase",
                  letterSpacing: "0.14em",
                  color: active ? "var(--camel)" : fg,
                  opacity: active ? 1 : 0.82,
                  textDecoration: "none",
                  transition: "opacity 140ms ease, color 140ms ease",
                }}
                onMouseEnter={(e) => (e.currentTarget.style.opacity = "1")}
                onMouseLeave={(e) => (e.currentTarget.style.opacity = active ? "1" : "0.82")}
              >
                {l}
              </a>
            );
          })}
        </nav>

        <div style={{ display: "flex", alignItems: "center", gap: "12px" }}>
          <div className="nrtr-nav-cta">
            <Button variant="primary" size="sm" onClick={onBook}>
              Join the Founding List
            </Button>
          </div>
          {/* Mobile hamburger — shown < 980px via CSS */}
          <button
            className="nrtr-nav-burger"
            aria-label={open ? "Close menu" : "Open menu"}
            aria-expanded={open}
            onClick={() => setOpen((v) => !v)}
            style={{
              display: "none",
              flexDirection: "column",
              justifyContent: "center",
              alignItems: "center",
              gap: "5px",
              width: 44,
              height: 44,
              border: "none",
              background: "none",
              cursor: "pointer",
              padding: 0,
            }}
          >
            <span style={{ display: "block", width: 22, height: 2, background: barColor, borderRadius: 2, transition: "transform 240ms ease, opacity 240ms ease", transform: open ? "translateY(7px) rotate(45deg)" : "none" }} />
            <span style={{ display: "block", width: 22, height: 2, background: barColor, borderRadius: 2, transition: "opacity 140ms ease", opacity: open ? 0 : 1 }} />
            <span style={{ display: "block", width: 22, height: 2, background: barColor, borderRadius: 2, transition: "transform 240ms ease, opacity 240ms ease", transform: open ? "translateY(-7px) rotate(-45deg)" : "none" }} />
          </button>
        </div>
      </div>

      {/* Mobile panel */}
      {open && (
        <div
          className="nrtr-nav-panel"
          style={{
            borderTop: `1px solid ${dark ? "var(--line-on-dark)" : "var(--line-soft)"}`,
            background: dark ? "rgba(24,16,10,0.96)" : "rgba(238,227,204,0.98)",
            backdropFilter: "blur(14px)",
            WebkitBackdropFilter: "blur(14px)",
          }}
        >
          <div style={{ maxWidth: "var(--container)", margin: "0 auto", padding: "12px var(--space-6) 22px", display: "flex", flexDirection: "column" }}>
            {NAV_LINKS.map(([l, target]) => (
              <a
                key={l}
                href={target}
                onClick={(e) => handleNav(e, target)}
                style={{
                  fontFamily: "var(--font-label)",
                  fontSize: "13px",
                  fontWeight: 500,
                  textTransform: "uppercase",
                  letterSpacing: "0.14em",
                  color: isActive(target) ? "var(--camel)" : fg,
                  opacity: 0.9,
                  textDecoration: "none",
                  padding: "14px 0",
                  borderBottom: `1px solid ${dark ? "var(--line-on-dark)" : "var(--line-soft)"}`,
                }}
              >
                {l}
              </a>
            ))}
            <div style={{ marginTop: "18px" }}>
              <Button variant="primary" size="lg" fullWidth onClick={() => { setOpen(false); onBook && onBook(); }}>
                Join the Founding List
              </Button>
            </div>
          </div>
        </div>
      )}
    </header>
    {stickyCta && isMobile && (
      <div aria-hidden={pastHero ? undefined : "true"} style={{ position: "fixed", left: 0, right: 0, bottom: 0, zIndex: 60, padding: "12px 16px calc(12px + env(safe-area-inset-bottom, 0px))", background: "var(--nav-fill-dark-scrolled)", backdropFilter: "blur(14px)", WebkitBackdropFilter: "blur(14px)", borderTop: "1px solid var(--line-on-dark)", boxShadow: "0 -8px 30px rgba(20,14,9,0.28)", transform: pastHero ? "translateY(0)" : "translateY(130%)", visibility: pastHero ? "visible" : "hidden", transition: pastHero ? "transform .4s cubic-bezier(.16,1,.3,1), visibility 0s" : "transform .4s cubic-bezier(.16,1,.3,1), visibility 0s .4s" }}>
        <Button variant="primary" size="lg" fullWidth onClick={onBook} tabIndex={pastHero ? undefined : -1}>Join the Founding List</Button>
      </div>
    )}
    </React.Fragment>
  );
}

window.SiteNav = SiteNav;
