// Marketing site shell — top nav, sidebar, page-end nav, search palette
const { useState, useEffect, useMemo, useRef } = React;

/* ── Style sheets injected once ─────────────────────────────────────────── */
const shellCSS = `
/* ── Top nav ── */
.top-nav {
  position: fixed; top: 0; left: 0; right: 0;
  height: var(--topnav-h);
  z-index: 60;
  background: rgba(11,23,34,0.78);
  backdrop-filter: blur(14px);
  -webkit-backdrop-filter: blur(14px);
  border-bottom: 1px solid rgba(35,65,86,0.7);
}
.top-nav-inner {
  height: 100%;
  max-width: 1480px;
  margin: 0 auto;
  padding: 0 28px;
  display: flex; align-items: center; gap: 20px;
}
.wordmark {
  display: inline-flex; align-items: center; gap: 10px;
  font-family: var(--mono);
  font-size: 12px; font-weight: 600;
  letter-spacing: 0.18em;
  color: var(--ink);
  background: none; border: 0; cursor: pointer;
  padding: 0;
}
.wordmark-logo {
  width: 28px; height: 20px;
  object-fit: contain;
  flex-shrink: 0;
}
.top-nav-spacer { flex: 1; }
.top-nav-cta-secondary {
  font-size: 13px; color: var(--steel); cursor: pointer;
  background: none; border: 0; font-family: var(--sans);
  text-decoration: none;
}
.top-nav-cta-secondary:hover { color: var(--ink); }
.top-nav-cta {
  font-size: 13px; font-weight: 600;
  color: var(--bg);
  background: linear-gradient(180deg, #2dd4ee, var(--cyan));
  padding: 8px 14px;
  border-radius: 6px;
  border: 1px solid rgba(0,180,216,0.4);
  box-shadow: 0 8px 20px -8px rgba(0,180,216,0.55), inset 0 1px 0 rgba(255,255,255,0.3);
  cursor: pointer;
  font-family: var(--sans);
  text-decoration: none;
  display: inline-block;
}
.top-nav-cta:hover { filter: brightness(1.08); }
.kbd {
  font-family: var(--mono);
  font-size: 10px;
  border: 1px solid rgba(139,211,234,0.25);
  border-radius: 4px;
  padding: 1px 5px;
  color: var(--steel);
  background: rgba(20,40,56,0.6);
}
.search-trigger {
  display: inline-flex; align-items: center; gap: 8px;
  font-family: var(--mono);
  font-size: 11px; color: var(--steel);
  background: rgba(16,31,44,0.6);
  border: 1px solid var(--line);
  border-radius: 7px;
  padding: 7px 10px;
  cursor: pointer; min-width: 280px;
  transition: border-color .12s;
}
.search-trigger:hover { border-color: rgba(139,211,234,0.35); color: var(--ink); }
.search-trigger .search-placeholder { flex: 1; text-align: left; }

/* ── ⌘K Search palette ── */
.palette-overlay {
  position: fixed; inset: 0;
  background: rgba(6,14,22,0.72);
  backdrop-filter: blur(6px);
  -webkit-backdrop-filter: blur(6px);
  z-index: 200;
  display: flex; align-items: flex-start; justify-content: center;
  padding-top: 18vh;
}
.palette {
  width: 640px; max-width: calc(100vw - 32px);
  background: rgba(14,28,42,0.97);
  border: 1px solid rgba(139,211,234,0.22);
  border-radius: 14px;
  box-shadow: 0 40px 80px -20px rgba(0,0,0,0.7);
  overflow: hidden;
}
.palette-search {
  display: flex; align-items: center; gap: 12px;
  padding: 14px 16px;
  border-bottom: 1px solid rgba(139,211,234,0.12);
}
.palette-search svg { opacity: 0.5; flex-shrink: 0; }
.palette-search input {
  flex: 1;
  background: none; border: 0; outline: none;
  font-family: var(--sans); font-size: 15px;
  color: var(--ink);
}
.palette-search input::placeholder { color: var(--muted); }
.palette-results { padding: 6px; max-height: 380px; overflow-y: auto; }
.palette-row {
  display: flex; align-items: center; gap: 12px;
  padding: 10px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: background .1s;
}
.palette-row:hover, .palette-row.sel {
  background: rgba(0,180,216,0.09);
}
.palette-badge {
  font-family: var(--mono);
  font-size: 9px; letter-spacing: 0.14em; text-transform: uppercase;
  padding: 2px 7px; border-radius: 4px;
  flex-shrink: 0;
}
.palette-badge.nav { color: var(--cyan); background: rgba(0,180,216,0.09); border: 1px solid rgba(0,180,216,0.3); }
.palette-badge.faq { color: var(--green); background: rgba(89,217,157,0.09); border: 1px solid rgba(89,217,157,0.3); }
.palette-label { font-size: 13.5px; color: var(--ink); flex: 1; line-height: 1.35; }
.palette-group { font-family: var(--mono); font-size: 10px; color: var(--muted); flex-shrink: 0; }
.palette-empty { padding: 32px 16px; text-align: center; font-size: 13px; color: var(--muted); font-family: var(--mono); }

/* ── Sidebar ── */
.layout {
  display: grid;
  grid-template-columns: var(--sidebar-w) 1fr;
  min-height: 100vh;
  padding-top: var(--topnav-h);
}
.sidebar {
  position: fixed;
  top: var(--topnav-h); left: 0;
  width: var(--sidebar-w);
  height: calc(100vh - var(--topnav-h));
  background: rgba(11,23,34,0.7);
  backdrop-filter: blur(12px);
  -webkit-backdrop-filter: blur(12px);
  border-right: 1px solid var(--line);
  overflow-y: auto;
  padding: 22px 16px 32px;
  scrollbar-width: thin;
  scrollbar-color: rgba(139,211,234,0.18) transparent;
}
.sidebar::-webkit-scrollbar { width: 6px; }
.sidebar::-webkit-scrollbar-thumb { background: rgba(139,211,234,0.18); border-radius: 4px; }

.sb-tagline {
  font-family: var(--mono);
  font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase;
  color: rgba(184,202,215,0.7);
  margin: 4px 10px 22px; line-height: 1.5;
}
.sb-tagline .tag-accent { color: var(--cyan); }

.nav-section { margin-bottom: 22px; }
.nav-section-label {
  font-family: var(--mono);
  font-size: 10px; letter-spacing: 0.15em; text-transform: uppercase;
  color: rgba(184,202,215,0.6);
  padding: 0 12px; margin-bottom: 6px;
  display: flex; align-items: center; gap: 8px;
}
.nav-section-label .line {
  flex: 1; height: 1px;
  background: linear-gradient(90deg, rgba(184,202,215,0.18), transparent);
}
.nav-link {
  display: flex; align-items: center; gap: 10px;
  width: 100%; padding: 9px 12px; border-radius: 7px;
  font-size: 13.5px; color: var(--steel);
  border: 1px solid transparent; cursor: pointer;
  background: none; font-family: var(--sans); text-align: left;
  transition: color .12s, background .12s, border-color .12s;
  margin-bottom: 1px;
}
.nav-link:hover { color: var(--ink); background: rgba(20,40,56,0.5); }
.nav-link.active {
  color: var(--cyan); background: rgba(0,180,216,0.08);
  border-color: rgba(0,180,216,0.2); font-weight: 500;
}
.nav-link .glyph {
  width: 16px; height: 16px;
  display: inline-flex; align-items: center; justify-content: center;
  opacity: 0.55;
}
.nav-link.active .glyph { opacity: 1; color: var(--cyan); }
.nav-link .badge {
  margin-left: auto; font-family: var(--mono);
  font-size: 9px; letter-spacing: 0.08em; padding: 1px 5px;
  border-radius: 3px; background: rgba(139,211,234,0.08);
  color: var(--haze); border: 1px solid rgba(139,211,234,0.18);
}
.nav-link.docs-link { color: var(--haze); font-style: italic; }
.nav-link.docs-link::after { content: '↗'; margin-left: auto; font-style: normal; opacity: 0.6; }

.sb-footer {
  margin-top: auto; padding: 18px 12px 0;
  border-top: 1px solid var(--line); display: grid; gap: 6px;
}
.sb-footer a {
  font-family: var(--mono); font-size: 10px; letter-spacing: 0.08em; color: var(--muted);
}
.sb-footer a:hover { color: var(--ink); }

/* ── Main area ── */
.main {
  grid-column: 2; min-width: 0;
  padding: 36px 56px 96px;
  max-width: 1200px; width: 100%;
}
.section-wrap { animation: fadein .26s ease-out both; }
@keyframes fadein {
  from { opacity: 0; transform: translateY(6px); }
  to   { opacity: 1; transform: translateY(0); }
}

/* ── Page header ── */
.page-eyebrow {
  font-family: var(--mono); font-size: 10px; letter-spacing: 0.2em;
  text-transform: uppercase; color: var(--cyan); margin-bottom: 14px;
  display: inline-flex; align-items: center; gap: 10px;
}
.page-eyebrow::before {
  content: ''; width: 18px; height: 1px; background: var(--cyan); display: inline-block;
}
.page-title {
  font-family: var(--serif); font-weight: 600; font-size: 56px;
  line-height: 1.05; letter-spacing: -0.015em; color: var(--ink);
  margin-bottom: 18px; text-wrap: pretty;
}
.page-title em { font-style: italic; color: var(--haze); font-weight: 500; }
.page-lead {
  font-size: 18px; color: var(--steel); line-height: 1.55;
  max-width: 720px; margin-bottom: 36px;
  padding-bottom: 32px; border-bottom: 1px solid var(--line);
}
h2.section-h {
  font-family: var(--serif); font-weight: 600; font-size: 32px;
  line-height: 1.15; letter-spacing: -0.01em; margin: 56px 0 10px; color: var(--ink);
}
h2.section-h + .sub { color: var(--muted); font-size: 14.5px; margin-bottom: 22px; max-width: 640px; }
.kicker {
  font-family: var(--mono); font-size: 10px; letter-spacing: 0.18em;
  text-transform: uppercase; color: var(--haze); margin-bottom: 8px; display: inline-block;
}

/* ── Cards ── */
.card {
  background: rgba(16,31,44,0.83);
  border: 1px solid rgba(139,211,234,0.16);
  border-radius: 14px;
  box-shadow: 0 18px 48px rgba(0,0,0,0.18);
  padding: 22px 24px; position: relative;
}
.card.with-accent { padding-top: 24px; }
.card.with-accent::before {
  content: ''; position: absolute; top: 0; left: 0; right: 0;
  height: 3px; border-radius: 14px 14px 0 0;
}
.accent-cyan::before   { background: var(--cyan); }
.accent-green::before  { background: var(--green); }
.accent-amber::before  { background: var(--amber); }
.accent-rose::before   { background: var(--rose); }
.accent-violet::before { background: var(--violet); }

/* ── Page-end nav ── */
.page-end-nav {
  display: grid; grid-template-columns: 1fr 1fr; gap: 16px;
  margin-top: 72px; padding-top: 28px; border-top: 1px solid var(--line);
}
.page-end-card {
  background: rgba(16,31,44,0.6); border: 1px solid var(--line);
  border-radius: 10px; padding: 16px 18px; cursor: pointer;
  transition: border-color .12s, transform .15s;
}
.page-end-card:hover { border-color: rgba(139,211,234,0.45); transform: translateY(-1px); }
.page-end-card .dir {
  font-family: var(--mono); font-size: 10px; letter-spacing: 0.15em;
  text-transform: uppercase; color: var(--muted); margin-bottom: 4px;
}
.page-end-card.next { text-align: right; }
.page-end-card .pname { font-family: var(--serif); font-size: 20px; font-weight: 600; color: var(--haze); }
.page-end-card.docs-out { border: 1px dashed rgba(139,211,234,0.32); background: rgba(0,180,216,0.04); }
.page-end-card.docs-out .dir { color: var(--cyan); }

/* ── Responsive ── */
@media (max-width: 1080px) {
  .main { padding: 28px 28px 80px; }
  .page-title { font-size: 44px; }
}
@media (max-width: 880px) {
  .layout { grid-template-columns: 1fr; }
  .sidebar { display: none; }
  .main { padding: 22px 18px 60px; }
  .search-trigger { min-width: 180px; }
}
`;

if (!document.getElementById('shell-css')) {
  const s = document.createElement('style');
  s.id = 'shell-css'; s.textContent = shellCSS;
  document.head.appendChild(s);
}

/* ── Navigation model ─────────────────────────────────────────────────── */
const NAV = [
  {
    group: 'Platform',
    items: [
      { id: 'overview',  label: 'Overview',         glyph: '◇' },
      { id: 'modules',   label: 'Platform modules', glyph: '◫' },
    ],
  },
  {
    group: 'Strategy',
    items: [
      { id: 'storyline', label: 'How it works',     glyph: '⇶' },
      { id: 'why',       label: 'Why SurfaceGX',    glyph: '▦', badge: 'matrix' },
    ],
  },
  {
    group: 'Go-to-market',
    items: [
      { id: 'teams',     label: 'For your team',    glyph: '◉' },
      { id: 'services',  label: 'Services',         glyph: '◐' },
      { id: 'start',     label: 'Get started',      glyph: '→', badge: 'free' },
    ],
  },
  {
    group: 'Company',
    items: [
      { id: 'about',     label: 'About',            glyph: '◈' },
    ],
  },
  {
    group: 'Resources',
    items: [
      { id: 'concepts', label: 'Key concepts', glyph: '◴' },
      { id: 'faq',      label: 'FAQ',          glyph: '?', badge: 'GEO·AEO' },
    ],
  },
];

const PAGE_FLOW = ['overview','modules','storyline','why','teams','services','start','about','concepts','faq'];

/* ── Sidebar ── */
function Sidebar({ active, setActive }) {
  return (
    <aside className="sidebar">
      <div className="sb-tagline">
        AI visibility<br/>
        repair <span className="tag-accent">infrastructure</span>
      </div>

      {NAV.map(g => (
        <div className="nav-section" key={g.group}>
          <div className="nav-section-label">
            <span>{g.group}</span>
            <span className="line"></span>
          </div>
          {g.items.map(it => it.url ? (
            <a
              key={it.id}
              href={it.url}
              target="_blank"
              rel="noopener noreferrer"
              className="nav-link docs-link"
            >
              <span className="glyph">{it.glyph}</span>
              <span>{it.label}</span>
            </a>
          ) : (
            <button
              key={it.id}
              className={`nav-link ${active === it.id ? 'active' : ''}`}
              onClick={() => setActive(it.id)}
            >
              <span className="glyph">{it.glyph}</span>
              <span>{it.label}</span>
              {it.badge && <span className="badge">{it.badge}</span>}
            </button>
          ))}
        </div>
      ))}

      <div className="sb-footer">
        <a href="mailto:hello@surfacegx.com">hello@surfacegx.com</a>
        <a href="https://portal.surfacegx.com/login" style={{color:'var(--cyan)',fontWeight:600}}>Log in →</a>
        <span style={{fontFamily:'var(--mono)',fontSize:'10px',color:'var(--muted)',letterSpacing:'0.06em'}}>© SurfaceGX 2026</span>
      </div>
    </aside>
  );
}

/* ── Top nav ── */
function TopNav({ setActive, setPaletteOpen }) {
  return (
    <nav className="top-nav">
      <div className="top-nav-inner">
        <button className="wordmark" onClick={() => setActive('overview')}>
          <img src="/logo.png" alt="SurfaceGX" className="wordmark-logo" /> SurfaceGX
        </button>
        <div className="top-nav-spacer"></div>
        <button className="search-trigger" onClick={() => setPaletteOpen(true)}>
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
          </svg>
          <span className="search-placeholder">Search platform & docs…</span>
          <span className="kbd">⌘K</span>
        </button>
        <a href="https://portal.surfacegx.com/login" className="top-nav-cta-secondary">Log in</a>
        <a href="https://portal.surfacegx.com/taster" className="top-nav-cta">Run free scan</a>
      </div>
    </nav>
  );
}

/* ── ⌘K Search palette (SGX-003) ── */
function SearchPalette({ onClose, setActive, setFaqOpenId, setFaqFilter }) {
  const [query, setQuery] = React.useState('');
  const [selectedIdx, setSelectedIdx] = React.useState(0);
  const inputRef = React.useRef(null);

  const allItems = React.useMemo(() => {
    const navItems = NAV.flatMap(g =>
      g.items
        .filter(i => !i.docs)
        .map(i => ({ type: 'nav', id: i.id, label: i.label, group: g.group }))
    );
    const faqData = window.FAQ_DATA || [];
    const faqItems = faqData.map(f => ({
      type: 'faq', id: f.id, label: f.q, group: f.catLabel,
    }));
    return [...navItems, ...faqItems];
  }, []);

  const results = React.useMemo(() => {
    if (!query.trim()) return allItems.slice(0, 9);
    const q = query.toLowerCase();
    return allItems.filter(i =>
      i.label.toLowerCase().includes(q) || i.group.toLowerCase().includes(q)
    ).slice(0, 12);
  }, [query, allItems]);

  React.useEffect(() => {
    setTimeout(() => inputRef.current && inputRef.current.focus(), 40);
  }, []);

  React.useEffect(() => {
    setSelectedIdx(0);
  }, [query]);

  const select = React.useCallback((item) => {
    if (item.type === 'faq') {
      setFaqFilter('all');
      setFaqOpenId(item.id);
      setActive('faq');
    } else {
      setActive(item.id);
    }
    onClose();
  }, [setActive, setFaqOpenId, setFaqFilter, onClose]);

  const handleKey = React.useCallback((e) => {
    if (e.key === 'ArrowDown') {
      e.preventDefault();
      setSelectedIdx(i => Math.min(i + 1, results.length - 1));
    } else if (e.key === 'ArrowUp') {
      e.preventDefault();
      setSelectedIdx(i => Math.max(i - 1, 0));
    } else if (e.key === 'Enter') {
      if (results[selectedIdx]) select(results[selectedIdx]);
    } else if (e.key === 'Escape') {
      onClose();
    }
  }, [results, selectedIdx, select, onClose]);

  return (
    <div className="palette-overlay" onClick={onClose}>
      <div className="palette" onClick={e => e.stopPropagation()}>
        <div className="palette-search">
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
            <circle cx="11" cy="11" r="8"/><path d="m21 21-4.35-4.35"/>
          </svg>
          <input
            ref={inputRef}
            value={query}
            onChange={e => setQuery(e.target.value)}
            onKeyDown={handleKey}
            placeholder="Search platform & docs…"
          />
          <span className="kbd">Esc</span>
        </div>
        <div className="palette-results">
          {results.length === 0 ? (
            <div className="palette-empty">No results for "{query}"</div>
          ) : results.map((r, i) => (
            <div
              key={r.id + i}
              className={`palette-row ${i === selectedIdx ? 'sel' : ''}`}
              onClick={() => select(r)}
              onMouseEnter={() => setSelectedIdx(i)}
            >
              <span className={`palette-badge ${r.type}`}>
                {r.type === 'faq' ? 'FAQ' : 'Platform'}
              </span>
              <span className="palette-label">{r.label}</span>
              <span className="palette-group">{r.group}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ── Page-end nav ── */
function PageEndNav({ active, setActive, docsLink }) {
  const idx = PAGE_FLOW.indexOf(active);
  const prev = idx > 0 ? PAGE_FLOW[idx - 1] : null;
  const next = idx >= 0 && idx < PAGE_FLOW.length - 1 ? PAGE_FLOW[idx + 1] : null;
  const labelFor = id => {
    for (const g of NAV) {
      const f = g.items.find(i => i.id === id);
      if (f) return f.label;
    }
    return id;
  };
  return (
    <div className="page-end-nav">
      {prev ? (
        <div className="page-end-card" onClick={() => setActive(prev)}>
          <div className="dir">← Previous</div>
          <div className="pname">{labelFor(prev)}</div>
        </div>
      ) : <span />}
      {docsLink ? (
        <div className="page-end-card docs-out next" onClick={() => setActive(docsLink.id)}>
          <div className="dir">Continue in docs →</div>
          <div className="pname">{docsLink.label}</div>
        </div>
      ) : next ? (
        <div className="page-end-card next" onClick={() => setActive(next)}>
          <div className="dir">Next →</div>
          <div className="pname">{labelFor(next)}</div>
        </div>
      ) : <span />}
    </div>
  );
}

Object.assign(window, { TopNav, Sidebar, PageEndNav, SearchPalette, NAV, PAGE_FLOW });
