/* DEV · Início — cockpit do Digi por si próprio.
   Para o Fábio Costa, que aterra aqui directamente ao fazer login.

   8 blocos, ordenados por hierarquia operacional:
   1. Hero (saudação + 1-line health)
   2. Chat Digi embedded (header avatar + briefing inline + 1 turno + input)
   3. 4 Modos (Clientes/Colaboradores/Dev/Board · saúde por modo)
   4. Inbox · "Pede a tua atenção"
   5. Pipelines (3) + Módulos (7)
   6. Build (6 cards)
   7. Operação (4 cards)
   8. Integrações + Roadmap Paulino

   Mantém dark theme. Mock estático de chat — Enter/Enviar abre fullscreen via onOpenChat. */

// ─── CHAT EMBEDDED · meia altura ──────────────────────────
const DevChatModule = ({ user, onOpenChat, onNavigate }) => {
  const [draft, setDraft] = React.useState('');
  const scrollRef = React.useRef(null);
  const userInitials = (user?.nome || 'FC').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();

  const submit = (text) => {
    const t = (text != null ? text : draft).trim();
    if (!t) return;
    if (onOpenChat) onOpenChat({ initialMessage: t });
    setDraft('');
  };

  const Bubble = ({ from, children, time }) => (
    <div style={{
      display: 'flex', gap: 10, marginBottom: 12,
      flexDirection: from === 'user' ? 'row-reverse' : 'row',
      alignItems: 'flex-start',
    }}>
      <div style={{
        width: 26, height: 26, borderRadius: '50%', flexShrink: 0,
        display: 'grid', placeItems: 'center',
        background: from === 'digi'
          ? 'color-mix(in oklch, var(--ai-500) 25%, transparent)'
          : 'var(--bg-elev)',
        color: from === 'digi' ? 'var(--ai-500)' : 'var(--text-muted)',
        fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-mono)',
        border: from === 'digi' ? '1px solid color-mix(in oklch, var(--ai-500) 35%, transparent)' : '1px solid var(--border)',
      }}>
        {from === 'digi' ? <Icon name="sparkle" size={12} /> : userInitials}
      </div>
      <div style={{ minWidth: 0, maxWidth: '78%' }}>
        <div style={{
          padding: '8px 12px', borderRadius: 10,
          background: from === 'user' ? 'color-mix(in oklch, var(--ai-500) 20%, transparent)' : 'var(--bg-elev)',
          border: '1px solid ' + (from === 'user' ? 'color-mix(in oklch, var(--ai-500) 30%, transparent)' : 'var(--border)'),
          fontSize: 12.5, lineHeight: 1.55, color: 'var(--text)',
        }}>
          {children}
        </div>
        {time && (
          <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 3, textAlign: from === 'user' ? 'right' : 'left' }}>{time}</div>
        )}
      </div>
    </div>
  );

  return (
    <div style={{
      height: 480,                                  // meia altura aprox
      borderRadius: 12,
      border: '1px solid var(--border)',
      background: 'var(--bg-elev)',
      display: 'flex', flexDirection: 'column',
      overflow: 'hidden',
      marginBottom: 22,
    }}>
      {/* header */}
      <div style={{
        padding: '10px 14px', borderBottom: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 10, flexShrink: 0,
        background: 'var(--bg-sunken)',
      }}>
        <div style={{
          width: 28, height: 28, borderRadius: '50%',
          background: 'color-mix(in oklch, var(--ai-500) 28%, transparent)',
          color: 'var(--ai-500)',
          display: 'grid', placeItems: 'center',
          border: '1px solid color-mix(in oklch, var(--ai-500) 40%, transparent)',
        }}>
          <Icon name="sparkle" size={13} />
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div className="font-display" style={{ fontSize: 13, fontWeight: 600, letterSpacing: '0.02em' }}>Digi</div>
          <div style={{ fontSize: 10, color: 'var(--success)', display: 'flex', alignItems: 'center', gap: 5, fontFamily: 'var(--font-mono)' }}>
            <span style={{ width: 5, height: 5, borderRadius: '50%', background: 'var(--success)' }} />
            online · mesma conversa do WhatsApp
          </div>
        </div>
        <button onClick={() => onOpenChat && onOpenChat()} className="btn btn-xs btn-ghost" style={{ padding: '4px 8px' }}>
          <Icon name="sparkle" size={11} style={{ color: 'var(--ai-500)' }} />
          <span style={{ marginLeft: 4 }}>Abrir</span>
        </button>
      </div>

      {/* messages */}
      <div ref={scrollRef} style={{ flex: 1, minHeight: 0, overflowY: 'auto' }} className="scrollbar">
        <div style={{ maxWidth: 720, margin: '0 auto', padding: '14px 18px' }}>
          {/* date divider */}
          <div style={{ textAlign: 'center', margin: '0 0 14px', fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
            <span style={{ padding: '2px 8px', background: 'var(--bg)', borderRadius: 10, border: '1px solid var(--border)' }}>
              {new Date().toLocaleDateString('pt-PT', { weekday: 'long', day: '2-digit', month: 'short' }).toUpperCase()}
            </span>
          </div>

          {/* 1. Briefing inicial */}
          <Bubble from="digi" time="08:00">
            Bom dia, {(user?.nome || 'Fábio').split(' ')[0]}. Hoje tens 3 prioridades:
            <ol style={{ margin: '8px 0 4px 18px', padding: 0, fontSize: 12, lineHeight: 1.7, color: 'var(--text-muted)' }}>
              <li>Aprovar deploy <strong className="font-mono" style={{ color: 'var(--ai-500)' }}>FRAME-GESTAO-TICKETS</strong> (low risk · 94% cobertura)</li>
              <li>Pingar <strong style={{ color: 'var(--text)' }}>Sónia Casimiro</strong> sobre <strong>quality_kb</strong> — parado há 14 dias</li>
              <li>Decidir fallback Sonnet em <strong>sales · clientes</strong> — Opus +23% WoW</li>
            </ol>
          </Bubble>

          {/* 2. Card inline · deploy staged */}
          <div style={{ display: 'flex', gap: 10, marginBottom: 12, alignItems: 'flex-start' }}>
            <div style={{ width: 26, flexShrink: 0 }} />
            <div style={{
              maxWidth: '78%', minWidth: 0, padding: 12, borderRadius: 10,
              border: '1px solid var(--border)', background: 'var(--bg)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6 }}>
                <span style={{
                  padding: '2px 7px', fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em',
                  borderRadius: 3, fontFamily: 'var(--font-mono)',
                  background: 'oklch(0.3 0.14 30)', color: 'oklch(0.85 0.18 30)',
                }}>URGENTE · DEPLOY STAGED</span>
              </div>
              <div className="font-display" style={{ fontSize: 14, fontWeight: 600, marginBottom: 4 }}>
                FRAME-GESTAO-TICKETS aguarda há 2h
              </div>
              <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.55, marginBottom: 10 }}>
                Owner: <strong style={{ color: 'var(--text)' }}>João Pedro Paulino</strong>. Diff +42 / −18 · cobertura 94% · risco baixo. Sub-módulo SAT, novo flow de gestão de tickets Mimaki.
              </div>
              <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
                <button onClick={() => onNavigate && onNavigate('deploy')} className="btn btn-xs btn-ai">
                  <Icon name="zap" size={11} />Rever diff
                </button>
                <button className="btn btn-xs">
                  <Icon name="check" size={11} />Aprovar
                </button>
                <button className="btn btn-xs btn-ghost">Adiar 1h</button>
              </div>
            </div>
          </div>

          {/* 3. utilizador responde */}
          <Bubble from="user" time="09:14">
            Bom dia. Abre-me o diff do FRAME-GESTAO-TICKETS.
          </Bubble>

          {/* 4. Digi confirma */}
          <Bubble from="digi" time="09:14">
            A abrir. Resumo rápido: 3 ficheiros, 4 prompts novos para gestão Mimaki via Gestor SAT, 0 breaking changes nos prompts existentes. Cobertura testes a 94% (acima do limiar 85%). <strong style={{ color: 'var(--ai-500)' }}>Recomendo aprovar.</strong>
          </Bubble>

          {/* quick replies */}
          <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 8, marginLeft: 36 }}>
            {['Aprovar agora', 'Mostra os 4 prompts', 'Quem testou?', 'Ping ao Paulino'].map(s => (
              <button key={s} onClick={() => submit(s)} className="btn btn-xs btn-ghost" style={{ borderRadius: 14, fontSize: 11 }}>
                {s}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* input */}
      <div style={{
        padding: '10px 14px', borderTop: '1px solid var(--border)',
        display: 'flex', alignItems: 'center', gap: 8, flexShrink: 0,
        background: 'var(--bg-sunken)',
      }}>
        <button className="btn btn-xs btn-ghost" style={{ padding: 4, flexShrink: 0 }} title="Anexar">
          <Icon name="plus" size={13} />
        </button>
        <input
          type="text"
          value={draft}
          onChange={(e) => setDraft(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); submit(); } }}
          placeholder="Escreve uma mensagem como humano…"
          style={{
            flex: 1, background: 'var(--bg)', color: 'var(--text)',
            border: '1px solid var(--border)', borderRadius: 8,
            padding: '7px 11px', fontSize: 12.5, outline: 'none',
            fontFamily: 'inherit',
          }}
        />
        <button onClick={() => submit()} className="btn btn-xs btn-ai" style={{ flexShrink: 0 }}>
          <Icon name="send" size={11} />Enviar
        </button>
      </div>
    </div>
  );
};

const DevInicio = ({ user, onNavigate, onOpenChat }) => {
  const goto = (id) => { if (id && onNavigate) onNavigate(id); };

  // ─── 4 MODOS ──────────────────────────────────────────────
  const modos = [
    { id: 'clientes', name: 'CLIENTES', sub: '3 pipelines · 10 funções', conv: 142, status: 'warn',
      detail: 'Aquisição ✓ · Serviço ✓ · Crescimento ⏳ por construir', flag: '2 flagged' },
    { id: 'colaboradores', name: 'COLABORADORES', sub: '7 módulos · 193 colab.', conv: 312, status: 'ok',
      detail: 'Sales · SAT · OPS · MKT · FIN · HR · BI', flag: 'saudável' },
    { id: 'dev', name: 'DEV', sub: '5 utilizadores', conv: 18, status: 'ok',
      detail: 'FC · RL · JP · FS · MF · acesso total', flag: 'tu estás aqui' },
    { id: 'board', name: 'BOARD', sub: '3 utilizadores', conv: 0, status: 'idle',
      detail: 'Chairman · CEO · CFO · visão estratégica', flag: 'sem actividade' },
  ];

  // ─── INBOX ─────────────────────────────────────────────────
  const triage = [
    { id: 'd1', sev: 'high', icon: 'zap',     title: '1 deploy aguarda aprovação',
      desc: 'FRAME-GESTAO-TICKETS · staging há 2h · diff +42 / −18 · risco baixo (cobertura 94%). Owner: João Pedro.',
      cta: 'Rever diff', target: 'deploy', meta: 'staging · 2h' },
    { id: 'd2', sev: 'high', icon: 'alert',   title: 'KB · quality_kb pendente há 14 dias',
      desc: 'Source aguarda Sónia Casimiro. Bloqueia HNSW reindex e qualidade de retrieval em SP_CLIENTES.',
      cta: 'Pingar Sónia', target: 'kb', meta: 'kb.quality_kb' },
    { id: 'd3', sev: 'med',  icon: 'doc',     title: '3 prompts flagged em revisão',
      desc: 'SP_FINANCEIRO_AGING (2 conversas com hallucination), FRAME_OBJECCOES_PRECO (1 com tom errado).',
      cta: 'Ver flagged', target: 'prompts', meta: '7 conversas' },
    { id: 'd4', sev: 'med',  icon: 'dollar',  title: 'Anthropic Opus spike +23% WoW',
      desc: 'Aumento concentrado em sales · clientes (sub-modo). Avaliar fallback para Sonnet em queries simples.',
      cta: 'Abrir Costs', target: 'costs', meta: 'cost.anthropic.opus' },
    { id: 'd5', sev: 'low',  icon: 'database', title: 'Postgres · 61G livres',
      desc: 'Tendência de descida 1.2GB/dia. Threshold de alerta: 20GB. Estimativa: ~34 dias.',
      cta: 'Ver infra', target: 'integracoes', meta: 'infra.postgres' },
  ];

  // ─── PIPELINES + MÓDULOS ───────────────────────────────────
  const pipelines = [
    { id: 'aquisicao', name: 'Aquisição', desc: 'Qualificação + Nurturing + AllDecor', funcs: 3, status: 'ok',  meta: '18 conv/24h' },
    { id: 'servico',   name: 'Serviço',   desc: 'Help Desk + Tickets + Encomendas + Logística + Docs', funcs: 6, status: 'warn', meta: '9 conv/24h · 1 flag' },
    { id: 'crescim',   name: 'Crescimento', desc: 'Recompra + Upsell + Cross-sell + Reactivação', funcs: 1, status: 'pending', meta: 'P3 · por construir' },
  ];
  const modulos = [
    { name: 'Sales',      v: 'v4.0', status: 'ok',     n: 'DIG, DIM, NS, TAS, SNK' },
    { name: 'SAT',        v: 'v3.0', status: 'ok',     n: 'DIG, DIM, NS, TAS' },
    { name: 'Operations', v: 'v4.0', status: 'ok',     n: 'DIG SA · 6 dept × 3 níveis' },
    { name: 'Marketing',  v: 'v3.0', status: 'ok',     n: 'Farben · 7 marcas' },
    { name: 'Finance',    v: 'v3.0', status: 'warn',   n: 'Farben · PT' },
    { name: 'HR',         v: 'v3.0', status: 'ok',     n: 'Farben · todo PT' },
    { name: 'BI',         v: 'v1.0', status: 'pending', n: 'Walter Noia · base' },
  ];

  // ─── BUILD + OPERAÇÃO ──────────────────────────────────────
  const buildCards = [
    { id: 'architecture', icon: 'layers',   label: 'Architecture',  desc: '3 layers · 23 nodes' },
    { id: 'prompts',      icon: 'doc',      label: 'Prompts',       desc: '8 SP · 22 FRAMEs',   badge: '3 flag' },
    { id: 'kb',           icon: 'bi',       label: 'Knowledge Base',desc: '15 sources · 83.551 chunks', badge: 'pendente' },
    { id: 'skills',       icon: 'sparkle',  label: 'Skills',        desc: '7 + 21 por criar' },
    { id: 'agents',       icon: 'sparkle',  label: 'Sub-agentes',   desc: '20 + 4 marcas' },
    { id: 'tools',        icon: 'bolt',     label: 'Tools',         desc: '3 funcionais · 2 pendentes' },
  ];
  const opCards = [
    { id: 'conversations',icon: 'history',  label: 'Replay',     desc: '518 conv · 7 flagged', badge: '7' },
    { id: 'costs',        icon: 'dollar',   label: 'Costs',      desc: '$67.42 hoje · +23%', badge: 'spike' },
    { id: 'deploy',       icon: 'zap',      label: 'Deploy',     desc: '1 staged · low risk', badge: '1' },
    { id: 'routing',      icon: 'menu',     label: 'Routing',    desc: 'identificar_contacto()' },
  ];

  // ─── INTEGRAÇÕES ──────────────────────────────────────────
  const integ = [
    { name: 'Gestor CRM',     status: 'ok' },
    { name: 'Gestor SAT',     status: 'ok' },
    { name: 'KB Postgres',    status: 'ok' },
    { name: 'BD Colab.',      status: 'ok' },
    { name: 'Apollo.io',      status: 'ok' },
    { name: 'MS Graph',       status: 'ok' },
    { name: 'ClickUp',        status: 'ok' },
    { name: 'DuckDuckGo',     status: 'ok' },
    { name: 'Primavera v10',  status: 'pending', tag: 'P1' },
    { name: 'ProdTrack',      status: 'pending', tag: 'P1' },
    { name: 'GA4',            status: 'pending', tag: 'P2' },
    { name: 'Meta Ads',       status: 'pending', tag: 'P3' },
    { name: 'Google Ads',     status: 'pending', tag: 'P3' },
    { name: 'VNNOX',          status: 'pending', tag: 'P3' },
    { name: 'fal.ai',         status: 'pending', tag: 'P3' },
    { name: 'Clearbit',       status: 'pending', tag: 'P4' },
  ];

  // ─── ROADMAP ──────────────────────────────────────────────
  const roadmap = [
    { p: 'P1', label: 'BLOQUEIA GO-LIVE', count: 5, done: 1, owner: 'JP', sev: 'high',
      items: ['Processamento ficheiros WA (4/10)', 'Deploy SP_COLABORADORES v3.0', 'Routing dept heydigi.js', 'Contexto dinâmico/sessão', 'identificar_contacto() webhook'] },
    { p: 'P2', label: 'FUNCIONALIDADES-CHAVE', count: 5, done: 0, owner: 'JP + P.Neto', sev: 'med',
      items: ['Layouts Gestor SAT', 'Tools Python no heydigi.js', 'PDFs públicos + sendDocument()', 'GA4 credentials', 'Validar FRAME-TROUBLESHOOTING'] },
    { p: 'P3', label: 'FRAMEWORKS · SKILLS · INTEG.', count: 18, done: 0, owner: 'FC + Claude', sev: 'low',
      items: ['17 FWs (MKT/FIN/OPS/HR/TKT)', '20 SPs sub-agentes', '21 skills por criar', 'quality_kb ingestão', 'APIs: Primavera, ProdTrack, VNNOX, Meta, Google, fal.ai'] },
    { p: 'P4', label: 'PILOTOS', count: 5, done: 0, owner: 'FC + equipas', sev: 'low',
      items: ['Teste E2E WhatsApp', 'Piloto comerciais', 'Piloto SAT', 'Piloto AllDecor', 'Piloto Pipeline 3'] },
  ];

  // ─── helpers ──────────────────────────────────────────────
  const SevBadge = ({ sev }) => {
    const map = {
      high: { bg: 'oklch(0.3 0.14 30)',  fg: 'oklch(0.85 0.18 30)',   label: 'CRÍTICO' },
      med:  { bg: 'oklch(0.32 0.1 70)',  fg: 'oklch(0.85 0.16 70)',   label: 'ATENÇÃO' },
      low:  { bg: 'oklch(0.3 0.04 250)', fg: 'oklch(0.75 0.06 250)',  label: 'INFO' },
    };
    const s = map[sev] || map.low;
    return (
      <span style={{
        padding: '2px 7px', fontSize: 9.5, fontWeight: 700, letterSpacing: '0.06em',
        borderRadius: 3, background: s.bg, color: s.fg, fontFamily: 'var(--font-mono)',
      }}>{s.label}</span>
    );
  };

  const StatusDot = ({ s }) => {
    const c = s === 'ok' ? 'var(--success)'
            : s === 'warn' ? 'oklch(0.78 0.16 70)'
            : s === 'pending' ? 'oklch(0.78 0.12 240)'
            : s === 'idle' ? 'var(--text-dim)'
            : 'var(--text-dim)';
    return <span style={{ width: 7, height: 7, borderRadius: '50%', background: c, display: 'inline-block', flexShrink: 0 }} />;
  };

  const SectionTitle = ({ title, count, suffix }) => (
    <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 10 }}>
      <h2 className="font-display" style={{ margin: 0, fontSize: 14, fontWeight: 600, letterSpacing: '0.02em' }}>{title}</h2>
      <span style={{ fontSize: 11, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{count != null ? `${count} ${suffix || ''}` : suffix}</span>
    </div>
  );

  return (
    <div style={{ flex: 1, overflow: 'auto', background: 'var(--bg)' }}>
      <div style={{ maxWidth: 1320, margin: '0 auto', padding: '24px 28px 80px' }}>

        {/* ─── 1. HERO ────────────────────────────────────── */}
        <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 24, marginBottom: 18 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
              DEV · INÍCIO · {new Date().toLocaleDateString('pt-PT', { weekday: 'long', day: '2-digit', month: 'long' }).toUpperCase()}
            </div>
            <h1 className="font-display" style={{
              margin: '4px 0 6px', fontSize: 28, fontWeight: 600, letterSpacing: '-0.015em',
            }}>
              Bom dia, {user?.nome?.split(' ')[0] || 'Fábio'}.
            </h1>
            <p style={{ margin: 0, fontSize: 13.5, color: 'var(--text-muted)', lineHeight: 1.5, maxWidth: 760 }}>
              Sistema saudável. 5 itens pedem-te atenção hoje — 2 críticos. Custo de ontem $54.18 (+12% WoW). 472 conversas em 24h, latência p95 345ms. Roadmap go-live: <strong style={{ color: 'oklch(0.85 0.18 30)' }}>5 tarefas P1 com Paulino</strong>.
            </p>
          </div>
        </div>

        {/* ─── 2. CHAT DIGI EMBEDDED ─────────────────────── */}
        <DevChatModule user={user} onOpenChat={onOpenChat} onNavigate={onNavigate} />

        {/* ─── 3. 4 MODOS ──────────────────────────────────── */}
        <section style={{ marginBottom: 22 }}>
          <SectionTitle title="4 Modos" count={modos.length} suffix="modos · saúde por modo" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 10 }}>
            {modos.map(m => (
              <div key={m.id} style={{
                padding: 14, borderRadius: 8,
                border: '1px solid var(--border)', background: 'var(--bg-elev)',
              }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
                  <span className="font-display" style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.06em', color: m.id === 'dev' ? 'var(--ai-500)' : 'var(--text)' }}>{m.name}</span>
                  <StatusDot s={m.status} />
                </div>
                <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginBottom: 10 }}>{m.sub}</div>
                <div className="font-display" style={{ fontSize: 22, fontWeight: 600, lineHeight: 1.1 }}>{m.conv}<span style={{ fontSize: 11, color: 'var(--text-dim)', fontWeight: 400, marginLeft: 4 }}>conv/24h</span></div>
                <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 8, lineHeight: 1.4 }}>{m.detail}</div>
                <div style={{ fontSize: 10.5, color: m.status === 'warn' ? 'oklch(0.85 0.16 70)' : 'var(--text-dim)', fontFamily: 'var(--font-mono)', marginTop: 6 }}>{m.flag}</div>
              </div>
            ))}
          </div>
        </section>

        {/* ─── 4. INBOX ─────────────────────────────────────── */}
        <section style={{ marginBottom: 22 }}>
          <SectionTitle title="Pede a tua atenção" count={triage.length} suffix="pendentes" />
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {triage.map(it => (
              <div key={it.id} style={{
                padding: 13, borderRadius: 8,
                border: '1px solid var(--border)', background: 'var(--bg-elev)',
                display: 'grid', gridTemplateColumns: '32px 1fr auto', gap: 12,
                alignItems: 'flex-start',
              }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 7,
                  background: it.sev === 'high' ? 'oklch(0.3 0.14 30)' : it.sev === 'med' ? 'oklch(0.32 0.1 70)' : 'var(--bg-sunken)',
                  color: it.sev === 'high' ? 'oklch(0.85 0.18 30)' : it.sev === 'med' ? 'oklch(0.85 0.16 70)' : 'var(--text-muted)',
                  display: 'grid', placeItems: 'center', flexShrink: 0,
                }}>
                  <Icon name={it.icon} size={15} />
                </div>
                <div style={{ minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                    <SevBadge sev={it.sev} />
                    <span style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{it.meta}</span>
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600, lineHeight: 1.35, marginBottom: 3 }}>{it.title}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5 }}>{it.desc}</div>
                </div>
                <button onClick={() => goto(it.target)} className="btn btn-xs"
                  style={{ flexShrink: 0, alignSelf: 'flex-start' }}>{it.cta}</button>
              </div>
            ))}
          </div>
        </section>

        {/* ─── 5. PIPELINES + MÓDULOS ────────────────────── */}
        <section style={{ marginBottom: 22, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
          <div>
            <SectionTitle title="Pipelines · modo Clientes" count={pipelines.length} suffix="pipelines · 10 funções" />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {pipelines.map(p => (
                <div key={p.id} style={{
                  padding: 12, borderRadius: 8,
                  border: '1px solid var(--border)', background: 'var(--bg-elev)',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 4 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <StatusDot s={p.status} />
                      <span className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>{p.name}</span>
                      <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>{p.funcs} funções</span>
                    </div>
                    <span style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>{p.meta}</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5 }}>{p.desc}</div>
                </div>
              ))}
            </div>
          </div>
          <div>
            <SectionTitle title="Módulos · modo Colaboradores" count={modulos.length} suffix="módulos · 193 colab." />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
              {modulos.map(m => (
                <div key={m.name} style={{
                  padding: '8px 10px', borderRadius: 7,
                  border: '1px solid var(--border)', background: 'var(--bg-elev)',
                  display: 'flex', alignItems: 'center', gap: 8,
                }}>
                  <StatusDot s={m.status} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'baseline', gap: 6 }}>
                      <span style={{ fontSize: 12, fontWeight: 600 }}>{m.name}</span>
                      <span style={{ fontSize: 9.5, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>{m.v}</span>
                    </div>
                    <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.n}</div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>

        {/* ─── 6. BUILD ────────────────────────────────────── */}
        <section style={{ marginBottom: 22 }}>
          <SectionTitle title="Build · o que se constrói" count={buildCards.length} suffix="secções" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 8 }}>
            {buildCards.map(r => (
              <button key={r.id} onClick={() => goto(r.id)} style={{
                textAlign: 'left', padding: 12, borderRadius: 8,
                border: '1px solid var(--border)', background: 'var(--bg-elev)',
                cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 4,
                transition: 'border-color 0.15s, background 0.15s',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--text-muted)'; e.currentTarget.style.background = 'var(--bg-hover)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.background = 'var(--bg-elev)'; }}
              >
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Icon name={r.icon} size={15} />
                  {r.badge && (
                    <span style={{
                      padding: '1px 6px', fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 600,
                      borderRadius: 3, color: 'var(--ai-500)',
                      background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)',
                    }}>{r.badge}</span>
                  )}
                </div>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{r.label}</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{r.desc}</div>
              </button>
            ))}
          </div>
        </section>

        {/* ─── 7. OPERAÇÃO ────────────────────────────────── */}
        <section style={{ marginBottom: 22 }}>
          <SectionTitle title="Operação · o que se executa" count={opCards.length} suffix="secções" />
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8 }}>
            {opCards.map(r => (
              <button key={r.id} onClick={() => goto(r.id)} style={{
                textAlign: 'left', padding: 12, borderRadius: 8,
                border: '1px solid var(--border)', background: 'var(--bg-elev)',
                cursor: 'pointer', display: 'flex', flexDirection: 'column', gap: 4,
                transition: 'border-color 0.15s, background 0.15s',
              }}
              onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--text-muted)'; e.currentTarget.style.background = 'var(--bg-hover)'; }}
              onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.background = 'var(--bg-elev)'; }}
              >
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                  <Icon name={r.icon} size={15} />
                  {r.badge && (
                    <span style={{
                      padding: '1px 6px', fontSize: 9.5, fontFamily: 'var(--font-mono)', fontWeight: 600,
                      borderRadius: 3, color: 'var(--ai-500)',
                      background: 'color-mix(in oklch, var(--ai-500) 14%, transparent)',
                    }}>{r.badge}</span>
                  )}
                </div>
                <div style={{ fontSize: 12, fontWeight: 600 }}>{r.label}</div>
                <div style={{ fontSize: 10.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>{r.desc}</div>
              </button>
            ))}
          </div>
        </section>

        {/* ─── 8. INTEGRAÇÕES + ROADMAP ─────────────────── */}
        <section style={{ display: 'grid', gridTemplateColumns: '1fr 1.2fr', gap: 18 }}>
          <div>
            <SectionTitle title="Integrações · 16 fontes" count={integ.filter(i => i.status === 'ok').length} suffix="/16 funcionais" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 6 }}>
              {integ.map(i => (
                <button key={i.name} onClick={() => goto('integracoes')} style={{
                  padding: '7px 10px', borderRadius: 6,
                  border: '1px solid var(--border)', background: 'var(--bg-elev)',
                  display: 'flex', alignItems: 'center', gap: 8, cursor: 'pointer', textAlign: 'left',
                }}>
                  <StatusDot s={i.status} />
                  <span style={{ flex: 1, fontSize: 11.5 }}>{i.name}</span>
                  {i.tag && (
                    <span style={{ padding: '0 5px', fontSize: 9, fontFamily: 'var(--font-mono)', fontWeight: 700, borderRadius: 2, background: 'var(--bg-sunken)', color: 'var(--text-dim)', letterSpacing: '0.04em' }}>{i.tag}</span>
                  )}
                </button>
              ))}
            </div>
          </div>
          <div>
            <SectionTitle title="Roadmap Paulino · go-live" count={roadmap.reduce((a,b) => a + b.count, 0)} suffix="tarefas · 4 fases" />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {roadmap.map(r => (
                <button key={r.p} onClick={() => goto('roadmap')} style={{
                  padding: 12, borderRadius: 8,
                  border: '1px solid var(--border)', background: 'var(--bg-elev)',
                  textAlign: 'left', cursor: 'pointer', display: 'block',
                }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 6 }}>
                    <span className="font-mono" style={{
                      padding: '2px 6px', borderRadius: 3, fontSize: 10, fontWeight: 700, letterSpacing: '0.04em',
                      background: r.sev === 'high' ? 'oklch(0.3 0.14 30)' : r.sev === 'med' ? 'oklch(0.32 0.1 70)' : 'var(--bg-sunken)',
                      color: r.sev === 'high' ? 'oklch(0.85 0.18 30)' : r.sev === 'med' ? 'oklch(0.85 0.16 70)' : 'var(--text-muted)',
                    }}>{r.p}</span>
                    <span style={{ fontSize: 10.5, fontFamily: 'var(--font-mono)', fontWeight: 700, letterSpacing: '0.06em', color: 'var(--text)' }}>{r.label}</span>
                    <span style={{ flex: 1 }} />
                    <span style={{ fontSize: 10, fontFamily: 'var(--font-mono)', color: 'var(--text-dim)' }}>{r.done}/{r.count} · {r.owner}</span>
                  </div>
                  <div style={{ fontSize: 11, color: 'var(--text-muted)', lineHeight: 1.55 }}>
                    {r.items.slice(0, 3).join(' · ')}{r.items.length > 3 ? ` · +${r.items.length - 3}` : ''}
                  </div>
                  {/* progress bar */}
                  <div style={{ marginTop: 8, height: 3, background: 'var(--bg-sunken)', borderRadius: 2, overflow: 'hidden' }}>
                    <div style={{
                      height: '100%', width: `${(r.done / r.count) * 100}%`,
                      background: r.sev === 'high' ? 'oklch(0.78 0.18 30)' : r.sev === 'med' ? 'oklch(0.78 0.16 70)' : 'var(--ai-500)',
                    }} />
                  </div>
                </button>
              ))}
            </div>
          </div>
        </section>

        {/* ─── Footer · stats line ─────────────────────────── */}
        <div style={{
          marginTop: 22, padding: 14, borderRadius: 8,
          border: '1px solid var(--border)', background: 'var(--bg-sunken)',
          display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 14,
        }}>
          {[
            { k: 'Conversas 24h', v: '472' },
            { k: 'Latência p95', v: '345ms' },
            { k: 'Custo MTD', v: '$1.24k', sub: '75% budget' },
            { k: 'KB chunks', v: '83.551', sub: '+4k pendente' },
            { k: 'Sub-agentes', v: '4 / 24', sub: '20 por criar' },
            { k: 'Skills', v: '7 / 28', sub: '21 por criar' },
          ].map(s => (
            <div key={s.k}>
              <div style={{ fontSize: 9.5, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.06em', textTransform: 'uppercase' }}>{s.k}</div>
              <div className="font-display" style={{ fontSize: 16, fontWeight: 600, lineHeight: 1.1, marginTop: 3 }}>{s.v}</div>
              {s.sub && <div style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }}>{s.sub}</div>}
            </div>
          ))}
        </div>

      </div>
    </div>
  );
};

window.DevInicio = DevInicio;
window.DevChatModule = DevChatModule;
