// Insights page — editorial layout, real thumbnails, searchable & filterable
function PageInsights({ setPage }) {
  useReveal();
  const t = useT();
  const [filter, setFilter] = React.useState('Todos');
  const [query, setQuery] = React.useState('');
  const [sort, setSort] = React.useState('recent'); // 'recent' | 'short'

  // Lookup maps: Portuguese key → translated label
  const tagMap = { 'Ensaio': t('is.t.essay'), 'Pesquisa': t('is.t.research'), 'Entrevista': t('is.t.interview'), 'Case': t('is.t.case'), 'Artigo': t('is.t.article') };
  const catMap = { 'Todos': t('c.filter_all'), 'Arquitetura': t('is.c.arch'), 'IA': t('is.c.ia'), 'Saúde': t('is.c.health') };
  const roleMap = { 'Fundador & Tech Lead': t('is.r.founder'), 'Pesquisa': t('is.r.research'), 'Product Designer': t('is.r.designer'), 'Software Engineer': t('is.r.engineer') };
  const ptMonthKey = { 'jan': 'is.m.jan', 'fev': 'is.m.feb', 'mar': 'is.m.mar', 'abr': 'is.m.apr', 'mai': 'is.m.may', 'jun': 'is.m.jun', 'jul': 'is.m.jul', 'ago': 'is.m.aug', 'set': 'is.m.sep', 'out': 'is.m.oct', 'nov': 'is.m.nov', 'dez': 'is.m.dec' };
  const txDate = (d) => { const p = d.split(' '); return p.length === 2 ? p[0] + ' ' + (ptMonthKey[p[1]] ? t(ptMonthKey[p[1]]) : p[1]) : d; };
  const txCat = (c) => catMap[c] || c;
  const txTag = (tag) => tagMap[tag] || tag;
  const txRole = (r) => roleMap[r] || r;

  // Each post has a visual kind that maps to InsightVisual + metadata
  const posts = [
    { id: 1, kind: 'ensaio',    tag: 'Ensaio',     cat: 'Arquitetura', t: 'O fim da arquitetura de microsserviços (como conhecemos)', d: 'Por que modulitos venceram a guerra silenciosamente. Quando o custo operacional de 42 serviços supera o acoplamento de um monolito bem modularizado.', time: 8,  date: '14 abr', featured: true, author: 'Felipe Castelini', authorRole: 'Fundador & Tech Lead' },
    { id: 2, kind: 'pesquisa',  tag: 'Pesquisa',   cat: 'IA',          t: 'Estado da IA aplicada no Brasil — 2026', d: 'Relatório anual com 240 empresas entrevistadas sobre adoção, maturidade e ROI de iniciativas de IA em produção.', time: 44, date: '02 abr', pages: true, author: 'Equipe Atom Forge', authorRole: 'Pesquisa' },
    { id: 3, kind: 'entrevista',tag: 'Entrevista', cat: 'Design',      t: 'Design systems como infraestrutura, não biblioteca', d: 'Conversa sobre tokens, governança e por que um design system precisa do mesmo rigor que uma API pública.', time: 22, date: '28 mar', author: 'Larissa Matos', authorRole: 'Product Designer' },
    { id: 4, kind: 'pesquisa',  tag: 'Case',       cat: 'Fintech',     t: 'Como replatformamos um core bancário em 9 meses', d: 'Migração com zero downtime para uma malha de serviços em Go. Sob NDA — sem nome de cliente, com métrica real.', time: 12, date: '21 mar', author: 'Pedro Alves', authorRole: 'Software Engineer' },
    { id: 5, kind: 'ensaio',    tag: 'Artigo',     cat: 'Cloud',       t: 'FinOps não é sobre cortar — é sobre ver', d: 'Como reduzimos 38% do custo de cloud de um cliente sem cortar nenhum workload.', time: 6,  date: '14 mar', author: 'Felipe Castelini', authorRole: 'Fundador & Tech Lead' },
    { id: 6, kind: 'entrevista',tag: 'Ensaio',     cat: 'IA',          t: 'Agentes que ouvem antes de responder', d: 'Copilotos de domínio exigem uma nova gramática de interação. Dados, contexto e permissão, nessa ordem.', time: 10, date: '07 mar', author: 'Felipe Castelini', authorRole: 'Fundador & Tech Lead' },
    { id: 7, kind: 'ensaio',    tag: 'Case',       cat: 'Saúde',       t: 'Triagem assistida por IA, auditada por médicos', d: 'Protocolos versionados, decisões rastreáveis, LGPD desde o dia 1. Projeto sob NDA.', time: 9,  date: '28 fev', author: 'Pedro Alves', authorRole: 'Software Engineer' },
    { id: 8, kind: 'entrevista',tag: 'Artigo',     cat: 'Design',      t: 'Escrita de UI — a diferença entre "Salvar" e "Guardar"', d: 'Quatro regras que aprendemos errando em produtos que rodam em escala nacional.', time: 5,  date: '21 fev', author: 'Larissa Matos', authorRole: 'Product Designer' },
    { id: 9, kind: 'pesquisa',  tag: 'Pesquisa',   cat: 'Arquitetura', t: 'Benchmark — latência de 12 bancos digitais brasileiros', d: 'P99 de APIs públicas medido por 30 dias. Resultados podem surpreender.', time: 16, date: '14 fev', author: 'Equipe Atom Forge', authorRole: 'Pesquisa' },
  ];

  const cats = ['Todos', 'Arquitetura', 'IA', 'Design', 'Fintech', 'Cloud', 'Saúde'];

  let visible = posts;
  if (filter !== 'Todos') {
    visible = visible.filter(p => p.cat === filter);
  } else if (!query.trim()) {
    const seen = new Set();
    visible = posts.filter(p => { if (seen.has(p.cat)) return false; seen.add(p.cat); return true; });
  }
  if (query.trim()) {
    const q = query.toLowerCase();
    visible = visible.filter(p => (p.t + ' ' + p.d + ' ' + p.cat + ' ' + p.tag).toLowerCase().includes(q));
  }
  if (sort === 'short') visible = [...visible].sort((a, b) => a.time - b.time);

  const featured = posts.find(p => p.featured);
  const rest = visible.filter(p => !(filter === 'Todos' && !query && p === featured));

  return (
    <>
      {/* HERO — compact, editorial */}
      <section style={{ padding: '72px 0 40px', position: 'relative', overflow: 'hidden' }}>
        <div className="tick-grid" />
        <div className="shell" style={{ position: 'relative' }}>
          <Eyebrow>{t('is.ey')}</Eyebrow>
          <h1 className="display" style={{ fontSize: 'clamp(40px, 7vw, 104px)', margin: '20px 0 28px', maxWidth: '16ch', lineHeight: 0.98 }}>
            {t('is.h1a')}{' '}
            <em className="display-italic" style={{ color: 'var(--crimson)' }}>{t('is.h1em')}</em>{' '}
            {t('is.h1b')}
          </h1>
          <p style={{ fontSize: 17, opacity: 0.72, maxWidth: 580, lineHeight: 1.55, margin: 0 }}>
            {t('is.sub')}
          </p>
        </div>
      </section>

      {/* FEATURED — editorial hero (only when no filter/search) */}
      {featured && filter === 'Todos' && !query && (
        <section style={{ padding: '40px 0 64px' }}>
          <div className="shell">
            <Reveal>
              <a href="#" onClick={(e) => { e.preventDefault(); setPage('insight-' + featured.id); }} className="feat-grid card-hover" style={{
                display: 'grid',
                gridTemplateColumns: '1.15fr 1fr',
                gap: 48,
                alignItems: 'stretch',
                textDecoration: 'none',
              }}>
                <div style={{
                  aspectRatio: '5 / 4',
                  background: 'var(--bg-2)',
                  borderRadius: 22,
                  position: 'relative',
                  overflow: 'hidden',
                  border: '1px solid var(--line)',
                }}>
                  <InsightVisualByCat cat={featured.cat} />
                  <div style={{ position: 'absolute', top: 20, left: 20, display: 'flex', gap: 6 }}>
                    <Chip>{t('is.featured')}</Chip>
                    <Chip>{featured.cat}</Chip>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '24px 0' }}>
                  <div style={{ fontFamily: 'var(--mono)', fontSize: 11, textTransform: 'uppercase', letterSpacing: '0.14em', opacity: 0.55 }}>
                    {txTag(featured.tag)} · {featured.time} min · {txDate(featured.date)}
                  </div>
                  <h2 className="display" style={{
                    fontSize: 'clamp(32px, 4vw, 56px)',
                    margin: '18px 0 18px',
                    lineHeight: 1.02,
                  }}>{featured.t}</h2>
                  <p style={{ fontSize: 17, opacity: 0.75, lineHeight: 1.55, marginBottom: 20, maxWidth: 52 + 'ch' }}>{featured.d}</p>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 24 }}>
                    <div style={{
                      width: 32, height: 32, borderRadius: '50%',
                      background: 'var(--crimson)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontFamily: 'var(--mono)', fontSize: 11, fontWeight: 700, color: '#fff', flexShrink: 0,
                    }}>{featured.author.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.2 }}>{featured.author}</div>
                      <div style={{ fontSize: 11, opacity: 0.55, fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{txRole(featured.authorRole)}</div>
                    </div>
                  </div>
                  <div style={{ display: 'inline-flex', alignItems: 'center', gap: 10, color: 'var(--crimson)', fontSize: 14, fontWeight: 500 }}>
                    {t('is.read')}
                    <svg width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M3 11L11 3M11 3H5M11 3V9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                  </div>
                </div>
              </a>
            </Reveal>
          </div>
        </section>
      )}

      {/* FILTER + SEARCH bar */}
      <div style={{
        position: 'sticky', top: 72, zIndex: 40,
        background: 'color-mix(in srgb, var(--bg) 90%, transparent)',
        backdropFilter: 'blur(10px)',
        borderTop: '1px solid var(--line)',
        borderBottom: '1px solid var(--line)',
      }}>
        <div className="shell" style={{
          display: 'flex', gap: 16, padding: '14px 0', alignItems: 'center', flexWrap: 'wrap',
        }}>
          <div style={{ display: 'flex', gap: 6, overflowX: 'auto', flex: 1, minWidth: 0 }}>
            {cats.map(c => (
              <button key={c} onClick={() => setFilter(c)} style={{
                padding: '8px 14px',
                borderRadius: 999,
                fontSize: 13,
                background: filter === c ? 'var(--ink)' : 'transparent',
                color: filter === c ? 'var(--bg)' : 'var(--ink-dim)',
                border: filter === c ? 'none' : '1px solid var(--line)',
                whiteSpace: 'nowrap',
                transition: 'all 0.2s',
                fontWeight: filter === c ? 600 : 400,
              }}>
                {txCat(c)}
              </button>
            ))}
          </div>
          <div style={{
            display: 'flex', alignItems: 'center', gap: 10,
            padding: '8px 14px',
            border: '1px solid var(--line)',
            borderRadius: 999,
            background: 'var(--bg-2)',
            minWidth: 220,
          }}>
            <svg width="14" height="14" viewBox="0 0 14 14" fill="none" style={{ opacity: 0.5 }}>
              <circle cx="6" cy="6" r="4.5" stroke="currentColor" strokeWidth="1.3"/>
              <path d="M9.5 9.5L12.5 12.5" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round"/>
            </svg>
            <input
              value={query}
              onChange={(e) => setQuery(e.target.value)}
              placeholder={t('is.search_ph')}
              style={{
                flex: 1, background: 'transparent', border: 'none', outline: 'none',
                fontFamily: 'var(--sans)', fontSize: 13, color: 'var(--ink)',
              }}
            />
            {query && (
              <button onClick={() => setQuery('')} style={{ opacity: 0.5, fontSize: 14, padding: 0, lineHeight: 1 }}>×</button>
            )}
          </div>
          <div style={{ display: 'flex', gap: 4, border: '1px solid var(--line)', borderRadius: 999, padding: 3 }}>
            {[['recent', t('is.sort_recent')], ['short', t('is.sort_short')]].map(([k, l]) => (
              <button key={k} onClick={() => setSort(k)} style={{
                padding: '6px 12px', borderRadius: 999, fontSize: 12,
                background: sort === k ? 'var(--crimson)' : 'transparent',
                color: sort === k ? 'var(--ink)' : 'var(--ink-dim)',
                fontWeight: sort === k ? 600 : 400,
                transition: 'all 0.2s',
              }}>{l}</button>
            ))}
          </div>
        </div>
      </div>

      {/* RESULTS COUNT */}
      <section style={{ paddingTop: 32 }}>
        <div className="shell">
          <div className="eyebrow" style={{ opacity: 0.6 }}>
            {visible.length} {visible.length === 1 ? t('is.pub1') : t('is.pub_n')}
            {filter !== 'Todos' && ` ${t('is.in_cat')} ${txCat(filter)}`}
            {query && ` · ${t('is.searching')} "${query}"`}
          </div>
        </div>
      </section>

      {/* GRID */}
      <section className="section-pad-sm" style={{ paddingTop: 20 }}>
        <div className="shell">
          {rest.length === 0 ? (
            <div style={{
              padding: '80px 0', textAlign: 'center',
              border: '1px dashed var(--line)', borderRadius: 18,
            }}>
              <div className="display" style={{ fontSize: 32, marginBottom: 12 }}>{t('is.empty_h')}</div>
              <p style={{ opacity: 0.6, fontSize: 15 }}>{t('is.empty_p')}</p>
            </div>
          ) : (
            <div className="grid grid-3 insights-grid">
              {rest.map((p, i) => (
                <Reveal key={p.id} delay={(i % 3) * 50}>
                  <article className="card-hover" onClick={() => setPage('insight-' + p.id)} style={{ cursor: 'pointer', display: 'flex', flexDirection: 'column', height: '100%' }}>
                    <div style={{
                      aspectRatio: '4 / 3',
                      background: 'var(--bg-2)',
                      borderRadius: 14,
                      marginBottom: 18,
                      position: 'relative',
                      overflow: 'hidden',
                      border: '1px solid var(--line)',
                    }}>
                      <InsightVisualByCat cat={p.cat} />
                      <div style={{ position: 'absolute', top: 14, left: 14, display: 'flex', gap: 6 }}>
                        <Chip>{txCat(p.cat)}</Chip>
                      </div>
                      <div style={{
                        position: 'absolute', bottom: 14, right: 14,
                        padding: '4px 10px', borderRadius: 999,
                        background: 'color-mix(in srgb, var(--bg) 70%, transparent)',
                        backdropFilter: 'blur(6px)',
                        fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.08em', textTransform: 'uppercase',
                      }}>
                        {p.time} {p.pages ? 'pg' : 'min'}
                      </div>
                    </div>
                    <div style={{
                      fontFamily: 'var(--mono)', fontSize: 11, textTransform: 'uppercase',
                      letterSpacing: '0.12em', opacity: 0.55, marginBottom: 10,
                    }}>
                      {txTag(p.tag)} · {txDate(p.date)}
                    </div>
                    <h3 className="display" style={{ fontSize: 22, margin: '0 0 10px', lineHeight: 1.12 }}>{p.t}</h3>
                    <p style={{ opacity: 0.72, fontSize: 14, lineHeight: 1.55, margin: '0 0 16px' }}>{p.d}</p>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 'auto' }}>
                      <div style={{
                        width: 28, height: 28, borderRadius: '50%',
                        background: 'var(--crimson)', display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontFamily: 'var(--mono)', fontSize: 10, fontWeight: 700, color: '#fff', flexShrink: 0,
                      }}>{p.author.split(' ').map(w => w[0]).slice(0,2).join('')}</div>
                      <div>
                        <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.2 }}>{p.author}</div>
                        <div style={{ fontSize: 11, opacity: 0.55, fontFamily: 'var(--mono)', textTransform: 'uppercase', letterSpacing: '0.08em' }}>{txRole(p.authorRole)}</div>
                      </div>
                    </div>
                  </article>
                </Reveal>
              ))}
            </div>
          )}
        </div>
      </section>

      {/* NEWSLETTER */}
      <section className="surface-dark section-pad" style={{ position: 'relative', overflow: 'hidden', marginTop: 80 }}>
        <div className="orb" style={{ width: 540, height: 540, background: 'var(--crimson-deep)', top: '-40%', right: '10%', opacity: 0.3 }} />
        <div className="shell news-grid" style={{ position: 'relative', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80, alignItems: 'center' }}>
          <div>
            <Eyebrow dark>{t('is.news_ey')}</Eyebrow>
            <h2 className="display" style={{ fontSize: 'clamp(40px, 5.5vw, 80px)', margin: '20px 0' }}>
              {t('is.news_h2a')} <em className="display-italic" style={{ color: 'var(--crimson)' }}>{t('is.news_em')}</em> {t('is.news_h2b')}
            </h2>
            <p style={{ fontSize: 17, opacity: 0.72, lineHeight: 1.55, maxWidth: 460 }}>
              {t('is.news_sub')}
            </p>
          </div>
          <form onSubmit={(e) => e.preventDefault()} style={{
            display: 'flex', gap: 0, padding: 6,
            border: '1px solid rgba(237,235,230,0.2)', borderRadius: 999,
            background: 'rgba(237,235,230,0.04)',
          }}>
            <input type="email" placeholder="voce@empresa.com.br" style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              padding: '14px 20px', color: 'var(--ink)',
              fontFamily: 'var(--mono)', fontSize: 14,
            }} />
            <button style={{
              padding: '14px 24px', background: 'var(--crimson)', color: 'var(--ink)',
              borderRadius: 999, fontSize: 14, fontWeight: 500,
            }}>{t('is.news_sub_btn')}</button>
          </form>
        </div>
      </section>

      <style>{`
        @media (max-width: 980px) {
          .feat-grid, .news-grid { grid-template-columns: 1fr !important; gap: 24px !important; }
          .insights-grid { grid-template-columns: 1fr !important; }
        }
      `}</style>
    </>
  );
}

Object.assign(window, { PageInsights });
