const NAV_ITEMS = [
  { id: "performance", label: "Performance" },
  { id: "design", label: "Design" },
  { id: "build", label: "The Build" },
  { id: "cities", label: "Cities" },
  { id: "sepang", label: "Sepang" },
  { id: "gallery", label: "Gallery" },
  { id: "specs", label: "Specs" },
];

function Nav() {
  const [active, setActive] = useState("");
  const [open, setOpen] = useState(false);
  // Hero video mute toggle. Video ALWAYS plays on loop — this only controls audio.
  // Default: muted (browsers require this for autoplay anyway). Click to unmute.
  const [muted, setMuted] = useState(() => {
    try { return localStorage.getItem("heroVideoMuted") !== "false"; } catch { return true; }
  });

  // Sync any hero videos to current muted state. Video keeps playing on loop
  // regardless — we only flip the muted property.
  useEffect(() => {
    const sync = () => {
      document.querySelectorAll("[data-hero-video]").forEach((v) => {
        v.muted = muted;
        v.volume = muted ? 0 : 1; // belt-and-braces against stuck volume
        // Keep playing — never pause from mute control.
        if (v.paused) {
          const p = v.play();
          if (p && p.catch) p.catch(() => {});
        }
      });
    };
    sync();
    // Re-sync when DOM changes (variant switches mount new video elements)
    const mo = new MutationObserver(sync);
    mo.observe(document.body, { childList: true, subtree: true });
    return () => mo.disconnect();
  }, [muted]);

  const toggleMute = () => {
    const next = !muted;
    setMuted(next);
    try { localStorage.setItem("heroVideoMuted", String(next)); } catch {}
  };

  useEffect(() => {
    const ids = NAV_ITEMS.map((i) => i.id);
    const els = ids.map((id) => document.getElementById(id)).filter(Boolean);
    if (!els.length) return;

    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) setActive(e.target.id);
        });
      },
      { rootMargin: "-40% 0px -50% 0px", threshold: 0 }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);

  return (
    <nav className="n-nav">
      <div className="n-nav-inner">
        <a href="#top" className="n-plate" aria-label="Home — Hyundai N · Never Just Drive">
          <span className="n-plate-prefix">Hyundai</span>
          <span className="n-plate-n">N</span>
          <span className="n-plate-num">Never Just Drive</span>
        </a>

        <ul className="n-links">
          {NAV_ITEMS.map((it) => (
            <li key={it.id}>
              <a
                href={`#${it.id}`}
                className={"n-link " + (active === it.id ? "is-active" : "")}
              >
                {it.label}
              </a>
            </li>
          ))}
        </ul>

        <button
          className="n-mute"
          aria-label={muted ? "Unmute hero video" : "Mute hero video"}
          aria-pressed={!muted}
          onClick={toggleMute}
          title={muted ? "Unmute" : "Mute"}
        >
          {muted ? (
            // Speaker with X (muted)
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M11 5L6 9H2v6h4l5 4V5z"/>
              <line x1="22" y1="9" x2="16" y2="15"/>
              <line x1="16" y1="9" x2="22" y2="15"/>
            </svg>
          ) : (
            // Speaker with sound waves (unmuted)
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
              <path d="M11 5L6 9H2v6h4l5 4V5z"/>
              <path d="M15.54 8.46a5 5 0 0 1 0 7.07"/>
              <path d="M19.07 4.93a10 10 0 0 1 0 14.14"/>
            </svg>
          )}
        </button>

        <button
          className="n-burger"
          aria-label="Menu"
          aria-expanded={open}
          onClick={() => setOpen((v) => !v)}
        >
          <span /><span /><span />
        </button>
      </div>

      {open && (
        <div className="n-mobile" onClick={() => setOpen(false)}>
          {NAV_ITEMS.map((it) => (
            <a key={it.id} href={`#${it.id}`} className="n-mobile-link">
              {it.label}
            </a>
          ))}
        </div>
      )}

      <style>{`
        .n-nav {
          position: fixed;
          top: 0; left: 0; right: 0;
          z-index: 50;
          background: color-mix(in oklab, var(--bg-0) 55%, transparent);
          backdrop-filter: blur(14px) saturate(140%);
          -webkit-backdrop-filter: blur(14px) saturate(140%);
          border-bottom: 1px solid color-mix(in oklab, var(--line) 70%, transparent);
        }
        .n-nav-inner {
          max-width: var(--max-w);
          margin: 0 auto;
          padding: 14px var(--gutter);
          display: flex;
          align-items: center;
          justify-content: space-between;
          gap: 24px;
        }
        .n-plate {
          display: inline-flex;
          align-items: baseline;
          gap: 8px;
          font-family: var(--font-display);
          font-size: 16px;
          letter-spacing: 0.04em;
          text-transform: uppercase;
          white-space: nowrap;
        }
        .n-plate-num { color: var(--ink-1); }
        .n-plate-prefix { color: var(--ink-0); }
        .n-plate-n {
          color: var(--accent);
          font-size: 22px;
          padding: 0 4px;
        }
        .n-links {
          display: flex;
          gap: 4px;
          list-style: none;
        }
        .n-link {
          font-family: var(--font-mono);
          font-size: 11px;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          color: var(--ink-2);
          padding: 8px 14px;
          position: relative;
          transition: color 0.2s;
        }
        .n-link:hover { color: var(--ink-0); }
        .n-link.is-active { color: var(--ink-0); }
        .n-link.is-active::after {
          content: "";
          position: absolute;
          left: 14px; right: 14px;
          bottom: 2px;
          height: 1px;
          background: var(--accent);
        }
        .n-burger {
          display: none;
          flex-direction: column;
          gap: 4px;
          padding: 8px;
        }
        .n-burger span {
          width: 22px; height: 1.5px;
          background: var(--ink-0);
          display: block;
        }
        .n-mute {
          display: inline-flex;
          align-items: center;
          justify-content: center;
          width: 32px;
          height: 32px;
          color: var(--ink-2);
          border: 1px solid var(--line);
          border-radius: 50%;
          background: transparent;
          margin-left: 4px;
          cursor: pointer;
          transition: color 0.18s, border-color 0.18s, background 0.18s;
        }
        .n-mute:hover { color: var(--ink-0); border-color: var(--ink-2); }
        .n-mute[aria-pressed="true"] {
          color: var(--accent);
          border-color: var(--accent);
        }
        .n-mobile {
          display: none;
          position: absolute; top: 100%; left: 0; right: 0;
          background: var(--bg-1);
          border-bottom: 1px solid var(--line);
          padding: 12px var(--gutter) 20px;
          flex-direction: column;
          gap: 4px;
        }
        .n-mobile-link {
          font-family: var(--font-mono);
          font-size: 12px;
          letter-spacing: 0.18em;
          text-transform: uppercase;
          padding: 14px 0;
          color: var(--ink-1);
          border-bottom: 1px solid var(--line);
        }
        @media (max-width: 720px) {
          .n-links { display: none; }
          .n-burger { display: flex; }
          .n-mobile { display: flex; }
        }
      `}</style>
    </nav>
  );
}

window.Nav = Nav;
