// Signal — Insights index + reader drawer

function PageInsights({ t, navigate, route }) {
  const selectedId = route.params.id;
  const selected = INSIGHTS.find((p) => p.id === selectedId);
  const [filter, setFilter] = React.useState('ALL');
  const tags = ['ALL', 'ESSAY', 'FIELD NOTE', 'TALK'];
  const filtered = INSIGHTS.filter((p) => filter === 'ALL' || p.tag === filter);

  return (
    <>
      <section style={{ padding: '80px 48px 40px', maxWidth: 1320, margin: '0 auto' }}>
        <Reveal>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub, marginBottom: 16 }}>
            <span style={{ color: t.accent }}>▸</span> /signal
          </div>
        </Reveal>
        <Reveal delay={60}>
          <h1 style={{ fontSize: 'clamp(56px, 8vw, 96px)', lineHeight: 0.96, letterSpacing: -3, fontWeight: 500, margin: 0 }}>
            Signal. <span style={{ color: t.sub }}>Not noise.</span>
          </h1>
        </Reveal>
        <Reveal delay={140}>
          <p style={{ fontSize: 18, lineHeight: 1.55, color: t.sub, maxWidth: 720, marginTop: 28 }}>
            Essays, field notes, and talks on the decisions enterprise tech leaders are
            actually making right now. Monthly newsletter, no growth hacks.
          </p>
        </Reveal>

        <div style={{ marginTop: 48, display: 'flex', gap: 8, alignItems: 'center', borderBottom: `1px solid ${t.rule}`, paddingBottom: 16 }}>
          <span style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub, marginRight: 8 }}>FILTER:</span>
          {tags.map((tag) => (
            <button key={tag} onClick={() => setFilter(tag)}
              style={{
                padding: '6px 12px', fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                background: filter === tag ? t.accent : 'transparent',
                color: filter === tag ? t.bg : t.sub,
                border: `1px solid ${filter === tag ? t.accent : t.rule}`,
                borderRadius: 6, cursor: 'pointer', transition: 'all .15s',
              }}>{tag}</button>
          ))}
          <span style={{ marginLeft: 'auto', fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub }}>
            {filtered.length} {filtered.length === 1 ? 'piece' : 'pieces'}
          </span>
        </div>
      </section>

      <section style={{ padding: '24px 48px 80px', maxWidth: 1320, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
          {filtered.map((p, i) => (
            <Reveal key={p.id} delay={i * 60}>
              <InsightCard t={t} p={p} onClick={() => navigate('/insights', { id: p.id })} />
            </Reveal>
          ))}
        </div>
      </section>

      <NewsletterBlock t={t} navigate={navigate} />

      {selected && <ReaderDrawer t={t} post={selected} onClose={() => navigate('/insights')} navigate={navigate} />}
    </>
  );
}

function ReaderDrawer({ t, post, onClose, navigate }) {
  const idx = INSIGHTS.findIndex((p) => p.id === post.id);
  const prev = INSIGHTS[idx - 1];
  const next = INSIGHTS[idx + 1];

  React.useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') onClose();
      if (e.key === 'ArrowLeft' && prev) navigate('/insights', { id: prev.id });
      if (e.key === 'ArrowRight' && next) navigate('/insights', { id: next.id });
    };
    document.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => {
      document.removeEventListener('keydown', onKey);
      document.body.style.overflow = '';
    };
  }, [post.id, prev, next]);

  return ReactDOM.createPortal(
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 100,
      background: 'rgba(0,0,0,0.72)', backdropFilter: 'blur(10px)',
      display: 'flex', justifyContent: 'flex-end',
      animation: 'sgFadeIn .25s',
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        width: '100%', maxWidth: 820, height: '100%', background: t.bg,
        overflowY: 'auto', borderLeft: `1px solid ${t.rule}`,
        animation: 'sgDrawerIn .35s cubic-bezier(.2,.7,.3,1)',
      }}>
        <div style={{
          position: 'sticky', top: 0, background: t.bg + 'f2', backdropFilter: 'blur(12px)',
          borderBottom: `1px solid ${t.rule}`, padding: '16px 48px',
          display: 'flex', alignItems: 'center', justifyContent: 'space-between', zIndex: 2,
        }}>
          <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub, display: 'flex', gap: 12 }}>
            <span style={{ color: t.accent }}>{post.tag}</span>
            <span>·</span><span>{post.date}</span>
            <span>·</span><span>{post.time} read</span>
          </div>
          <button onClick={onClose} aria-label="Close"
            style={{ width: 32, height: 32, borderRadius: 16, background: 'transparent', color: t.ink, border: `1px solid ${t.rule}`, cursor: 'pointer', fontSize: 14, fontFamily: 'inherit' }}>
            ✕
          </button>
        </div>
        <article style={{ padding: '48px 72px 96px', maxWidth: 720 }}>
          <h1 style={{ fontSize: 'clamp(36px, 5vw, 56px)', fontWeight: 500, letterSpacing: -1.6, lineHeight: 1.06, margin: 0 }}>{post.title}</h1>
          <p style={{ fontSize: 19, lineHeight: 1.5, color: t.sub, marginTop: 20, fontStyle: 'italic', fontFamily: 'Newsreader, serif' }}>{post.dek}</p>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 32, paddingBottom: 32, borderBottom: `1px solid ${t.rule}` }}>
            <div style={{ width: 36, height: 36, borderRadius: 18, background: t.accent, color: t.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'JetBrains Mono, monospace', fontWeight: 700, fontSize: 13 }}>GB</div>
            <div>
              <div style={{ fontSize: 14, fontWeight: 500 }}>Burson Consulting</div>
              <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.sub }}>Technology & AI Advisory</div>
            </div>
          </div>
          <div style={{ marginTop: 40 }}>
            {post.body.map((para, i) => (
              <p key={i} style={{ fontSize: 17, lineHeight: 1.65, margin: '0 0 22px', color: t.ink }}>
                {para}
              </p>
            ))}
          </div>

          <div style={{ marginTop: 48, padding: '28px 32px', background: t.card, border: `1px solid ${t.rule}`, borderRadius: 12 }}>
            <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.accent, marginBottom: 8 }}>▸ SIGNAL / MONTHLY</div>
            <h3 style={{ fontSize: 22, fontWeight: 600, margin: '4px 0 12px', letterSpacing: -0.4 }}>More like this, once a month.</h3>
            <p style={{ fontSize: 14, lineHeight: 1.55, color: t.sub, margin: '0 0 20px' }}>
              Essays and field notes on enterprise tech and AI. Four thousand readers.
              Unsubscribe in one click.
            </p>
            <SgButton t={t} onClick={() => navigate('/contact', { form: 'signal' })}>Subscribe →</SgButton>
          </div>

          <div style={{ marginTop: 56, display: 'flex', justifyContent: 'space-between', gap: 20 }}>
            {prev ? (
              <button onClick={() => navigate('/insights', { id: prev.id })}
                style={{ textAlign: 'left', cursor: 'pointer', background: 'transparent', border: `1px solid ${t.rule}`, borderRadius: 10, padding: '16px 20px', flex: 1, color: t.ink, fontFamily: 'inherit' }}>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: t.sub, marginBottom: 6 }}>← PREVIOUS</div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{prev.title}</div>
              </button>
            ) : <div style={{ flex: 1 }} />}
            {next ? (
              <button onClick={() => navigate('/insights', { id: next.id })}
                style={{ textAlign: 'right', cursor: 'pointer', background: 'transparent', border: `1px solid ${t.rule}`, borderRadius: 10, padding: '16px 20px', flex: 1, color: t.ink, fontFamily: 'inherit' }}>
                <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 10, color: t.sub, marginBottom: 6 }}>NEXT →</div>
                <div style={{ fontSize: 14, fontWeight: 500 }}>{next.title}</div>
              </button>
            ) : <div style={{ flex: 1 }} />}
          </div>
        </article>
      </div>
      <style>{`
        @keyframes sgDrawerIn { from { transform: translateX(40px); opacity: 0 } to { transform: none; opacity: 1 } }
      `}</style>
    </div>,
    document.body,
  );
}

function NewsletterBlock({ t, navigate }) {
  const [email, setEmail] = React.useState('');
  const [state, setState] = React.useState('idle');
  const submit = (e) => {
    e.preventDefault();
    if (!email.includes('@')) { setState('err'); return; }
    setState('loading');
    setTimeout(() => setState('ok'), 700);
  };
  return (
    <section style={{ padding: '80px 48px', borderTop: `1px solid ${t.rule}`, background: t.bgAlt }}>
      <div style={{ maxWidth: 820, margin: '0 auto', textAlign: 'center' }}>
        <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.accent, marginBottom: 16 }}>▸ signal // monthly</div>
        <h2 style={{ fontSize: 44, fontWeight: 500, letterSpacing: -1.4, margin: 0, lineHeight: 1.05 }}>
          One essay a month. Four thousand readers.
        </h2>
        <p style={{ fontSize: 16, color: t.sub, marginTop: 16, lineHeight: 1.55 }}>
          No growth hacks. No summaries of other people's writing. Unsubscribe in one click.
        </p>
        <form onSubmit={submit} style={{ marginTop: 32, display: 'flex', gap: 10, maxWidth: 460, margin: '32px auto 0' }}>
          <input
            type="email" value={email} onChange={(e) => { setEmail(e.target.value); setState('idle'); }}
            placeholder="your@work-email.com" disabled={state === 'ok'}
            style={{
              flex: 1, padding: '14px 18px', fontSize: 15, fontFamily: 'inherit',
              background: t.card, color: t.ink,
              border: `1px solid ${state === 'err' ? t.accent2 : t.rule}`, borderRadius: 8, outline: 'none',
            }} />
          <SgButton t={t} onClick={submit} as="button">
            {state === 'loading' ? '…' : state === 'ok' ? '✓' : 'Subscribe →'}
          </SgButton>
        </form>
        {state === 'err' && <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.accent2, marginTop: 10 }}>please enter a valid email</div>}
        {state === 'ok' && <div style={{ fontFamily: 'JetBrains Mono, monospace', fontSize: 11, color: t.accent, marginTop: 10 }}>✓ subscribed — check your inbox</div>}
      </div>
    </section>
  );
}

Object.assign(window, { PageInsights, NewsletterBlock });
