// Top nav — minimal, sticky, with backdrop blur.
function Nav() {
  const [scrolled, setScrolled] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 20);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const items = [
    { label: 'How it works', href: '#how' },
    { label: 'Signals', href: '#signals' },
    { label: 'Use cases', href: '#usecases' },
    { label: 'FAQ', href: '#faq' },
  ];

  return (
    <nav style={{
      position: 'fixed', top: 0, left: 0, right: 0, zIndex: 50,
      backdropFilter: 'blur(14px) saturate(140%)',
      WebkitBackdropFilter: 'blur(14px) saturate(140%)',
      background: scrolled ? 'color-mix(in srgb, var(--bg) 78%, transparent)' : 'transparent',
      borderBottom: scrolled ? '1px solid var(--rule)' : '1px solid transparent',
      transition: 'background 220ms var(--ease-out), border-color 220ms var(--ease-out)',
    }}>
      <div className="container" style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        height: 64,
      }}>
        <Wordmark />
        <div className="hide-sm" style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
          {items.map(it => (
            <a key={it.href} href={it.href} className="ulink" style={{
              fontFamily: 'var(--font-mono)', fontSize: 12,
              letterSpacing: '0.04em', color: 'var(--fg-mute)',
            }}>{it.label}</a>
          ))}
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <ThemeToggle />
          <a href="#book" className="btn btn-primary" style={{ padding: '10px 16px', fontSize: 12 }}>
            Book a founder demo
            <ArrowRight size={12} />
          </a>
        </div>
      </div>
    </nav>
  );
}

// Three-way light/dark/system theme toggle. Persists to localStorage('theme')
// and writes data-theme on <html>. When 'system', listens to the OS color
// scheme and re-resolves on changes. The FOUC bootstrap in index.html sets
// the initial data-theme; this component owns updates after mount.
function ThemeToggle() {
  const [mode, setMode] = React.useState(() => {
    try {
      const v = localStorage.getItem('theme');
      if (v === 'light' || v === 'dark' || v === 'system') return v;
    } catch (e) {}
    return 'system';
  });

  const applyResolved = React.useCallback((m) => {
    const resolved = m === 'system'
      ? (window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light')
      : m;
    if (resolved === 'light') {
      document.documentElement.setAttribute('data-theme', 'light');
    } else {
      document.documentElement.removeAttribute('data-theme');
    }
    // Keep the tweaks-panel theme state in sync so that future tweak edits
    // (accent, font, etc.) don't snap the theme back via applyTweaks.
    if (typeof window.__bpSyncTheme === 'function') {
      window.__bpSyncTheme(resolved);
    }
  }, []);

  // Apply on mount + whenever mode changes; persist to localStorage.
  React.useEffect(() => {
    try { localStorage.setItem('theme', mode); } catch (e) {}
    applyResolved(mode);
  }, [mode, applyResolved]);

  // While in 'system', follow OS preference changes live.
  React.useEffect(() => {
    if (mode !== 'system') return;
    const mql = window.matchMedia('(prefers-color-scheme: dark)');
    const onChange = () => applyResolved('system');
    mql.addEventListener('change', onChange);
    return () => mql.removeEventListener('change', onChange);
  }, [mode, applyResolved]);

  const options = [
    { value: 'light',  label: 'Light theme',  icon: <SunIcon /> },
    { value: 'system', label: 'System theme', icon: <SystemIcon /> },
    { value: 'dark',   label: 'Dark theme',   icon: <MoonIcon /> },
  ];

  return (
    <div
      role="radiogroup"
      aria-label="Color theme"
      className="hide-sm"
      style={{
        display: 'flex',
        alignItems: 'center',
        gap: 0,
        padding: 2,
        border: '1px solid var(--rule-strong)',
        borderRadius: 999,
        background: 'transparent',
        fontFamily: 'var(--font-mono)',
      }}
    >
      {options.map((o) => {
        const active = mode === o.value;
        return (
          <button
            key={o.value}
            type="button"
            role="radio"
            aria-checked={active}
            aria-label={o.label}
            title={o.label}
            onClick={() => setMode(o.value)}
            style={{
              width: 28, height: 24,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              border: 0,
              borderRadius: 999,
              background: active ? 'var(--bg-3)' : 'transparent',
              color: active ? 'var(--fg)' : 'var(--fg-mute)',
              cursor: 'pointer',
              padding: 0,
              transition: 'background 200ms var(--ease-out), color 200ms var(--ease-out)',
            }}
            onMouseEnter={(e) => { if (!active) e.currentTarget.style.color = 'var(--fg)'; }}
            onMouseLeave={(e) => { if (!active) e.currentTarget.style.color = 'var(--fg-mute)'; }}
          >
            {o.icon}
          </button>
        );
      })}
    </div>
  );
}

// Inline SVG icons. Stroke uses currentColor so they pick up the button color.
function SunIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
         aria-hidden="true">
      <circle cx="12" cy="12" r="4" />
      <path d="M12 2v2" />
      <path d="M12 20v2" />
      <path d="m4.93 4.93 1.41 1.41" />
      <path d="m17.66 17.66 1.41 1.41" />
      <path d="M2 12h2" />
      <path d="M20 12h2" />
      <path d="m4.93 19.07 1.41-1.41" />
      <path d="m17.66 6.34 1.41-1.41" />
    </svg>
  );
}

function MoonIcon() {
  return (
    <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="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
    </svg>
  );
}

function SystemIcon() {
  return (
    <svg width="13" height="13" viewBox="0 0 24 24" fill="none"
         stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"
         aria-hidden="true">
      <rect x="2" y="4" width="20" height="14" rx="2" />
      <path d="M8 21h8" />
      <path d="M12 18v3" />
    </svg>
  );
}

window.Nav = Nav;
