// Signal — interactive prototype
// Shared primitives: nav, router, scroll-reveal, theme tokens.

const SG_THEMES = {
  dark: {
    bg: '#0a0b0d', bgAlt: '#101114', bgElev: '#14161a',
    ink: '#f4f4f2', sub: '#8a8d94', subDim: '#5e6168',
    rule: 'rgba(244,244,242,0.10)', ruleStrong: 'rgba(244,244,242,0.22)',
    accent: '#52e0a1', accent2: '#ff6847',
    card: '#111316', chip: 'rgba(82,224,161,0.12)',
  },
  light: {
    bg: '#f5f5f3', bgAlt: '#eeede9', bgElev: '#ffffff',
    ink: '#0a0b0d', sub: '#6a6d72', subDim: '#9a9da2',
    rule: 'rgba(10,11,13,0.12)', ruleStrong: 'rgba(10,11,13,0.22)',
    accent: '#0a9955', accent2: '#cc3a1a',
    card: '#fbfbf9', chip: 'rgba(10,153,85,0.10)',
  },
  forest: {
    bg: '#06140d', bgAlt: '#0a1d14', bgElev: '#0e2418',
    ink: '#e8fff2', sub: '#6aa887', subDim: '#47785f',
    rule: 'rgba(82,224,161,0.16)', ruleStrong: 'rgba(82,224,161,0.32)',
    accent: '#52e0a1', accent2: '#ff6847',
    card: '#0a1d14', chip: 'rgba(82,224,161,0.14)',
  },
};

// ── tiny hash router ───────────────────────────────────────────
function useRoute() {
  const parse = () => {
    const h = (window.location.hash || '#/').slice(1);
    const [path, q] = h.split('?');
    const params = Object.fromEntries(new URLSearchParams(q || ''));
    return { path: path || '/', params };
  };
  const [route, setRoute] = React.useState(parse);
  React.useEffect(() => {
    const on = () => setRoute(parse());
    window.addEventListener('hashchange', on);
    return () => window.removeEventListener('hashchange', on);
  }, []);
  const navigate = (path, params) => {
    const qs = params ? '?' + new URLSearchParams(params).toString() : '';
    window.location.hash = '#' + path + qs;
    window.scrollTo({ top: 0, behavior: 'instant' });
  };
  return [route, navigate];
}

// ── scroll reveal ──────────────────────────────────────────────
function Reveal({ children, delay = 0, y = 16 }) {
  const ref = React.useRef(null);
  const [show, setShow] = React.useState(false);
  React.useEffect(() => {
    if (!ref.current) return;
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => { if (e.isIntersecting) setShow(true); });
    }, { threshold: 0.12, rootMargin: '0px 0px -40px 0px' });
    io.observe(ref.current);
    return () => io.disconnect();
  }, []);
  return (
    <div ref={ref} style={{
      opacity: show ? 1 : 0,
      transform: show ? 'none' : `translateY(${y}px)`,
      transition: `opacity .7s cubic-bezier(.2,.7,.3,1) ${delay}ms, transform .7s cubic-bezier(.2,.7,.3,1) ${delay}ms`,
      willChange: 'opacity, transform',
    }}>{children}</div>
  );
}

// ── nav ────────────────────────────────────────────────────────
function Nav({ t, route, navigate }) {
  const links = [
    ['/', 'home'],
    ['/services', 'services'],
    ['/insights', 'insights'],
    ['/about', 'about'],
    ['/contact', 'contact'],
  ];
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 50,
      background: t.bg + 'e8', backdropFilter: 'blur(14px)',
      borderBottom: `1px solid ${t.rule}`,
    }}>
      <div style={{
        maxWidth: 1320, margin: '0 auto', padding: '16px 48px',
        display: 'grid', gridTemplateColumns: '1fr auto 1fr', alignItems: 'center', gap: 40,
      }}>
        <a href="#/" onClick={(e) => { e.preventDefault(); navigate('/'); }}
          style={{ display: 'flex', alignItems: 'center', gap: 12, textDecoration: 'none', color: t.ink }}>
          <div style={{
            width: 24, height: 24, borderRadius: 5, background: t.accent,
            color: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 13,
          }}>B</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 8 }}>
            <span style={{ fontSize: 16, fontWeight: 600, letterSpacing: -0.3 }}>Burson</span>
            <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub }}>/consulting</span>
          </div>
        </a>

        <nav style={{ display: 'flex', gap: 4, justifyContent: 'center', position: 'relative',
          background: t.bgAlt, borderRadius: 10, padding: 4, border: `1px solid ${t.rule}` }}>
          {links.map(([path, label]) => {
            const active = route.path === path;
            return (
              <a key={path} href={'#' + path}
                onClick={(e) => { e.preventDefault(); navigate(path); }}
                style={{
                  fontFamily: 'JetBrains Mono, monospace', fontSize: 12,
                  padding: '8px 14px', borderRadius: 7,
                  color: active ? t.bg : t.sub,
                  background: active ? t.accent : 'transparent',
                  textDecoration: 'none', fontWeight: 500, transition: 'color .2s, background .2s',
                }}>{label}</a>
            );
          })}
        </nav>

        <div style={{ display: 'flex', gap: 12, justifyContent: 'flex-end', alignItems: 'center' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8,
            fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub }}>
            <span style={{
              width: 7, height: 7, borderRadius: 4, background: t.accent,
              boxShadow: `0 0 10px ${t.accent}`,
              animation: 'sgPulse 2.4s ease-in-out infinite',
            }} />
            <span>Q3 2026 · 2 slots</span>
          </div>
          <a href="#/contact" onClick={(e) => { e.preventDefault(); navigate('/contact'); }}
            style={{
              fontFamily: 'JetBrains Mono, monospace', fontSize: 12, fontWeight: 500,
              padding: '10px 16px', border: `1px solid ${t.accent}`,
              color: t.accent, borderRadius: 7, textDecoration: 'none',
            }}>Book intro →</a>
        </div>
      </div>
      <style>{`
        @keyframes sgPulse { 0%,100% { opacity: 1 } 50% { opacity: 0.3 } }
      `}</style>
    </header>
  );
}

// ── primitive buttons ─────────────────────────────────────────
function SgButton({ t, variant = 'primary', onClick, children, as, href, full }) {
  const [hover, setHover] = React.useState(false);
  const styles = {
    primary: { bg: t.accent, color: t.bg, border: 'none' },
    secondary: { bg: 'transparent', color: t.ink, border: `1px solid ${t.rule}` },
    ghost: { bg: 'transparent', color: t.ink, border: 'none' },
  }[variant];
  const Tag = as || 'button';
  return (
    <Tag
      href={href}
      onClick={onClick}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => setHover(false)}
      style={{
        display: 'inline-flex', alignItems: 'center', justifyContent: 'center', gap: 8,
        fontSize: 14, fontWeight: 500, padding: '14px 22px',
        background: styles.bg, color: styles.color, border: styles.border,
        borderRadius: 8, textDecoration: 'none', cursor: 'pointer',
        fontFamily: 'Geist, sans-serif',
        transform: hover ? 'translateY(-1px)' : 'none',
        boxShadow: hover && variant === 'primary' ? `0 8px 24px ${t.accent}40` : 'none',
        transition: 'transform .15s, box-shadow .2s, background .2s',
        width: full ? '100%' : 'auto',
      }}>
      {children}
    </Tag>
  );
}

function SectionHeader({ t, kicker, title, note }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 48, gap: 40, flexWrap: 'wrap' }}>
      <div>
        <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub, marginBottom: 12 }}>
          <span style={{ color: t.accent }}>▸</span> {kicker}
        </div>
        <h2 style={{ fontSize: 'clamp(36px, 4.2vw, 56px)', fontWeight: 500, letterSpacing: -1.5, margin: 0, lineHeight: 1.02, maxWidth: 900 }}>
          {title}
        </h2>
      </div>
      {note && <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 12, color: t.sub, textAlign: 'right', maxWidth: 280, lineHeight: 1.6 }}>{note}</div>}
    </div>
  );
}

// ── telemetry / hero animated panel ───────────────────────────
function TelemetryPanel({ t }) {
  const rows = [
    { k: 'strategy.align', v: 'ok', c: t.accent },
    { k: 'eng.throughput', v: '+34%', c: t.accent },
    { k: 'ai.roi', v: 'measuring', c: t.ink },
    { k: 'due_diligence', v: '3 active', c: t.ink },
    { k: 'org.redesign', v: 'shipping', c: t.accent2 },
    { k: 'advisory.slots', v: '2 open', c: t.accent },
  ];
  const [typed, setTyped] = React.useState('');
  const fullCmd = '$ burson --status --live';
  React.useEffect(() => {
    let i = 0; const id = setInterval(() => {
      i += 1; setTyped(fullCmd.slice(0, i));
      if (i >= fullCmd.length) clearInterval(id);
    }, 45);
    return () => clearInterval(id);
  }, []);
  const [shown, setShown] = React.useState(0);
  React.useEffect(() => {
    if (typed !== fullCmd) return;
    let i = 0;
    const id = setInterval(() => {
      i += 1; setShown(i);
      if (i >= rows.length) clearInterval(id);
    }, 240);
    return () => clearInterval(id);
  }, [typed]);

  return (
    <div style={{
      background: t.card, border: `1px solid ${t.rule}`, borderRadius: 12, overflow: 'hidden',
      fontFamily: 'JetBrains Mono, monospace', fontSize: 13,
      boxShadow: `0 24px 60px -20px ${t.accent}25`,
    }}>
      <div style={{ padding: '12px 16px', borderBottom: `1px solid ${t.rule}`, display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: t.sub }}>
        <span style={{ width: 10, height: 10, borderRadius: 5, background: '#ff6057' }} />
        <span style={{ width: 10, height: 10, borderRadius: 5, background: '#febc2e' }} />
        <span style={{ width: 10, height: 10, borderRadius: 5, background: '#28c840' }} />
        <span style={{ marginLeft: 8 }}>advisory — live status</span>
        <span style={{ marginLeft: 'auto', color: t.accent }}>●</span>
      </div>
      <div style={{ padding: 22 }}>
        <div style={{ color: t.sub, marginBottom: 16, minHeight: 20 }}>
          {typed}
          <span style={{ display: 'inline-block', width: 7, height: 14, background: t.accent, marginLeft: 4, verticalAlign: 'middle', animation: 'sgBlink 1s step-end infinite' }} />
        </div>
        {rows.map((r, i) => (
          <div key={r.k} style={{
            display: 'flex', justifyContent: 'space-between', padding: '8px 0',
            borderBottom: i === rows.length - 1 ? 'none' : `1px dashed ${t.rule}`,
            opacity: i < shown ? 1 : 0,
            transform: i < shown ? 'none' : 'translateY(-4px)',
            transition: 'opacity .3s, transform .3s',
          }}>
            <span style={{ color: t.sub }}>{r.k}</span>
            <span style={{ color: r.c, fontWeight: 500 }}>{r.v}</span>
          </div>
        ))}
        {shown >= rows.length && (
          <div style={{ marginTop: 16, color: t.accent, display: 'flex', alignItems: 'center', gap: 4, animation: 'sgFadeIn .4s' }}>
            <span>▸</span><span>ready for intro</span>
          </div>
        )}
      </div>
      <style>{`
        @keyframes sgBlink { 50% { opacity: 0 } }
        @keyframes sgFadeIn { from { opacity: 0 } to { opacity: 1 } }
      `}</style>
    </div>
  );
}

// ── ticker ────────────────────────────────────────────────────
function Ticker({ t }) {
  const items = ['FORD', 'SAINSBURY\u2019S', 'NESTLÉ', 'UNILEVER', 'YOOX NET-A-PORTER', 'EMIRATES', 'BOOTS', 'ARGOS', 'WPP OPEN'];
  const row = [...items, ...items];
  return (
    <section style={{ borderTop: `1px solid ${t.rule}`, borderBottom: `1px solid ${t.rule}`, padding: '24px 0', overflow: 'hidden', background: t.bgAlt }}>
      <div style={{ display: 'flex', gap: 56, animation: 'sgScroll 38s linear infinite', fontFamily: 'JetBrains Mono, monospace', fontSize: 13, color: t.sub, letterSpacing: 1.5, whiteSpace: 'nowrap' }}>
        {row.map((c, i) => (
          <span key={i} style={{ display: 'inline-flex', alignItems: 'center', gap: 56 }}>
            {c}<span style={{ color: t.accent }}>◆</span>
          </span>
        ))}
      </div>
      <style>{`@keyframes sgScroll { from { transform: translateX(0) } to { transform: translateX(-50%) } }`}</style>
    </section>
  );
}

// ── footer ────────────────────────────────────────────────────
function Footer({ t, navigate }) {
  return (
    <footer style={{ padding: '64px 48px 32px', background: t.bgAlt, borderTop: `1px solid ${t.rule}` }}>
      <div style={{ maxWidth: 1320, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr 1fr 1fr', gap: 48, paddingBottom: 48, borderBottom: `1px solid ${t.rule}` }}>
          <div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
              <div style={{ width: 28, height: 28, borderRadius: 6, background: t.accent, color: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 14 }}>B</div>
              <span style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.3, color: t.ink }}>Burson Consulting</span>
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: t.sub, margin: 0, maxWidth: 360 }}>
              Technology &amp; AI advisory for executive teams rebuilding the operating
              model for the current decade.
            </p>
          </div>
          <FooterCol t={t} title="Practice" items={[
            ['AI Strategy', '/services'], ['Tech Strategy', '/services'],
            ['Engineering', '/services'], ['M&A / DD', '/services'],
          ]} navigate={navigate} />
          <FooterCol t={t} title="Signal" items={[
            ['Essays', '/insights'], ['Field notes', '/insights'],
            ['Talks', '/insights'], ['Newsletter', '/contact'],
          ]} navigate={navigate} />
          <FooterCol t={t} title="Firm" items={[
            ['About', '/about'], ['Contact', '/contact'],
            ['LinkedIn', null], ['RSS', null],
          ]} navigate={navigate} />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', paddingTop: 24, fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub }}>
          <span>© 2026 burson_consulting · London &amp; remote</span>
          <span>v.1.0 // last shipped 2026.04.24</span>
        </div>
      </div>
    </footer>
  );
}

function FooterCol({ t, title, items, navigate }) {
  return (
    <div>
      <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.subDim, marginBottom: 16, letterSpacing: 1 }}>
        {title.toUpperCase()}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {items.map(([label, path]) => (
          <a key={label} href={path ? '#' + path : '#'}
            onClick={(e) => { if (path) { e.preventDefault(); navigate(path); } }}
            style={{ color: t.ink, textDecoration: 'none', fontSize: 14, opacity: 0.8, transition: 'opacity .15s' }}
            onMouseEnter={(e) => (e.currentTarget.style.opacity = 1)}
            onMouseLeave={(e) => (e.currentTarget.style.opacity = 0.8)}>
            {label}
          </a>
        ))}
      </div>
    </div>
  );
}

Object.assign(window, {
  SG_THEMES, useRoute, Reveal, Nav, SgButton, SectionHeader,
  TelemetryPanel, Ticker, Footer,
});
