// nav.jsx — sticky glass nav, mono indexed links, scroll-spy active state
const { useState: useStateNav, useEffect: useEffectNav } = React;

const NAV_ITEMS = [
  { idx: "01", label: "about", id: "about" },
  { idx: "02", label: "focus", id: "focus" },
  { idx: "03", label: "projects", id: "projects" },
  { idx: "04", label: "writing", id: "articles" },
  { idx: "05", label: "status", id: "status" },
];

function Nav() {
  const [scrolled, setScrolled] = useStateNav(false);
  const [open, setOpen] = useStateNav(false);
  const [active, setActive] = useStateNav("");

  useEffectNav(() => {
    const onScroll = () => setScrolled(window.scrollY > 16);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();

    // scroll-spy: highlight the section nearest the top third of the viewport
    const ids = [...NAV_ITEMS.map((n) => n.id), "contact"];
    const spy = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => { if (e.isIntersecting) setActive(e.target.id); });
      },
      { rootMargin: "-32% 0px -60% 0px", threshold: 0 }
    );
    ids.forEach((id) => { const el = document.getElementById(id); if (el) spy.observe(el); });
    return () => { window.removeEventListener("scroll", onScroll); spy.disconnect(); };
  }, []);

  const go = (e, id) => {
    e.preventDefault();
    setOpen(false);
    const el = document.getElementById(id);
    if (el) {
      const reduce = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
      window.scrollTo({ top: el.getBoundingClientRect().top + window.scrollY - 72, behavior: reduce ? "auto" : "smooth" });
    }
  };

  return (
    <nav className={"nav" + (scrolled ? " scrolled" : "")}>
      <div className="nav-inner">
        <a className="brand" href="#top" onClick={(e) => go(e, "top")}>
          <span className="mark">s/</span>
          <span className="wm">sirucka<span className="cz">.cz</span><span className="cursor"></span></span>
        </a>
        <div className="nav-links">
          {NAV_ITEMS.map((n) => (
            <a key={n.id} href={"#" + n.id} onClick={(e) => go(e, n.id)} className={active === n.id ? "active" : ""}>
              <span className="idx">{n.idx}</span>{n.label}
            </a>
          ))}
        </div>
        <a className="nav-cta" href="#contact" onClick={(e) => go(e, "contact")}>[ contact ]</a>
        <button className="nav-burger" aria-label="Menu" onClick={() => setOpen((o) => !o)}>
          <i data-lucide={open ? "x" : "align-right"}></i>
        </button>
      </div>
      {open && (
        <div className="mobile-menu">
          {[...NAV_ITEMS, { idx: "06", label: "contact", id: "contact" }].map((n) => (
            <a key={n.id} href={"#" + n.id} onClick={(e) => go(e, n.id)}>
              <span className="idx">{n.idx}</span>{n.label}
            </a>
          ))}
        </div>
      )}
    </nav>
  );
}

window.Nav = Nav;
