
const NAV_GROUPS = [
  {
    label: "Stack",
    items: [
      { label: "Architecture", href: "#architecture" },
      { label: "Hardware", href: "#hardware" },
      { label: "UTS", href: "#uts" },
    ],
  },
  {
    label: "Dashboard",
    items: [
      { label: "PECAN", href: "#pecan" },
      { label: "Timeline", href: "#timeline" },
    ],
  },
  {
    label: "Integrations",
    items: [
      { label: "Bridges", href: "#bridges" },
      { label: "Broadcast", href: "#broadcast" },
      { label: "Lappy AI", href: "#lappy" },
    ],
  },
  {
    label: "Infrastructure",
    items: [
      { label: "Server", href: "#server" },
      { label: "Flight Recorder", href: "#flight" },
    ],
  },
  {
    label: "Team",
    items: [
      { label: "Team", href: "#team" },
    ],
  },
];

// Flat ordered list for scroll tracking
const ALL_SECTIONS = NAV_GROUPS.flatMap(g => g.items);

function NavGroup({ group, active, onNavigate }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const isActive = group.items.some(i => active === i.href.slice(1));

  React.useEffect(() => {
    const handler = (e) => {
      if (ref.current && !ref.current.contains(e.target)) setOpen(false);
    };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, []);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        onClick={() => setOpen(o => !o)}
        style={{
          background: "none", border: "none", cursor: "pointer",
          padding: "6px 12px", borderRadius: 6,
          fontFamily: "'Space Mono', monospace", fontSize: 11, fontWeight: 700,
          letterSpacing: 1, textTransform: "uppercase",
          color: isActive ? "#D6AB39" : "rgba(255,255,255,0.6)",
          borderBottom: isActive ? "1px solid #D6AB39" : "1px solid transparent",
          display: "flex", alignItems: "center", gap: 5, transition: "color 0.2s",
        }}
        onMouseEnter={() => setOpen(true)}
      >
        {group.label}
        <span style={{ fontSize: 8, opacity: 0.6, transition: "transform 0.2s", transform: open ? "rotate(180deg)" : "none", display: "inline-block" }}>▼</span>
      </button>

      {open && (
        <div
          onMouseLeave={() => setOpen(false)}
          style={{
            position: "absolute", top: "calc(100% + 8px)", left: "50%", transform: "translateX(-50%)",
            background: "rgba(13,12,17,0.97)", backdropFilter: "blur(20px)",
            border: "1px solid rgba(168,85,247,0.2)", borderRadius: 10,
            padding: "6px", zIndex: 200, minWidth: 160,
            boxShadow: "0 16px 40px rgba(0,0,0,0.5)",
          }}
        >
          {group.items.map(item => {
            const isItemActive = active === item.href.slice(1);
            return (
              <button
                key={item.href}
                onClick={() => { onNavigate(item.href); setOpen(false); }}
                style={{
                  display: "block", width: "100%", textAlign: "left",
                  background: isItemActive ? "rgba(214,171,57,0.1)" : "none",
                  border: "none", cursor: "pointer",
                  padding: "9px 14px", borderRadius: 6,
                  fontFamily: "'Space Mono', monospace", fontSize: 11, fontWeight: 700,
                  letterSpacing: 0.5,
                  color: isItemActive ? "#D6AB39" : "rgba(255,255,255,0.65)",
                  transition: "all 0.15s",
                  whiteSpace: "nowrap",
                }}
                onMouseEnter={e => { if (!isItemActive) e.currentTarget.style.background = "rgba(168,85,247,0.1)"; e.currentTarget.style.color = "#fff"; }}
                onMouseLeave={e => { if (!isItemActive) { e.currentTarget.style.background = "none"; e.currentTarget.style.color = "rgba(255,255,255,0.65)"; } }}
              >
                {isItemActive && <span style={{ color: "#D6AB39", marginRight: 6 }}>›</span>}
                {item.label}
              </button>
            );
          })}
        </div>
      )}
    </div>
  );
}

function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  const [active, setActive] = React.useState("overview");
  const [menuOpen, setMenuOpen] = React.useState(false);

  React.useEffect(() => {
    const onScroll = () => {
      setScrolled(window.scrollY > 40);
      const sections = ALL_SECTIONS.map(l => l.href.slice(1));
      for (let i = sections.length - 1; i >= 0; i--) {
        const el = document.getElementById(sections[i]);
        if (el && window.scrollY >= el.offsetTop - 120) {
          setActive(sections[i]);
          return;
        }
      }
      setActive("overview");
    };
    window.addEventListener("scroll", onScroll, { passive: true });
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  const scrollTo = (href) => {
    const id = href.slice(1);
    const el = document.getElementById(id);
    if (el) window.scrollTo({ top: el.offsetTop - 72, behavior: "smooth" });
    setMenuOpen(false);
  };

  return (
    <nav style={{
      position: "fixed", top: 0, left: 0, right: 0, zIndex: 100,
      background: scrolled ? "rgba(13,12,17,0.95)" : "transparent",
      backdropFilter: scrolled ? "blur(16px)" : "none",
      borderBottom: scrolled ? "1px solid rgba(168,85,247,0.15)" : "1px solid transparent",
      transition: "all 0.3s ease",
      padding: "0 2rem",
    }}>
      <div style={{ maxWidth: 1280, margin: "0 auto", display: "flex", alignItems: "center", justifyContent: "space-between", height: 68 }}>

        {/* Logo */}
        <div style={{ display: "flex", alignItems: "center", gap: 14, cursor: "pointer", flexShrink: 0 }} onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}>
          <img src="assets/WFR_DAQ_Logo.png" alt="WFR Data Acquisition" style={{ height: 38, width: "auto", display: "block" }} />
          <div style={{ width: 1, height: 28, background: "rgba(255,255,255,0.15)" }} />
          <div style={{ fontFamily: "'Orbitron', sans-serif", fontWeight: 900, fontSize: 16, background: "linear-gradient(90deg, #a855f7, #D6AB39)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent", letterSpacing: 3 }}>PECAN</div>
        </div>

        {/* Desktop grouped nav */}
        <div style={{ display: "flex", gap: 2, alignItems: "center" }} className="nav-desktop">
          {/* Overview standalone */}
          <button onClick={() => scrollTo("#overview")} style={{
            background: "none", border: "none", cursor: "pointer",
            padding: "6px 12px", borderRadius: 6,
            fontFamily: "'Space Mono', monospace", fontSize: 11, fontWeight: 700,
            letterSpacing: 1, textTransform: "uppercase",
            color: active === "overview" ? "#D6AB39" : "rgba(255,255,255,0.6)",
            borderBottom: active === "overview" ? "1px solid #D6AB39" : "1px solid transparent",
            transition: "color 0.2s",
          }}>Overview</button>

          {/* Grouped dropdowns */}
          {NAV_GROUPS.map(g => (
            <NavGroup key={g.label} group={g} active={active} onNavigate={scrollTo} />
          ))}

          <a href="https://github.com/Western-Formula-Racing/data-acquisition" target="_blank" rel="noopener noreferrer" style={{
            marginLeft: 10, padding: "6px 16px", borderRadius: 20,
            border: "1px solid rgba(168,85,247,0.45)", background: "rgba(168,85,247,0.1)",
            color: "#c4b5fd", fontFamily: "'Space Mono', monospace", fontSize: 11, fontWeight: 700,
            letterSpacing: 1, textDecoration: "none", textTransform: "uppercase", transition: "all 0.2s",
          }}>GitHub ↗</a>
        </div>

        {/* Mobile hamburger */}
        <button onClick={() => setMenuOpen(!menuOpen)} style={{ display: "none", background: "none", border: "none", cursor: "pointer", color: "#fff", fontSize: 22 }} className="nav-mobile-btn">
          {menuOpen ? "✕" : "☰"}
        </button>
      </div>

      {/* Mobile menu — flat list in scroll order */}
      {menuOpen && (
        <div style={{ background: "rgba(13,12,17,0.98)", borderTop: "1px solid rgba(168,85,247,0.2)", padding: "1rem 2rem 1.5rem" }}>
          <button onClick={() => scrollTo("#overview")} style={{ display: "block", width: "100%", textAlign: "left", background: "none", border: "none", cursor: "pointer", padding: "10px 0", fontFamily: "'Space Mono', monospace", fontSize: 13, fontWeight: 700, letterSpacing: 1, textTransform: "uppercase", color: active === "overview" ? "#D6AB39" : "rgba(255,255,255,0.7)", borderBottom: "1px solid rgba(255,255,255,0.07)" }}>Overview</button>
          {NAV_GROUPS.map(g => (
            <React.Fragment key={g.label}>
              <div style={{ fontFamily: "'Space Mono', monospace", fontSize: 9, color: "rgba(168,85,247,0.6)", letterSpacing: 3, textTransform: "uppercase", padding: "12px 0 4px" }}>{g.label}</div>
              {g.items.map(item => (
                <button key={item.href} onClick={() => scrollTo(item.href)} style={{ display: "block", width: "100%", textAlign: "left", background: "none", border: "none", cursor: "pointer", padding: "9px 0 9px 12px", fontFamily: "'Space Mono', monospace", fontSize: 12, fontWeight: 700, letterSpacing: 1, textTransform: "uppercase", color: active === item.href.slice(1) ? "#D6AB39" : "rgba(255,255,255,0.65)", borderBottom: "1px solid rgba(255,255,255,0.05)" }}>{item.label}</button>
              ))}
            </React.Fragment>
          ))}
        </div>
      )}

      <style>{`
        @media (max-width: 900px) {
          .nav-desktop { display: none !important; }
          .nav-mobile-btn { display: block !important; }
        }
      `}</style>
    </nav>
  );
}

Object.assign(window, { Nav });
