// jsx/TopNav.jsx — sticky top nav with blurred backdrop, a full-bleed
// mega-menu panel that spans the viewport (links in columns under mono
// section headings + a featured promo card), and a grouped mobile drawer.
// The mega panel opens on hover or focus; closes on outside click / Esc /
// mouse-leave.
const { useState, useEffect, useRef } = React;

// Each nav item opens a mega panel made of `columns` (a heading + a list of
// items) and an optional right-hand `promo` card. Items may carry a `desc`
// subtitle and `arrow: true` to mark a featured link (magenta + ↗ icon).
// Breadcrumb label shown after the brand, keyed by the page's `current` prop.
const PATH_LABELS = {
  home: "Studio",
  services: "Services",
  apps: "Custom AI applications",
  web: "Web platforms",
  consulting: "AI consulting",
  "case-studies": "Case studies",
  case: "Case · Cybersecurity",
  resources: "Resources",
  "ai-agents": "Zarco Agents",
  about: "About",
  privacy: "Privacy",
  cookies: "Cookies",
  terms: "Terms",
  accessibility: "Accessibility",
  "ai-use": "How we use AI",
  "modern-slavery": "Modern slavery",
};

// One-pager config (2026-06-11 rebuild: the site is homepage-only while the
// redesign lands; pages return one by one with new content. Dropdown/mega
// machinery below is kept — give an item `columns` and it comes back).
const NAV_CONFIG = [
  { label: "What we build", href: "index.html#what-we-do" },
  { label: "The console",   href: "index.html#proof" },
  { label: "Live systems",  href: "index.html#work" },
];

// Site-wide marquee that sits above the nav island on every page. Not sticky —
// it scrolls away while the nav stays pinned. (Previously lived on the homepage
// only, inside App.jsx.)
const TICKER_ITEMS = ["Production AI", "Engineered, not prompted", "Agents with memory", "Versioned skills", "MCP integrations", "Human in the loop", "UK-based studio"];
function TopNavTicker() {
  const row = TICKER_ITEMS.flatMap((t, i) => [
    <span key={"t" + i}>{t}</span>,
    <span key={"s" + i} className="topnav-ticker-star">✺</span>,
  ]);
  return (
    <div className="topnav-ticker" aria-hidden="true">
      <div className="topnav-ticker-track">{row}{row}</div>
    </div>
  );
}

function TopNav({ current = "home" }) {
  const [scrolled, setScrolled] = useState(false);
  const [drawerOpen, setDrawerOpen] = useState(false);
  const [openDropdown, setOpenDropdown] = useState(null);
  const navRef = useRef(null);
  // Hover-close is debounced so a brief gap between the trigger and the
  // panel (caused by the 8px float gap) doesn't snap the menu shut.
  const closeTimer = useRef(null);

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

  // The page renders client-side, so the browser's native jump to a #hash on
  // load fires before that section exists in the DOM and silently fails (you
  // land at the top instead of the linked section). Re-run the scroll once the
  // tree has mounted, retrying briefly until the target appears, and offset for
  // the sticky nav so the heading isn't hidden underneath it.
  useEffect(() => {
    const hash = window.location.hash;
    if (!hash || hash.length < 2) return;
    const id = decodeURIComponent(hash.slice(1));
    let tries = 0;
    const scrollToTarget = () => {
      const el = document.getElementById(id);
      if (el) {
        const top = el.getBoundingClientRect().top + window.scrollY - 88;
        window.scrollTo({ top, behavior: "auto" });
      } else if (tries++ < 40) {
        setTimeout(scrollToTarget, 50);
      }
    };
    scrollToTarget();
  }, []);

  useEffect(() => {
    if (!openDropdown) return;
    const onKey = (e) => { if (e.key === "Escape") setOpenDropdown(null); };
    const onClick = (e) => {
      if (navRef.current && !navRef.current.contains(e.target)) {
        setOpenDropdown(null);
      }
    };
    document.addEventListener("keydown", onKey);
    document.addEventListener("click", onClick);
    return () => {
      document.removeEventListener("keydown", onKey);
      document.removeEventListener("click", onClick);
    };
  }, [openDropdown]);

  const requestOpen = (label) => {
    if (closeTimer.current) { clearTimeout(closeTimer.current); closeTimer.current = null; }
    setOpenDropdown(label);
  };
  const requestClose = () => {
    if (closeTimer.current) clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => {
      setOpenDropdown(null);
      closeTimer.current = null;
    }, 140);
  };
  const toggle = (label) => {
    if (openDropdown === label) setOpenDropdown(null);
    else setOpenDropdown(label);
  };

  const activeItem = NAV_CONFIG.find((i) => i.label === openDropdown) || null;

  return (
    <React.Fragment>
    {/* TopNavTicker retired 2026-06-11 (premium redesign — the marquee read as
        the old "operator" look). Component kept below for easy restore. */}
    <nav className="topnav" data-scrolled={scrolled ? "true" : "false"} ref={navRef}>
      <div className="topnav-bar">
        <a href="index.html" className="topnav-brand" aria-label="Zarco home">
          <span className="topnav-brand-word">Zarco</span>
          <span className="topnav-brand-dot">.</span>
        </a>
        <div className="topnav-links">
          {NAV_CONFIG.map((item) =>
            item.href && !item.columns ? (
              <a
                key={item.label}
                href={item.href}
                className={"topnav-link" + (item.flagship ? " topnav-link-flagship" : "")}
              >
                {item.label}
              </a>
            ) : (
              <NavTrigger
                key={item.label}
                item={item}
                isOpen={openDropdown === item.label}
                onEnter={() => requestOpen(item.label)}
                onLeave={requestClose}
                onToggle={() => toggle(item.label)}
              />
            )
          )}
        </div>
        <div className="topnav-actions">
          <a href="#login" className="topnav-login">Log in</a>
          <a href="index.html#contact" className="btn topnav-cta">
            Book a call
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M7 17L17 7M7 7h10v10"/></svg>
          </a>
          <button className="topnav-menu" aria-label="Menu" aria-expanded={drawerOpen} onClick={() => setDrawerOpen(!drawerOpen)}>
            <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><line x1="3" y1="7" x2="21" y2="7"/><line x1="3" y1="17" x2="21" y2="17"/></svg>
          </button>
        </div>
      </div>

      {activeItem && (
        <React.Fragment>
          <div className="topnav-scrim" aria-hidden="true" onClick={() => setOpenDropdown(null)} />
          <div
            className="topnav-mega"
            role="menu"
            onMouseEnter={() => requestOpen(activeItem.label)}
            onMouseLeave={requestClose}
          >
            <div className="topnav-mega-inner">
              <div className="topnav-mega-cols">
                {activeItem.columns.map((col) => (
                  <div key={col.heading} className="topnav-mega-col">
                    <div className="topnav-mega-heading">{col.heading}</div>
                    <ul className="topnav-mega-list">
                      {col.items.map((i) => (
                        <li key={i.label}>
                          <a
                            href={i.href}
                            className={"topnav-mega-link" + (i.arrow ? " topnav-mega-link-feat" : "")}
                            role="menuitem"
                          >
                            <span className="topnav-mega-link-label">
                              {i.label}
                              {i.arrow && (
                                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                                  <path d="M7 17L17 7M7 7h10v10"/>
                                </svg>
                              )}
                            </span>
                            {i.desc && <span className="topnav-mega-link-desc">{i.desc}</span>}
                          </a>
                        </li>
                      ))}
                    </ul>
                  </div>
                ))}
              </div>
              {activeItem.promo && (
                <div className="topnav-mega-promo">
                  <div className="topnav-mega-promo-title">{activeItem.promo.title}</div>
                  <div className="topnav-mega-promo-body">{activeItem.promo.body}</div>
                  <a href={activeItem.promo.cta.href} className="topnav-mega-promo-cta">
                    {activeItem.promo.cta.label}
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M7 17L17 7M7 7h10v10"/></svg>
                  </a>
                </div>
              )}
            </div>
          </div>
        </React.Fragment>
      )}

      {drawerOpen && (
        <div className="topnav-drawer" onClick={() => setDrawerOpen(false)}>
          <div className="topnav-drawer-inner" onClick={(e) => e.stopPropagation()}>
            {NAV_CONFIG.map((item) =>
              item.href && !item.columns ? (
                <a
                  key={item.label}
                  href={item.href}
                  className="topnav-drawer-sublink topnav-drawer-sublink-feat topnav-drawer-toplink"
                >
                  {item.label}
                </a>
              ) : (
                <div key={item.label} className="topnav-drawer-group">
                  <div className="topnav-drawer-group-label">{item.label}</div>
                  {item.columns.flatMap((col) => col.items).map((i) => (
                    <a key={i.label} href={i.href} className={"topnav-drawer-sublink" + (i.arrow ? " topnav-drawer-sublink-feat" : "")}>
                      {i.label}
                    </a>
                  ))}
                </div>
              )
            )}
            <a href="#login" className="btn btn-ghost topnav-drawer-login">Log in</a>
            <a href="index.html#contact" className="btn btn-ink topnav-drawer-cta">Book a call</a>
          </div>
        </div>
      )}
    </nav>
    </React.Fragment>
  );
}

function NavTrigger({ item, isOpen, onEnter, onLeave, onToggle }) {
  return (
    <div
      className="topnav-dropdown-wrap"
      onMouseEnter={onEnter}
      onMouseLeave={onLeave}
    >
      <button
        type="button"
        className="topnav-trigger"
        data-open={isOpen ? "true" : "false"}
        onClick={onToggle}
        onFocus={onEnter}
        aria-expanded={isOpen}
        aria-haspopup="menu"
      >
        <span>{item.label}</span>
        <svg className="topnav-trigger-chev" width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
          <polyline points="6 9 12 15 18 9"/>
        </svg>
      </button>
    </div>
  );
}

const topnavCss = `
/* ── Site-wide marquee (above the nav island, not sticky) ── */
.topnav-ticker { background: var(--ink); color: var(--paper); overflow: hidden; padding: 8px 0; }
.topnav-ticker-track {
  display: inline-flex; gap: 34px; white-space: nowrap;
  font-family: var(--font-mono); font-size: 11px; letter-spacing: .12em;
  text-transform: uppercase; color: rgba(250, 250, 247, .72);
  animation: topnav-ticker-scroll 32s linear infinite;
}
.topnav-ticker-star { color: var(--magenta); }
@keyframes topnav-ticker-scroll { from { transform: translateX(0); } to { transform: translateX(-50%); } }
@media (prefers-reduced-motion: reduce) { .topnav-ticker-track { animation: none; } }

/* ── Floating capsule nav (Wispr-style island) ─────────────
   A detached, bordered "island" that floats with a gap from the
   top + sides. The sticky wrapper itself is transparent and
   click-through; only the capsule (and its menus) take pointer
   events, so content scrolls cleanly beneath the side gutters. */
.topnav {
  position: sticky; top: 0; z-index: 60;
  padding: 16px 24px 0;
  background: transparent;
  /* Must stay none: a backdrop-filter here (left over in older baked CSS)
     would make .topnav the containing block for the fixed scrim and clip the
     page-wide fade to the nav's own box. */
  backdrop-filter: none;
  -webkit-backdrop-filter: none;
  pointer-events: none;
}
.topnav > * { pointer-events: auto; }
.topnav-bar {
  position: relative;
  z-index: 2;
  max-width: 1120px;
  margin: 0 auto;
  height: 66px;
  display: grid;
  grid-template-columns: auto 1fr auto;
  align-items: center;
  gap: 24px;
  padding: 0 12px 0 26px;
  background: rgba(250, 250, 247, 0.8);
  -webkit-backdrop-filter: blur(16px);
  backdrop-filter: blur(16px);
  border: 1px solid var(--ink-10);
  border-radius: 999px;
  box-shadow: 0 14px 40px -18px rgba(14, 14, 14, 0.18);
  transition: box-shadow var(--dur-ui) var(--ease), border-color var(--dur-ui) var(--ease);
}
.topnav[data-scrolled="true"] .topnav-bar {
  border-color: var(--ink-20);
  box-shadow: 0 18px 48px -18px rgba(14, 14, 14, 0.26);
}
.topnav-brand {
  display: inline-flex; align-items: baseline;
  font-family: var(--font-display);
  font-weight: 500; font-size: 23px; letter-spacing: -0.01em;
  color: var(--ink); text-decoration: none;
}
.topnav-brand:hover { color: var(--ink); text-decoration: none; }
.topnav-brand-dot { color: var(--magenta); }
.topnav-links { display: flex; gap: 4px; justify-content: center; align-items: center; }
.topnav-link {
  font-family: var(--font-display);
  font-size: 16px; color: var(--ink); text-decoration: none; font-weight: 400;
  letter-spacing: 0;
  padding: 8px 14px; border-radius: var(--radius-pill); line-height: 1;
  transition: background 140ms var(--ease), color 140ms var(--ease);
}
.topnav-link:hover { color: var(--ink); background: var(--ink-04); text-decoration: none; }
.topnav-link-flagship {
  display: inline-flex; align-items: center; gap: 7px; font-weight: 600;
}
.topnav-link-flagship::before {
  content: ""; width: 6px; height: 6px; border-radius: 50%;
  background: var(--magenta); flex-shrink: 0;
}
.topnav-drawer-toplink { font-size: 18px; }
.topnav-actions { display: flex; gap: 8px; align-items: center; }
.topnav-login {
  font-family: var(--font-display);
  font-size: 16px; font-weight: 400; color: var(--ink);
  text-decoration: none; padding: 9px 14px; border-radius: var(--radius-pill);
  transition: color 140ms var(--ease), background 140ms var(--ease);
}
.topnav-login:hover { color: var(--ink); background: var(--ink-04); text-decoration: none; }
.topnav-cta {
  padding: 11px 20px; font-size: 15px; font-weight: 600;
  border: none; border-radius: var(--radius-pill);
  background: var(--magenta); color: #fff;
  display: inline-flex; align-items: center; gap: 7px;
  text-decoration: none;
  transition: background 140ms var(--ease), transform 140ms var(--ease);
}
.topnav-cta:hover {
  background: var(--magenta-deep); color: #fff; text-decoration: none; transform: translateY(-1px);
  box-shadow: 0 6px 24px -6px rgba(255, 0, 102, 0.45), 0 0 0 4px rgba(255, 0, 102, 0.08);
}
.topnav-cta svg { transition: transform var(--dur-micro) var(--ease); }
.topnav-cta:hover svg { transform: translate(2px, -2px); }
.topnav-menu {
  display: none;
  background: transparent; border: 1px solid var(--ink-20);
  width: 42px; height: 42px; border-radius: 50%;
  align-items: center; justify-content: center;
  color: var(--ink); cursor: pointer;
}

/* ── Dropdown trigger + wrapper ────────────────────── */
.topnav-dropdown-wrap {
  position: static;
  display: inline-flex;
  align-items: center;
}
.topnav-trigger {
  appearance: none;
  background: none;
  border: none;
  font: inherit;
  font-family: var(--font-display);
  font-size: 16px;
  font-weight: 400;
  color: var(--ink);
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 14px;
  border-radius: var(--radius-pill);
  line-height: 1;
  cursor: pointer;
  transition: background 140ms var(--ease), color 140ms var(--ease);
}
.topnav-trigger:hover { background: var(--ink-04); }
.topnav-trigger[data-open="true"] { background: var(--magenta-wash); color: var(--magenta); }
.topnav-trigger-chev {
  transition: transform 200ms cubic-bezier(0.22, 1, 0.36, 1);
  opacity: 0.5;
}
.topnav-trigger:hover .topnav-trigger-chev { opacity: 0.9; }
.topnav-trigger[data-open="true"] .topnav-trigger-chev { transform: rotate(180deg); opacity: 1; }

/* ── Floating mega panel ───────────────────────────── */
/* Dim scrim over the page while the panel is open. */
.topnav-scrim {
  position: fixed;
  inset: 0;
  background: rgba(14, 14, 14, 0.20);
  -webkit-backdrop-filter: blur(1px);
  backdrop-filter: blur(1px);
  animation: topnav-scrim-in 220ms var(--ease) both;
  z-index: 0;
}
@keyframes topnav-scrim-in { from { opacity: 0; } to { opacity: 1; } }

/* Detached, bordered card — centred under the island with a gap. */
.topnav-mega {
  position: absolute;
  left: 0; right: 0; top: 100%;
  width: min(860px, calc(100vw - 48px));
  margin: 10px auto 0;
  background: var(--paper);
  border: 1px solid var(--ink-10);
  border-radius: 24px;
  box-shadow: 0 28px 60px -20px rgba(14, 14, 14, 0.28);
  animation: topnav-mega-in 220ms cubic-bezier(0.22, 1, 0.36, 1) both;
  z-index: 2;
  overflow: hidden;
}
@keyframes topnav-mega-in {
  from { opacity: 0; transform: translateY(-10px); }
  to   { opacity: 1; transform: translateY(0); }
}
.topnav-mega-inner {
  display: grid;
  grid-template-columns: 1fr 1fr minmax(200px, 240px);
  gap: 28px;
  padding: 26px 26px 28px;
  align-items: start;
}
.topnav-mega-cols {
  display: contents;
}
.topnav-mega-heading {
  font-size: 13px;
  letter-spacing: 0;
  text-transform: none;
  color: var(--ink-40);
  font-weight: 500;
  margin-bottom: 16px;
}
.topnav-mega-list {
  list-style: none;
  padding: 0; margin: 0;
  display: flex;
  flex-direction: column;
  gap: 2px;
}
.topnav-mega-link {
  display: block;
  padding: 10px 0;
  text-decoration: none;
  border-radius: 8px;
}
.topnav-mega-link:hover { text-decoration: none; }
.topnav-mega-link-label {
  display: inline-flex;
  align-items: center;
  gap: 7px;
  font-size: 15.5px;
  font-weight: 600;
  letter-spacing: -0.01em;
  color: var(--ink);
  transition: color 140ms var(--ease);
}
.topnav-mega-link:hover .topnav-mega-link-label { color: var(--magenta); }
.topnav-mega-link-label svg {
  opacity: 0.8;
  transition: transform 140ms var(--ease);
}
.topnav-mega-link:hover .topnav-mega-link-label svg { transform: translate(2px, -2px); }
.topnav-mega-link-desc {
  display: block;
  margin-top: 3px;
  font-size: 13px;
  font-weight: 450;
  line-height: 1.45;
  color: var(--ink-60);
}
.topnav-mega-link-feat .topnav-mega-link-label { color: var(--magenta); }

/* Right-hand promo card */
.topnav-mega-promo {
  background: var(--ink);
  color: var(--paper);
  border-radius: var(--radius-lg);
  padding: 24px 24px 22px;
  display: flex;
  flex-direction: column;
  gap: 10px;
  align-self: stretch;
  min-height: 100%;
}
.topnav-mega-promo-title {
  font-family: var(--font-display);
  font-size: 21px;
  font-weight: 400;
  letter-spacing: -0.015em;
  line-height: 1.15;
}
.topnav-mega-promo-body {
  font-size: 13px;
  line-height: 1.5;
  color: rgba(250, 250, 247, 0.66);
}
.topnav-mega-promo-cta {
  margin-top: auto;
  align-self: flex-start;
  display: inline-flex;
  align-items: center;
  gap: 7px;
  padding: 10px 16px;
  border-radius: var(--radius-pill);
  background: var(--paper-pure);
  color: var(--ink);
  font-size: 13.5px;
  font-weight: 600;
  text-decoration: none;
  transition: transform 140ms var(--ease);
}
.topnav-mega-promo-cta:hover { text-decoration: none; transform: translateY(-1px); }
.topnav-mega-promo-cta svg { transition: transform 140ms var(--ease); }
.topnav-mega-promo-cta:hover svg { transform: translate(2px, -2px); }

@media (prefers-reduced-motion: reduce) {
  .topnav-mega, .topnav-scrim { animation: none; }
}

/* ── Mobile drawer (floating card) ─────────────────── */
.topnav-drawer {
  position: absolute; left: 0; right: 0; top: 100%;
  margin: 10px 24px 0;
  background: var(--paper);
  border: 1px solid var(--ink-10);
  border-radius: 20px;
  box-shadow: 0 24px 48px -16px rgba(14, 14, 14, 0.24);
  max-height: calc(100vh - 110px);
  overflow-y: auto;
  z-index: 2;
}
.topnav-drawer-inner { display: flex; flex-direction: column; gap: 4px; padding: 18px 22px 22px; }
.topnav-drawer-link {
  padding: 14px 0; font-size: 18px; font-weight: 600; color: var(--ink);
  text-decoration: none; border-bottom: 1px solid var(--ink-10);
}
.topnav-drawer-group {
  padding: 16px 0;
  border-bottom: 1px solid var(--ink-10);
  display: flex;
  flex-direction: column;
  gap: 4px;
}
.topnav-drawer-group-label {
  font-size: 12px;
  letter-spacing: 0;
  text-transform: none;
  color: var(--ink-40);
  font-weight: 500;
  margin-bottom: 6px;
}
.topnav-drawer-sublink {
  padding: 8px 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--ink);
  text-decoration: none;
}
.topnav-drawer-sublink-feat { color: var(--magenta); font-weight: 600; }
.topnav-drawer-login {
  width: 100%;
  justify-content: center;
  margin-top: 16px;
}
.topnav-drawer-cta {
  width: 100%;
  justify-content: center;
  margin-top: 10px;
}

@media (max-width: 920px) {
  .topnav-bar { grid-template-columns: 1fr auto; height: 60px; padding: 0 12px 0 22px; gap: 12px; }
  .topnav-links { display: none; }
  .topnav-cta { display: none; }
  .topnav-login { display: none; }
  .topnav-menu { display: inline-flex; }
}
`;

window.TopNav = TopNav;
window.topnavCss = topnavCss;
