const Nav = () => {
  const [menuOpen, setMenuOpen] = React.useState(null);
  return (
    <nav style={{
      position: 'sticky', top: 0, zIndex: 40,
      background: 'rgba(7,7,10,0.72)',
      backdropFilter: 'saturate(1.4) blur(18px)',
      WebkitBackdropFilter: 'saturate(1.4) blur(18px)',
      borderBottom: '1px solid var(--line-1)',
    }}>
      <Container style={{
        display: 'grid',
        gridTemplateColumns: '1fr auto 1fr',
        alignItems: 'center',
        height: 64,
        gap: 24,
      }} wide>
        {/* LEFT — Brand */}
        <a href="/" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, justifySelf: 'start' }}>
          <BrandMark size={28} />
          <span style={{
            fontSize: 15, fontWeight: 700,
            letterSpacing: '-0.02em',
            color: 'var(--fg-1)',
          }}>
            AutoArchitect
          </span>
        </a>

        {/* CENTER — main menu */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 4, justifySelf: 'center' }} className="nav-desktop-links">
          <NavDropdown
            label="Products"
            open={menuOpen === 'products'}
            onToggle={() => setMenuOpen(menuOpen === 'products' ? null : 'products')}
          />
          <NavLink href="/gallery.html">Gallery</NavLink>
        </div>

        {/* RIGHT — theme toggle + GitHub CTA */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, justifySelf: 'end' }} className="nav-desktop-links">
          <ThemeToggle />
          <a href="https://github.com/syedia/autoarchitect" style={{ textDecoration: 'none' }}>
            <PrimaryBtn size="sm" icon={<I.github size={14} />}>Star on GitHub</PrimaryBtn>
          </a>
        </div>

        {/* Mobile menu button — occupies right grid cell on narrow screens */}
        <button className="nav-mobile-toggle" style={{
          display: 'none',
          alignItems: 'center', justifyContent: 'center',
          width: 38, height: 38, borderRadius: 8,
          background: 'var(--bg-2)',
          border: '1px solid var(--line-2)',
          color: 'var(--fg-1)',
          gridColumn: '3',
          justifySelf: 'end',
        }}>
          <I.menu size={18} />
        </button>
      </Container>
    </nav>
  );
};

const NavLink = ({ children, icon, href = '#' }) => {
  const [h, setH] = React.useState(false);
  return (
    <a href={href} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        display: 'inline-flex', alignItems: 'center', gap: 6,
        padding: '7px 12px',
        fontSize: 13.5, fontWeight: 500,
        color: h ? 'var(--fg-1)' : 'var(--fg-2)',
        borderRadius: 7,
        background: h ? 'var(--bg-2)' : 'transparent',
        transition: 'all 140ms',
      }}>
      {icon}
      {children}
    </a>
  );
};

const NavDropdown = ({ label, open, onToggle }) => {
  return (
    <div style={{ position: 'relative' }}>
      <button
        onClick={onToggle}
        style={{
          display: 'inline-flex', alignItems: 'center', gap: 6,
          padding: '7px 12px',
          fontSize: 13.5, fontWeight: 500,
          color: open ? 'var(--fg-1)' : 'var(--fg-2)',
          borderRadius: 7,
          background: open ? 'var(--bg-2)' : 'transparent',
        }}
      >
        {label}
        <I.chevron size={13} style={{ transition: 'transform 140ms', transform: open ? 'rotate(180deg)' : 'none' }} />
      </button>
      {open && (
        <div style={{
          position: 'absolute', top: 'calc(100% + 8px)', left: 0,
          width: 460,
          background: 'var(--bg-1)',
          border: '1px solid var(--line-2)',
          borderRadius: 12,
          padding: 8,
          boxShadow: '0 20px 50px -10px rgba(0,0,0,0.6)',
          display: 'grid',
          gridTemplateColumns: '1fr 1fr',
          gap: 4,
        }}>
          {[
            { icon: 'studio',  name: 'Studio',    href: '/',                desc: 'Self-hosted agent workspace', badge: 'Main' },
            { icon: 'cpu',     name: 'Code',      href: '/code.html',       desc: 'Agentic substrate that powers the platform' },
            { icon: 'docs',    name: 'Architecture', href: '/architecture.html', desc: 'Whitepapers documenting the platform' },
            { icon: 'chart',   name: 'Monitor',   href: '/monitor.html',    desc: 'Telemetry for your fleet' },
            { icon: 'saas',    name: 'Platform',  href: '/platform.html',   desc: 'Multi-tenant hub' },
            { icon: 'cloud',   name: 'Cloud',     href: '/cloud.html',      desc: 'Hosted & managed' },
            { icon: 'docs',    name: 'Skills',    href: '/skills.html',     desc: '370+ skills — 9 categories × 27 domains' },
            { icon: 'bolt',    name: 'Architect', href: '/agents.html',     desc: 'One autonomous agent, full-stack' },
          ].map((p) => {
            // Studio gets its own SVG mark (hex+S) — same one used in
            // the live Studio chrome — so the menu item visually matches
            // what the user sees once they land there. Other items keep
            // their lucide-style icons.
            const isStudio = p.icon === 'studio';
            const Icn = !isStudio ? (I[p.icon] || I.compass) : null;
            return (
              <a href={p.href || '#'} key={p.name} style={{
                display: 'flex', gap: 10, padding: 10,
                borderRadius: 8,
              }}
                onMouseEnter={(e) => { e.currentTarget.style.background = 'var(--bg-2)'; }}
                onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
              >
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: 'var(--bg-3)', border: '1px solid var(--line-2)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  color: 'var(--accent-2)', flexShrink: 0,
                }}>
                  {isStudio ? (
                    <window.StudioMark size={20} idKey={`nav-${p.name}`} />
                  ) : (
                    <Icn size={15} />
                  )}
                </div>
                <div>
                  <div style={{
                    fontSize: 13, fontWeight: 600, color: 'var(--fg-1)',
                    display: 'flex', alignItems: 'center', gap: 6,
                  }}>
                    {p.name}
                    {p.badge && (
                      <span style={{
                        fontSize: 9, color: 'var(--accent-2)',
                        fontFamily: 'var(--font-mono)',
                        padding: '1px 4px', borderRadius: 3,
                        background: 'var(--accent-soft)',
                        letterSpacing: '0.08em',
                      }}>{p.badge.toUpperCase()}</span>
                    )}
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--fg-3)', marginTop: 2 }}>{p.desc}</div>
                </div>
              </a>
            );
          })}
        </div>
      )}
    </div>
  );
};

/* Brand mark: a hexagonal blueprint-style logo. Not just the letter A. */
const BrandMark = ({ size = 28 }) => (
  <svg width={size} height={size} viewBox="0 0 32 32" fill="none"
    style={{ flexShrink: 0, filter: 'drop-shadow(0 0 8px var(--accent-glow))' }}>
    <defs>
      <linearGradient id="bm-g" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0" stopColor="var(--accent)" />
        <stop offset="1" stopColor="var(--accent-2)" />
      </linearGradient>
    </defs>
    {/* outer hex */}
    <path d="M16 2 L28 9 L28 23 L16 30 L4 23 L4 9 Z"
      fill="url(#bm-g)" opacity="0.18" />
    <path d="M16 2 L28 9 L28 23 L16 30 L4 23 L4 9 Z"
      stroke="url(#bm-g)" strokeWidth="1.5" />
    {/* inner triangle — the A */}
    <path d="M16 8 L23 22 L9 22 Z" stroke="var(--accent-2)" strokeWidth="1.5" fill="none" />
    <path d="M12.5 17 L19.5 17" stroke="var(--accent-2)" strokeWidth="1.5" />
    {/* center dot */}
    <circle cx="16" cy="16" r="1.5" fill="var(--accent-3)" />
  </svg>
);

/* Theme toggle — flips data-theme on <html>, synced to localStorage so
 * preference survives reloads. CSS variables already handle the rest. */
const ThemeToggle = () => {
  const [theme, setTheme] = React.useState(() =>
    document.documentElement.getAttribute('data-theme') || 'dark'
  );
  const flip = () => {
    const next = theme === 'dark' ? 'light' : 'dark';
    document.documentElement.setAttribute('data-theme', next);
    try { localStorage.setItem('aa-theme', next); } catch (_) {}
    setTheme(next);
  };
  const Icn = theme === 'dark' ? I.sun : I.moon;
  return (
    <button
      onClick={flip}
      title={theme === 'dark' ? 'Switch to light' : 'Switch to dark'}
      style={{
        width: 34, height: 34, borderRadius: 8,
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
        background: 'var(--bg-2)',
        border: '1px solid var(--line-2)',
        color: 'var(--fg-2)',
        cursor: 'pointer',
        transition: 'color 140ms, border-color 140ms',
      }}
      onMouseEnter={(e) => { e.currentTarget.style.color = 'var(--fg-1)'; e.currentTarget.style.borderColor = 'var(--line-3)'; }}
      onMouseLeave={(e) => { e.currentTarget.style.color = 'var(--fg-2)'; e.currentTarget.style.borderColor = 'var(--line-2)'; }}
    >
      <Icn size={15} />
    </button>
  );
};

Object.assign(window, { Nav, BrandMark, ThemeToggle });
