// Site shell - NavBar, Footer, DocsLayout, page chrome.
// Shared across every page in the MomentIQ site.

const injectVercelAnalytics = () => {
  if (typeof window === 'undefined' || typeof document === 'undefined') return;
  if (window.__MIQ_VERCEL_ANALYTICS_LOADED) return;
  window.__MIQ_VERCEL_ANALYTICS_LOADED = true;
  window.va = window.va || function () {
    (window.vaq = window.vaq || []).push(arguments);
  };
  const existing = document.querySelector('script[data-miq-vercel-analytics]');
  if (existing) return;
  const script = document.createElement('script');
  script.defer = true;
  script.src = (window.__MOMENTIQ_ENV && window.__MOMENTIQ_ENV.VERCEL_ANALYTICS_SRC)
    || '/_vercel/insights/script.js';
  script.setAttribute('data-miq-vercel-analytics', 'true');
  document.head.appendChild(script);
};

injectVercelAnalytics();

const NAV = [
  { l: 'Moment Lab', href: 'index.html' },
  { l: 'Start here', href: 'docs-setup.html' },
  { l: 'Docs',       href: 'docs.html' },
  { l: 'AI agents',  href: 'docs-ai-agents.html' },
  { l: 'Use cases',  href: 'use-cases.html' },
  { l: 'Pricing',    href: 'pricing.html' },
  { l: 'Dashboard',  href: 'dashboard.html' },
];

const SiteNav = ({ current = '', dark = false }) => {
  const fg = dark ? wf.darkInk2 : wf.ink2;
  const onDashboard = current === 'Dashboard';
  const signedIn = (() => {
    try { return !!JSON.parse(localStorage.getItem('miq_dashboard_session') || 'null')?.signedIn; }
    catch (_err) { return false; }
  })();
  return (
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: '14px 28px',
      borderBottom: `1px solid ${dark ? wf.darkLine : wf.line}`,
      background: dark ? wf.dark : wf.card,
      position: 'sticky', top: 0, zIndex: 50,
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 28 }}>
        <a href="index.html" style={{ textDecoration: 'none' }}><Logo dark={dark} /></a>
        <div style={{ display: 'flex', alignItems: 'center', gap: 22, fontFamily: wf.sans, fontSize: 13.5 }}>
          {NAV.map(n => (
            <a key={n.l} href={n.href} style={{
              textDecoration: 'none',
              color: current === n.l ? 'var(--accent)' : fg,
              fontWeight: current === n.l ? 700 : 500,
              background: current === n.l ? 'var(--accent-soft)' : 'transparent',
              border: current === n.l ? `1px solid var(--accent)` : '1px solid transparent',
              borderBottom: current === n.l ? `2px solid var(--accent)` : '2px solid transparent',
              borderRadius: 7,
              padding: '6px 10px',
            }}>{n.l}</a>
          ))}
        </div>
      </div>
      {!onDashboard && <div style={{ display: 'flex', alignItems: 'center', gap: 12, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, flexWrap: 'wrap', justifyContent: 'flex-end' }}>
          {[
            ['Usage-based', 'oklch(0.62 0.18 250)'],
            ['Grows with you', 'oklch(0.66 0.13 155)'],
            ['$5 credit to start', 'oklch(0.70 0.16 52)'],
          ].map(([label, color]) => (
            <span key={label} style={{
              fontFamily: wf.sans,
              fontSize: 12.5,
              fontWeight: 600,
              color,
              background: `color-mix(in oklch, ${color} 13%, transparent)`,
              border: `1px solid color-mix(in oklch, ${color} 34%, transparent)`,
              borderRadius: 999,
              padding: '4px 8px',
              whiteSpace: 'nowrap',
            }}>{label}</span>
          ))}
        </div>
        <a href={signedIn ? 'dashboard.html' : 'dashboard.html?auth=signup'} style={{ textDecoration: 'none', cursor: 'pointer' }}>
          <Btn primary size={13.5}>{signedIn ? 'Dashboard' : 'Sign up / log in'}</Btn>
        </a>
      </div>}
    </div>
  );
};

const Footer = () => (
  <div style={{ background: wf.dark, color: wf.darkInk2, padding: '56px 28px 28px', borderTop: `1px solid ${wf.darkLine}` }}>
    <div style={{ maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.3fr repeat(5, 1fr)', gap: 24 }}>
        <div>
          <Logo dark />
          <p style={{ fontFamily: wf.sans, fontSize: 13, color: wf.darkInk3, lineHeight: 1.6, margin: '14px 0 0', maxWidth: 280 }}>
            Timeline-first video and audio APIs for AI media apps. One key. Usage-based pricing.
          </p>
        </div>
        {[
          ['Product', [['Moment Lab','index.html'],['Docs','docs.html'],['Use cases','use-cases.html'],['Pricing','pricing.html']]],
          ['Endpoints', [['Video','docs.html#video'],['Audio','docs.html#audio'],['Timeline','docs.html#timeline']]],
          ['Account', [['Dashboard','dashboard.html'],['API keys','dashboard-api-keys.html'],['Usage','dashboard-usage.html'],['Billing','dashboard-billing.html']]],
          ['Resources', [['Start here','docs-setup.html'],['AI agents','docs-ai-agents.html'],['Quickstart','docs-quickstart.html'],['Changelog','changelog.html'],['Sitemap','sitemap.html']]],
          ['Trust', [['Contact','contact.html'],['Status','status.html'],['Privacy','privacy.html'],['Data retention','data-retention.html'],['Terms','terms.html'],['GitHub','https://github.com/wojoBro/moment-iq']]],
        ].map(([title, items]) => (
          <div key={title}>
            <div style={{ fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1.2, color: wf.darkInk3, textTransform: 'uppercase', marginBottom: 12 }}>{title}</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {items.map(([l, h]) => (
                <a key={l} href={h} style={{ fontFamily: wf.sans, fontSize: 13.5, color: wf.darkInk2, textDecoration: 'none' }}>{l}</a>
              ))}
            </div>
          </div>
        ))}
      </div>
      <div style={{ marginTop: 40, paddingTop: 18, borderTop: `1px solid ${wf.darkLine}`, display: 'flex', justifyContent: 'space-between', fontFamily: wf.mono, fontSize: 11, color: wf.darkInk3 }}>
        <span>(c) 2026 MomentIQ Labs</span>
        <span>api.momentiq.dev/v1</span>
      </div>
    </div>
  </div>
);

// Scaffold for all sub-pages: nav + (optional) hero + content + footer.
const Page = ({ current, children, dark = false }) => (
  <div style={{ minHeight: '100vh', background: wf.bg, fontFamily: wf.sans, color: wf.ink }}>
    <SiteNav current={current} />
    {children}
    <Footer />
  </div>
);

// Compact hero band for non-home pages.
const PageHero = ({ kicker, title, sub, right, accentBg = false }) => (
  <div style={{
    background: accentBg ? `linear-gradient(180deg, #0b0d10 0%, #0d1014 100%)` : wf.card,
    color: accentBg ? wf.card : wf.ink,
    borderBottom: `1px solid ${accentBg ? wf.darkLine : wf.line}`,
    padding: '52px 28px 56px',
  }}>
    <div style={{ maxWidth: 1280, margin: '0 auto', display: 'grid', gridTemplateColumns: right ? '1.4fr 1fr' : '1fr', gap: 36, alignItems: 'end' }}>
      <div>
        {kicker && <div style={{ fontFamily: wf.mono, fontSize: 11, letterSpacing: 1.2, color: 'var(--accent)', textTransform: 'uppercase', marginBottom: 10 }}>{kicker}</div>}
        <h1 style={{ fontFamily: wf.sans, fontSize: 44, lineHeight: 1.08, fontWeight: 600, letterSpacing: -0.8, margin: 0, maxWidth: 880 }}>{title}</h1>
        {sub && <p style={{ fontFamily: wf.sans, fontSize: 16, color: accentBg ? wf.darkInk2 : wf.ink3, lineHeight: 1.55, margin: '14px 0 0', maxWidth: 760 }}>{sub}</p>}
      </div>
      {right}
    </div>
  </div>
);

// Breadcrumbs bar
const Breadcrumbs = ({ items = [] }) => (
  <div style={{
    padding: '12px 28px', borderBottom: `1px solid ${wf.line}`,
    background: wf.cardAlt,
    fontFamily: wf.mono, fontSize: 12, color: wf.ink3,
  }}>
    <div style={{ maxWidth: 1280, margin: '0 auto' }}>
      {items.map((it, i) => (
        <React.Fragment key={i}>
          {i > 0 && <span style={{ margin: '0 8px', color: wf.ink4 }}>/</span>}
          {it.href ? <a href={it.href} style={{ color: wf.ink3, textDecoration: 'none' }}>{it.l}</a> : <span style={{ color: wf.ink2 }}>{it.l}</span>}
        </React.Fragment>
      ))}
    </div>
  </div>
);

// Two-column docs layout: sidebar nav + content
const DocsLayout = ({ activeId, children }) => (
  <div style={{ maxWidth: 1280, margin: '0 auto', padding: '32px 28px 56px', display: 'grid', gridTemplateColumns: '240px 1fr', gap: 36 }}>
    <DocsSidebar activeId={activeId} />
    <div style={{ minWidth: 0 }}>{children}</div>
  </div>
);

// Built lazily from GROUPS + endpointIdsByGroup + ENDPOINTS + docsHrefFor.
// Adding a new endpoint to ENDPOINTS automatically adds it to the docs sidebar.
// Lazy because endpoint-data.jsx loads after site-shell.jsx in some HTML files.
const buildDocsNav = () => [
  { group: 'Getting started', items: [
    { id: 'setup',       l: 'Start here',        href: 'docs-setup.html' },
    { id: 'quickstart',  l: 'Quickstart',        href: 'docs-quickstart.html' },
    { id: 'ai-agents',   l: 'AI agents',         href: 'docs-ai-agents.html' },
    { id: 'chatgpt',     l: 'ChatGPT connector', href: 'docs-chatgpt.html' },
    { id: 'claude',      l: 'Claude connector',  href: 'docs-claude.html' },
    { id: 'auth',        l: 'Authentication',    href: 'docs-authentication.html' },
    { id: 'errors',      l: 'Errors',            href: 'docs-errors.html' },
    { id: 'async-jobs',  l: 'Async jobs',        href: 'docs-async-jobs.html' },
    { id: 'one-key',     l: 'One API key',       href: 'docs.html#one-key' },
    { id: 'workflows',   l: 'Common workflows',  href: 'docs.html#workflows' },
    { id: 'sdks',        l: 'SDKs',              href: 'docs.html#sdks' },
  ]},
  ...Object.values(window.GROUPS || {}).map(g => ({
    group:  g.name,
    kicker: g.pathPrefix,
    color:  g.color,
    items:  window.endpointIdsByGroup(g.id).map(id => ({
      id,
      l:    window.ENDPOINTS[id].title,
      href: window.docsHrefFor(id),
      color: g.color,
    })),
  })),
];
const DOCS_NAV = []; // back-compat export - DocsSidebar calls buildDocsNav() at render

const DocsSidebar = ({ activeId }) => (
  <div style={{ position: 'sticky', top: 80, alignSelf: 'start' }}>
    {buildDocsNav().map(g => (
      <div key={g.group} style={{ marginBottom: 18 }}>
        <div style={{ fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1.2, color: g.color || wf.ink3, textTransform: 'uppercase', padding: '0 6px 6px' }}>
          {g.group}{g.kicker ? <span style={{ marginLeft: 6, color: g.color || 'var(--accent)' }}>{g.kicker}</span> : null}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {g.items.map(it => {
            const active = activeId === it.id;
            return (
              <a key={it.id} href={it.href} style={{
                fontFamily: it.id.includes('/') ? wf.mono : wf.sans,
                fontSize: it.id.includes('/') ? 12.5 : 13,
                padding: '5px 10px',
                color: it.color || (active ? wf.ink : wf.ink2),
                background: active ? wf.card : 'transparent',
                border: active ? `1px solid ${it.color || wf.line}` : '1px solid transparent',
                borderLeft: active ? `2px solid ${it.color || 'var(--accent)'}` : '2px solid transparent',
                borderRadius: 4,
                textDecoration: 'none',
                fontWeight: active ? 500 : 400,
              }}>{it.l}</a>
            );
          })}
        </div>
      </div>
    ))}
  </div>
);

// Method-colored endpoint chip used on cards.
const EndpointCard = ({ method = 'POST', path, desc, price, href, color = 'var(--accent)' }) => (
  <a href={href} style={{
    display: 'block', textDecoration: 'none', color: 'inherit',
    background: wf.card, border: `1px solid ${color}`, borderRadius: 10,
    padding: 14, transition: 'border-color .15s', boxShadow: `inset 0 2px 0 ${color}`,
  }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
      <Method kind={method} />
      <span style={{ fontFamily: wf.mono, fontSize: 12.5, color, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{path}</span>
    </div>
    <div style={{ fontFamily: wf.sans, fontSize: 13, color: wf.ink3, lineHeight: 1.45, minHeight: 36 }}>{desc}</div>
    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, paddingTop: 10, borderTop: `1px solid ${wf.line2}`, fontFamily: wf.mono, fontSize: 11 }}>
      <span style={{ color: wf.ink3 }}>{price}</span>
      <span style={{ color }}>Read docs -></span>
    </div>
  </a>
);

// H2/H3 styling for docs body
const H2 = ({ id, children, style }) => <h2 id={id} style={{ fontFamily: wf.sans, fontSize: 26, fontWeight: 600, letterSpacing: -0.4, margin: '40px 0 14px', color: wf.ink, scrollMarginTop: 80, ...style }}>{children}</h2>;
const H3 = ({ id, children, style }) => <h3 id={id} style={{ fontFamily: wf.sans, fontSize: 17, fontWeight: 600, margin: '28px 0 10px', color: wf.ink, scrollMarginTop: 80, ...style }}>{children}</h3>;
const P  = ({ children, style }) => <p style={{ fontFamily: wf.sans, fontSize: 14.5, lineHeight: 1.7, color: wf.ink2, margin: '0 0 12px', maxWidth: 760, ...style }}>{children}</p>;

// Param/response table - accepts either tuple rows [name,type,desc,required?]
// or object rows {name,type,description,required?}.
const ApiTable = ({ rows = [], cols = ['Field', 'Type', 'Description'] }) => {
  const cells = (r) => Array.isArray(r)
    ? { name: r[0], type: r[1], desc: r[2], required: !!r[3] }
    : { name: r.name, type: r.type, desc: r.description, required: !!r.required };
  return (
    <div style={{ border: `1px solid ${wf.line}`, borderRadius: 10, overflow: 'hidden', background: wf.card, marginBottom: 16 }}>
      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 0.8fr 2.4fr', padding: '10px 14px', background: wf.cardAlt, borderBottom: `1px solid ${wf.line}`, fontFamily: wf.mono, fontSize: 10.5, letterSpacing: 1, color: wf.ink3, textTransform: 'uppercase' }}>
        {cols.map(c => <span key={c}>{c}</span>)}
      </div>
      {rows.map((r, i) => {
        const c = cells(r);
        return (
          <div key={i} style={{
            display: 'grid', gridTemplateColumns: '1.2fr 0.8fr 2.4fr', alignItems: 'baseline',
            padding: '12px 14px',
            borderBottom: i < rows.length - 1 ? `1px solid ${wf.line2}` : 'none',
          }}>
            <span style={{ fontFamily: wf.mono, fontSize: 12.5, color: wf.ink, display: 'flex', alignItems: 'center', gap: 8 }}>
              {c.name}
              {c.required && <span style={{ fontFamily: wf.mono, fontSize: 9.5, padding: '1px 5px', borderRadius: 3, background: 'var(--accent-soft)', color: 'var(--accent)', textTransform: 'uppercase', letterSpacing: 0.5 }}>req</span>}
            </span>
            <span style={{ fontFamily: wf.mono, fontSize: 12, color: wf.ink3 }}>{c.type}</span>
            <span style={{ fontFamily: wf.sans, fontSize: 13, color: wf.ink2, lineHeight: 1.5 }}>{c.desc}</span>
          </div>
        );
      })}
    </div>
  );
};

// Code-tab block with multiple language tabs
const CodeTabs = ({ tabs = [], filename }) => {
  const [active, setActive] = React.useState(tabs[0]?.lang || 'cURL');
  const cur = tabs.find(t => t.lang === active) || tabs[0];

  const trackTab = (lang) => {
    if (window.MIQAnalytics) {
      window.MIQAnalytics.track('endpoint_code_tab_selected', { language: lang, filename });
    }
  };
  const trackCopy = () => {
    try { navigator.clipboard?.writeText((cur?.lines || []).join('\n')); } catch (e) {}
    if (window.MIQAnalytics) {
      window.MIQAnalytics.track('endpoint_copy_code_clicked', { language: active, filename, copy_type: 'codeblock' });
    }
  };

  return (
    <div style={{ background: '#0a0c0f', border: `1px solid ${wf.darkLine}`, borderRadius: 10, overflow: 'hidden', marginBottom: 16 }}>
      <div style={{ display: 'flex', alignItems: 'center', borderBottom: `1px solid ${wf.darkLine}`, background: '#0d1014' }}>
        {tabs.map(t => (
          <span key={t.lang} onClick={() => { setActive(t.lang); trackTab(t.lang); }} style={{
            fontFamily: wf.mono, fontSize: 11.5,
            padding: '10px 14px',
            color: t.lang === active ? wf.card : wf.darkInk3,
            borderBottom: t.lang === active ? `2px solid var(--accent)` : '2px solid transparent',
            marginBottom: -1,
            cursor: 'pointer',
          }}>{t.lang}</span>
        ))}
        <span style={{ flex: 1 }} />
        <span style={{ fontFamily: wf.mono, fontSize: 11, color: wf.darkInk3, padding: '0 12px' }}>{filename}</span>
        <span onClick={trackCopy} style={{ fontFamily: wf.mono, fontSize: 10.5, color: wf.darkInk3, padding: '0 12px 0 0', cursor: 'pointer' }}>copy </span>
      </div>
      <div style={{ padding: '14px 16px', fontFamily: wf.mono, fontSize: 12.5, lineHeight: 1.7, color: '#d8dde3' }}>
        {(cur?.lines || []).map((ln, i) => {
          let color = '#d8dde3';
          if (ln.startsWith('//') || ln.startsWith('#')) color = '#5b6573';
          else if (ln.startsWith('+ ')) color = 'var(--accent)';
          // very rough string highlighter
          const parts = []; let key = 0; let last = 0;
          const re = /"([^"]*)"/g; let m;
          while ((m = re.exec(ln)) !== null) {
            if (m.index > last) parts.push(<span key={key++}>{ln.slice(last, m.index)}</span>);
            parts.push(<span key={key++} style={{ color: color === '#5b6573' ? color : '#9bd17b' }}>"{m[1]}"</span>);
            last = m.index + m[0].length;
          }
          if (last < ln.length) parts.push(<span key={key++}>{ln.slice(last)}</span>);
          return <div key={i} style={{ whiteSpace: 'pre', color }}>{parts.length ? parts : (ln || '\u00a0')}</div>;
        })}
      </div>
    </div>
  );
};

const markAppReady = () => {
  const html = document.documentElement;
  const done = () => {
    html.classList.remove('js-app-loading');
    html.classList.add('js-app-ready');
  };
  if (typeof requestAnimationFrame === 'function') requestAnimationFrame(done);
  else done();
};

// Render-on-mount mount helper used by every page file
const mount = (el) => {
  const root = ReactDOM.createRoot(document.getElementById('root'));
  root.render(el);
  markAppReady();
  return root;
};

// Apply accent color tokens to the document (every page imports this).
const applyAccent = (name = 'blue') => {
  const accents = {
    none:   '#0b0d10',
    green:  'oklch(0.66 0.13 155)',
    orange: 'oklch(0.70 0.16 52)',
    blue:   'oklch(0.62 0.18 250)',
  };
  const accent = accents[name] || accents.blue;
  const accentSoft = `color-mix(in oklch, ${accent} 14%, transparent)`;
  document.documentElement.style.setProperty('--accent', accent);
  document.documentElement.style.setProperty('--accent-soft', accentSoft);
  document.documentElement.style.setProperty('--dens', 1);
};

Object.assign(window, {
  SiteNav, Footer, Page, PageHero, Breadcrumbs,
  DocsLayout, DocsSidebar, DOCS_NAV, NAV,
  EndpointCard, H2, H3, P, ApiTable, CodeTabs,
  mount, markAppReady, applyAccent, buildDocsNav,
});
