/* screen_marketing_inicio.jsx
   Marketing · Início — em desenvolvimento.
   Dashboard principal · Digi AI Marketing (thread único com memória)
   Expõe window.MktInicioScreen.
*/

// ─── Mock data — thread Digi AI ────────────────────────────────────────────

const _DIGI_MSGS_MOCK = [
  { role: 'assistant', proactive: false, ts: '11:04',
    text: 'Bom dia Fábio. Ontem aprovaste o briefing UJV150 e a proposta seguiu para o gate FC. Rui já pediu ajuste ao B4 — queres rever agora ou depois do almoço?' },
  { role: 'user', ts: '11:06',
    text: 'Depois do almoço. Como está a Meta Ads da Mimaki?' },
  { role: 'assistant', proactive: false, ts: '11:06',
    text: 'Consumo Q3 em 68% no ritmo previsto. CTR estável a 1.4% (baseline 1.2%). Uma criativo Reels UJV está a puxar a média — 3.1% CTR. Sugiro escalar essa e pausar a estática que está a 0.6%.' },
  { role: 'assistant', proactive: true, ts: '14:32',
    text: 'Fábio, 47 contactos entraram em silêncio há mais de 21 dias — a maioria são leads Mimaki que abriram o WA mas não responderam ao T-7. Preparei um segmento no CRM para reactivação com nova abordagem. Queres rever?' },
];

// ─── KPI cards mock ────────────────────────────────────────────────────────

const _KPIS_MOCK = [
  { label: 'Aprovações à minha espera', value: '4',    status: 'warn',   sub: '2 briefings · 2 campanhas' },
  { label: 'Campanhas em execução',      value: '11',   status: 'ok',     sub: '3 em Copy · 4 em Produção' },
  { label: 'Erros de campanha',          value: '1',    status: 'crit',   sub: 'BIOND — geração prompts' },
  { label: 'Publicações próx. 24h',      value: '7',    status: 'ok',     sub: '4 Meta · 2 LinkedIn · 1 Email' },
  { label: 'Burn rate Q3',               value: '68%',  status: 'ok',     sub: 'Meta Ads Mimaki no ritmo' },
  { label: 'BP cumprimento YTD',         value: '72%',  status: 'warn',   sub: 'Sensek em risco -15%' },
  { label: 'Follow-up 24h fila',         value: '23',   status: 'ok',     sub: '8 T-3 · 7 T-7 · 5 T-14 · 3 T-21' },
  { label: 'ROAS melhor 7d',             value: '4.2×', status: 'ok',     sub: 'Mimaki Reels UJV' },
];

const MktInicioScreen = ({ setSub, userName }) => {
  const hour = new Date().getHours();
  const saudacao = hour < 12 ? 'Bom dia' : hour < 19 ? 'Boa tarde' : 'Boa noite';
  const rawName = userName || (window.currentUser && (window.currentUser.nome_apresentar || window.currentUser.nome)) || '';
  const firstName = rawName.split(' ')[0] || 'Fábio';

  const [chatInput, setChatInput] = React.useState('');
  const [chatBusy, setChatBusy] = React.useState(false);

  // ─── Styles ───────────────────────────────────────────────────────────────
  const cardStyle = { padding: '14px 16px', borderRadius: 10, background: 'var(--bg-sunken)', border: '1px solid var(--border)', display: 'flex', flexDirection: 'column', gap: 4 };
  const titleStyle = { fontSize: 13, fontWeight: 600, color: 'var(--text)', marginBottom: 2 };
  const descStyle  = { fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.6 };
  const sectionLabel = { fontSize: 10, fontFamily: 'var(--font-mono)', letterSpacing: '0.08em', color: 'var(--text-dim)', marginBottom: 10 };
  const subLabel = {
    fontSize: 10, fontWeight: 700, textTransform: 'uppercase', letterSpacing: '0.08em',
    color: 'var(--ai-500, #3859D0)', fontFamily: 'var(--font-mono)', marginBottom: 8, marginTop: 4,
    display: 'flex', alignItems: 'center', gap: 6,
  };
  const dot = (color) => ({ width: 7, height: 7, borderRadius: '50%', background: color, flexShrink: 0, display: 'inline-block' });
  const tableHeader = { fontSize: 10, fontWeight: 700, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', padding: '6px 10px', background: 'var(--bg-sunken)', borderBottom: '1px solid var(--border)' };
  const tableCell   = { fontSize: 12, color: 'var(--text)', padding: '8px 10px', borderBottom: '1px solid var(--border)', lineHeight: 1.5 };
  const tableCellMuted = { ...tableCell, color: 'var(--text-muted)' };

  const statusColor = (s) => s === 'ok' ? 'var(--success)' : s === 'warn' ? 'var(--warning)' : s === 'crit' ? 'var(--danger)' : 'var(--text-dim)';

  const handleSend = () => {
    if (!chatInput.trim()) return;
    setChatBusy(true);
    // Mock — endpoint /api/marketing/digi-ai/chat a criar
    setTimeout(() => { setChatInput(''); setChatBusy(false); }, 800);
  };

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto' }}>

      {/* Page header */}
      <div style={{ padding: '28px 32px 0', flexShrink: 0 }}>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.08em' }}>
          MARKETING · INÍCIO
        </div>
        <h1 className="font-display" style={{ margin: '6px 0 4px', fontSize: 26, fontWeight: 600, letterSpacing: '-0.015em' }}>
          Início
        </h1>
        <div style={{ fontSize: 12, color: 'var(--text-muted)', display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20 }}>
          Dashboard principal · Digi AI Marketing · Sinais dos módulos
          <span style={{
            fontSize: 9, fontFamily: 'var(--font-mono)', letterSpacing: '0.09em', fontWeight: 600,
            padding: '2px 7px', borderRadius: 4,
            background: 'color-mix(in oklch, var(--warning) 12%, transparent)',
            color: 'var(--warning)',
            border: '1px solid color-mix(in oklch, var(--warning) 28%, transparent)',
          }}>EM DESENVOLVIMENTO</span>
        </div>

        <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', marginBottom: 6, letterSpacing: '-0.02em' }}>
          {saudacao}, {firstName}.
        </div>
        <div style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.65, maxWidth: 700, marginBottom: 24 }}>
          Ponto de entrada do módulo Marketing. Digi AI Marketing carregada com SP_MARKETING, 8 FRAMEs, 12 skills e sub-agentes prontos — pergunta, decide, executa. Abaixo, snapshot dos sinais que interessam agora: aprovações, campanhas, publicações, budget, follow-up.
        </div>
      </div>

      {/* ═══════════════════ WIDGET DIGI AI · MARKETING ═══════════════════ */}

      <div style={{ padding: '0 32px 24px' }}>
        <div style={{
          border: '1px solid color-mix(in oklch, var(--ai-500) 30%, var(--border))',
          borderRadius: 12,
          background: 'color-mix(in oklch, var(--ai-500) 3%, var(--bg-sunken))',
          overflow: 'hidden',
          display: 'flex', flexDirection: 'column',
        }}>
          {/* Widget header */}
          <div style={{ padding: '12px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 12, background: 'var(--bg-sunken)' }}>
            <div style={{
              width: 32, height: 32, borderRadius: 8,
              background: 'color-mix(in oklch, var(--ai-500) 20%, transparent)',
              display: 'grid', placeItems: 'center', color: 'var(--ai-500)', fontSize: 16, fontWeight: 700,
            }}>D</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text)' }}>Digi AI · Marketing</div>
              <div style={{ fontSize: 10.5, color: 'var(--text-muted)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>
                SP_MARKETING · 8 FRAMEs · 12 skills · 5 marca + 6 função · memória 5 camadas
              </div>
            </div>
            <select style={{ fontSize: 11, padding: '5px 10px', borderRadius: 6, background: 'var(--bg)', border: '1px solid var(--border)', color: 'var(--text)', fontFamily: 'var(--font-mono)' }}>
              <option>Marca: todas</option>
              <option>Mimaki</option>
              <option>BIOND</option>
              <option>Decal</option>
              <option>Sensek</option>
              <option>AllDecor</option>
              <option>NetScreen</option>
            </select>
          </div>

          {/* Thread */}
          <div className="scrollbar" style={{ padding: 16, display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 320, overflowY: 'auto' }}>
            {_DIGI_MSGS_MOCK.map((m, i) => {
              const isUser = m.role === 'user';
              return (
                <div key={i} style={{ display: 'flex', flexDirection: 'column', alignItems: isUser ? 'flex-end' : 'flex-start', gap: 3 }}>
                  <div style={{ display: 'flex', gap: 6, alignItems: 'center', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
                    <span>{m.ts}</span>
                    <span>·</span>
                    <span>{isUser ? 'Tu' : 'Digi'}</span>
                    {m.proactive && (
                      <span style={{
                        padding: '1px 5px', fontSize: 8.5, borderRadius: 3, fontWeight: 700, letterSpacing: '0.06em',
                        background: 'color-mix(in oklch, var(--warning) 14%, transparent)', color: 'var(--warning)',
                      }}>PROACTIVO</span>
                    )}
                  </div>
                  <div style={{
                    maxWidth: '78%',
                    padding: '10px 14px', borderRadius: 10,
                    background: isUser ? 'var(--ai-500)' : 'var(--bg)',
                    color: isUser ? '#fff' : 'var(--text)',
                    border: isUser ? 'none' : '1px solid var(--border)',
                    fontSize: 13, lineHeight: 1.55,
                  }}>
                    {m.text}
                  </div>
                  {m.proactive && !isUser && (
                    <div style={{ display: 'flex', gap: 5, marginTop: 3 }}>
                      <button className="btn btn-xs btn-ai">Ver segmento</button>
                      <button className="btn btn-xs">Adiar</button>
                      <button className="btn btn-xs">Ignorar</button>
                    </div>
                  )}
                </div>
              );
            })}
          </div>

          {/* Quick action chips */}
          <div style={{ padding: '8px 16px', borderTop: '1px solid var(--border)', display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {[
              'O que preciso rever agora?',
              'Estado das campanhas',
              'Análise budget Q3',
              'Sugerir plano trimestre',
              'Rever performance Mimaki',
              'Contactos em silêncio',
            ].map((c, i) => (
              <button key={i}
                onClick={() => setChatInput(c)}
                style={{
                  padding: '4px 10px', borderRadius: 999, fontSize: 10.5,
                  background: 'var(--bg)', border: '1px solid var(--border)',
                  color: 'var(--text-muted)', cursor: 'pointer',
                }}
              >{c}</button>
            ))}
          </div>

          {/* Input */}
          <div style={{ padding: '10px 16px 14px', display: 'flex', gap: 8, borderTop: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
            <input
              value={chatInput}
              onChange={e => setChatInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSend()}
              placeholder="Pergunta, pedido ou instrução..."
              style={{
                flex: 1, padding: '9px 12px', borderRadius: 8,
                background: 'var(--bg)', border: '1px solid var(--border)',
                color: 'var(--text)', fontSize: 13,
              }}
            />
            <button
              className="btn btn-ai"
              onClick={handleSend}
              disabled={chatBusy || !chatInput.trim()}
              style={{ padding: '8px 16px' }}
            >{chatBusy ? '…' : 'Enviar'}</button>
          </div>

          {/* Footer notice */}
          <div style={{ padding: '6px 16px 8px', fontSize: 10, color: 'var(--text-dim)', textAlign: 'center', fontStyle: 'italic', borderTop: '1px solid var(--border)', background: 'var(--bg-sunken)' }}>
            Mock UI · endpoint /api/marketing/digi-ai/chat por criar · thread persistente e memória a implementar
          </div>
        </div>
      </div>

      {/* ═══════════════════ KPI CARDS · SINAIS RÁPIDOS ═══════════════════ */}

      <div style={{ padding: '0 32px 24px' }}>
        <div style={{ ...sectionLabel, marginBottom: 8 }}>SINAIS RÁPIDOS</div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(180px, 1fr))', gap: 10 }}>
          {_KPIS_MOCK.map((k, i) => (
            <div key={i} style={{
              padding: '12px 14px', borderRadius: 10,
              background: 'var(--bg-sunken)', border: '1px solid var(--border)',
              borderLeft: `3px solid ${statusColor(k.status)}`,
              display: 'flex', flexDirection: 'column', gap: 3,
            }}>
              <div style={{ fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>{k.label}</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: 'var(--text)', fontFamily: 'var(--font-display)', lineHeight: 1.1 }}>{k.value}</div>
              <div style={{ fontSize: 10.5, color: 'var(--text-muted)', lineHeight: 1.4 }}>{k.sub}</div>
            </div>
          ))}
        </div>
        <div style={{ fontSize: 10, color: 'var(--text-dim)', marginTop: 6, fontStyle: 'italic' }}>
          Valores mock · endpoint /api/marketing/inicio/summary a criar
        </div>
      </div>

      {/* ═══════════════════ DASHBOARD BLOCOS + EM-DEV ═══════════════════ */}

      <div style={{ padding: '0 32px 40px', display: 'grid', gridTemplateColumns: '1fr 380px', gap: 24, alignItems: 'start' }}>

        {/* ── Coluna esquerda ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

          {/* 1. O que preciso rever */}
          <div>
            <div style={sectionLabel}>DASHBOARD · O QUE ESTÁ A ACONTECER</div>
            <div style={{ ...subLabel }}><span style={dot('#3859D0')} />O Que Preciso Rever Agora</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Aprovações à minha espera', d: 'Briefings + campanhas + estratégia + plano — filtrado por role (FC/RL/Armando/Bruno) com deep-link para cada item.' },
                { t: 'Bloqueadores', d: 'Peças com erro em Produção · publicações falhadas · campanhas sem briefing associado. Requer acção manual.' },
                { t: 'Decisões pendentes', d: 'Alertas AI onde a Digi pediu confirmação (pausar campanha, reactivar contactos, escalar orçamento).' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 2. Estado campanhas */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#0ea5e9')} />Estado das Campanhas</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Contagem por marca × fase', d: 'Grelha compacta Mimaki/BIOND/Decal/Sensek/AllDecor/NetScreen × Conceito/Copy/Prompts/Idiomas/Produção/Activação.' },
                { t: 'Movimentos últimas 48h', d: 'Campanhas que mudaram de fase · aprovações · rejeições · promoções para produção.' },
                { t: 'Deep-link Campanhas', d: 'Cada célula clicável abre o Kanban filtrado por marca × fase.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 3. Publicações 24h */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#059669')} />Fila de Publicação 24h</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Próximas peças a sair', d: 'Meta · LinkedIn · Email · WhatsApp · Web — com hora agendada, marca, campanha. Ordenadas por proximidade.' },
                { t: 'Aprovadas sem janela', d: 'Peças aprovadas mas ainda sem agendamento — pending manual em Activação.' },
                { t: 'Publicações no ar últimas 48h', d: 'Cronologia recente com métricas iniciais (impressões, engagement primeira hora).' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 4. BP × Real */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#8b5cf6')} />BP × Real por Marca</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Semáforo Mimaki · BIOND · Decal · Sensek', d: 'Cumprimento YTD por marca com projecção de fim de trimestre. Verde/amarelo/vermelho por marca × mercado.' },
                { t: 'Gap crítico', d: 'Marca em maior risco de falhar BP — magnitude do gap e sugestão AI de acção correctiva.' },
                { t: 'Deep-link Objectivos', d: 'Abre módulo Objectivos filtrado pela marca clicada.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 5. Budget snapshot */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#f59e0b')} />Budget Snapshot</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Top 3 categorias de custo', d: 'Ads · SaaS · AI — com breakdown mensal e comparação vs trimestre anterior.' },
                { t: 'Burn rate global Q', d: 'Consumido vs planeado com projecção fim trimestre. Semáforo 🟢 <70% · 🟡 70-90% · 🔴 >90%.' },
                { t: 'Custo AI acumulado', d: 'Claude API + Magnific + FLUX últimos 7 dias, com FRAME mais caro em destaque.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 6. Follow-up */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#ef4444')} />Follow-up Scheduler 24h</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Contactos T-3 · T-7 · T-14 · T-21', d: 'Fila prevista para as próximas 24h com nome, marca, template. Filtro por janela horária (9h-18h Lisbon).' },
                { t: 'Adiar / cancelar bulk', d: 'Selecção múltipla para adiar 24h ou cancelar antes do disparo. Registo em histórico.' },
                { t: 'Estatística cadência', d: 'Taxa de resposta por toque (T-3 vs T-7 vs T-14 vs T-21) — feedback para optimizar cadência.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 7. Sinais AI cross-módulo */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#ec4899')} />Sinais AI Cross-módulo</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Correlações detectadas', d: 'Digi identifica padrões (ex: "Instagram Mimaki gera +30% CTR aos fins-de-semana"). Sugestão de acção com CTA no chat.' },
                { t: 'Over-exposure', d: 'Contactos que receberam >N toques em janela X. Excluíveis automaticamente de novas campanhas.' },
                { t: 'Regressão qualidade', d: 'Descida de score Digi AI em respostas WA — alerta se pós-release de SP/FRAME.' },
                { t: 'Alertas gerados pela Digi', d: 'Todos os alertas que a Digi gerou nas últimas 24h — expandível com evidência e recomendação.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 8. Actividade recente */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#06b6d4')} />Actividade Recente 48h</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Últimos briefings criados', d: 'Autor, marca, produto, estado. Deep-link para o detalhe.' },
                { t: 'Movimentos Kanban', d: 'Campanhas que mudaram de fase, com autor e nota.' },
                { t: 'Publicações no ar', d: 'Cronologia de publicações efectivas Meta/LinkedIn/Email/WA.' },
                { t: 'Aprovações fechadas', d: 'Briefings/campanhas/estratégia aprovados nas últimas 48h com aprovador.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 9. Origem de Dados (em-des standard) */}
          <div>
            <div style={sectionLabel}>ESTRUTURA DO MÓDULO</div>
            <div style={{ ...subLabel }}><span style={dot('#3859D0')} />Origem de Dados</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Todos os módulos Marketing', d: 'Briefings · Campanhas · Estratégia · Plano · Produção · CRM · Activação · Monitorização · Performance Ads · Resultados · Budget · Sub-agentes · Open Houses — Início agrega sinais de cada um.' },
                { t: 'SP_MARKETING + FRAMEs + Skills', d: 'Digi AI carregada com system prompt oficial, 8 FRAMEs (BRIEFING/CONCEITO/KPI/ADS/EDITORIAL/CONTENT/EMAIL/SOCIAL) e 12 skills marketing.' },
                { t: 'Sub-agentes marca (VPS) + função', d: 'Digi decide autonomamente qual sub-agente invocar por marca (Mimaki/BIOND/Decal/Sensek/AllDecor) ou função (ADS/CONTENT/EMAIL/SEO/SOCIAL/ANALYTICS).' },
                { t: 'Memória 5 camadas', d: 'Perfil utilizador · trabalho actual · histórico decisões · estado global negócio · histórico da conversa. Espelha modelo SP_CLIENTES.' },
                { t: 'Trigger scheduler', d: 'Cron verifica eventos periodicamente e cria mensagens proactivas no thread do utilizador.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 10. Modelo conversação */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#a855f7')} />Modelo de Conversação · Thread Único com Memória</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {[
                { t: 'Uma janela · uma conversa contínua', d: 'Não há mensagens fragmentadas. Tudo acontece no mesmo thread — reactivo (utilizador escreve) e proactivo (Digi inicia) misturam no fluxo natural.' },
                { t: 'Persistência entre sessões', d: 'Últimas N mensagens carregam ao entrar. Nunca perdes o contexto do que foi discutido, decidido ou pedido antes.' },
                { t: 'Recall na resposta', d: 'Digi consulta memória antes de responder — refere decisões anteriores ("ontem decidiste X", "há 2h combinámos Y").' },
                { t: 'Iniciativa dentro do thread', d: 'Quando um evento merece acção (burn rate, aprovação atrasada, silêncio), Digi acrescenta nova mensagem — não notificação separada. CTAs directos na mensagem.' },
              ].map((f, i) => (
                <div key={i} style={cardStyle}>
                  <div style={titleStyle}>{f.t}</div>
                  <div style={descStyle}>{f.d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 11. Permissões */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#94a3b8')} />Permissões por Role</div>
            <div style={{ border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr' }}>
                <div style={tableHeader}>Perfil</div>
                <div style={tableHeader}>O que Digi mostra / faz</div>
              </div>
              {[
                ['Board',            'Agregados ROI · overview módulos · read-only'],
                ['Admin (FC · JP)',  'Controlo total · aprovações · configuração'],
                ['AI Strategist (RL)','Estratégia · aprovação briefings/campanhas (RL)'],
                ['Marketing Manager','Operações diárias · CRUD · execução'],
                ['Comercial (read)', 'Só campanhas do pipeline · sinais Marketing'],
                ['Cliente NetScreen','Isolamento total · só briefings + acompanhamento NetScreen'],
              ].map(([p, v], i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '180px 1fr' }}>
                  <div style={{ ...tableCell, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ai-500)' }}>{p}</div>
                  <div style={tableCellMuted}>{v}</div>
                </div>
              ))}
            </div>
          </div>

          {/* 12. Ligações ao sistema */}
          <div>
            <div style={{ ...subLabel }}><span style={dot('#ec4899')} />Ligações ao Sistema Existente</div>
            <div style={{ ...cardStyle, fontFamily: 'var(--font-mono)', fontSize: 12, lineHeight: 2, color: 'var(--text)' }}>
              <div>Todos os módulos Marketing → <span style={{ color: 'var(--ai-500)' }}>Início (agregação)</span></div>
              <div style={{ paddingLeft: 16 }}>↓</div>
              <div>Sinais rápidos (KPI cards) + Dashboard blocks</div>
              <div style={{ paddingLeft: 16, color: 'var(--text-muted)' }}>├── briefings · conteudo_campanhas → aprovações</div>
              <div style={{ paddingLeft: 16, color: 'var(--text-muted)' }}>├── activacao/calendario → publicações 24h</div>
              <div style={{ paddingLeft: 16, color: 'var(--text-muted)' }}>├── budget_expenses · agent_runs → burn rate</div>
              <div style={{ paddingLeft: 16, color: 'var(--text-muted)' }}>├── sdr_followup_queue → fila 24h</div>
              <div style={{ paddingLeft: 16, color: 'var(--text-muted)' }}>├── objectivos_bp × pipeline Gestor → BP semáforo</div>
              <div style={{ paddingLeft: 16, color: 'var(--text-muted)' }}>└── digi_ai_triggers → proactivos</div>
              <div style={{ paddingLeft: 16 }}>↓</div>
              <div>Digi AI Marketing (thread único com memória) → <span style={{ color: 'var(--ai-500)' }}>utilizador</span></div>
            </div>
          </div>

          {/* 13. Nota técnica */}
          <div style={{
            padding: '14px 16px', borderRadius: 8,
            background: 'color-mix(in oklch, var(--warning) 6%, transparent)',
            border: '1px solid color-mix(in oklch, var(--warning) 25%, transparent)',
          }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--warning)', fontFamily: 'var(--font-mono)', marginBottom: 6, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Consideração técnica</div>
            <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.65 }}>
              <strong style={{ color: 'var(--text)' }}>Local — a implementar:</strong>
              <br />
              1. Tabelas <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi_ai_messages</span> · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi_ai_memory_snapshots</span> · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi_ai_triggers</span> · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi_ai_actions</span> · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>inicio_summary_cache</span>.
              <br />
              2. Ficheiros <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>portal/prompts/SP_MARKETING.md</span> + 8 FRAMEs em Markdown.
              <br />
              3. Endpoints em <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>marketing-dev-server.js</span>: <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>POST /digi-ai/chat</span> (SSE, carrega SP + FRAMEs + memória, chama Sonnet 4.6) · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>GET /digi-ai/messages</span> · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>POST /digi-ai/action</span> · <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>GET /inicio/summary</span> (agrega KPIs).
              <br />
              4. Job scheduler local (cada 5 min) verifica eventos → cria mensagens proactivas em <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi_ai_messages</span>.
              <br />
              5. Agregador de memória — actualiza <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi_ai_memory_snapshots</span> sempre que algo muda em briefings/campanhas/budget.
              <br /><br />
              <strong style={{ color: 'var(--text)' }}>Handoff JP no deploy:</strong>
              <br />
              6. Sino/bell + toast global no <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>shell.jsx</span> — para notificações chegarem em qualquer ecrã do portal.
              <br />
              7. Trigger scheduler produção (cron VPS).
              <br />
              8. Auth check produção — <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>/me</span> role verification em todos os endpoints <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>digi-ai/*</span>.
              <br />
              9. Rate limiting + índices BD produção.
              <br />
              10. Se SP_MARKETING for para viver na VPS também — sync com <span style={{ fontFamily: 'var(--font-mono)', color: 'var(--text)' }}>heydigi-local/prompts</span>.
            </div>
          </div>
        </div>

        {/* ── Coluna direita (sticky) ── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 24, position: 'sticky', top: 0 }}>

          {/* Skills e Tools */}
          <div>
            <div style={sectionLabel}>SKILLS E TOOLS</div>
            <div style={{ border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr' }}>
                <div style={tableHeader}>Skill / Tool</div>
                <div style={tableHeader}>O que faz</div>
              </div>
              {[
                ['state-reader',           'Lê estado agregado dos módulos'],
                ['dashboard-aggregator',   'Consolida KPI cards + blocos'],
                ['memory-manager',         'Gere 5 camadas memória Digi'],
                ['context-aggregator',     'Puxa contexto pré-resposta'],
                ['proactive-composer',     'Gera mensagens de iniciativa'],
                ['sp-marketing-router',    'Escolhe sub-agente a invocar'],
                ['role-filter',            'Filtra por permissão do user'],
                ['deep-link-builder',      'Links contextuais para ecrãs'],
                ['notification-scheduler', 'Cron eventos → mensagens'],
                ['SP_MARKETING',           'System prompt oficial (arch doc)'],
                ['FRAMEs × 8',             'BRIEFING · CONCEITO · KPI · ADS · EDITORIAL · CONTENT · EMAIL · SOCIAL'],
                ['Skills × 12',            '11 [criar] + muppi-content ✅'],
              ].map(([s, d], i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1.4fr' }}>
                  <div style={{ ...tableCell, fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--ai-500)' }}>{s}</div>
                  <div style={tableCellMuted}>{d}</div>
                </div>
              ))}
            </div>
          </div>

          {/* O que ganhamos */}
          <div>
            <div style={sectionLabel}>O QUE GANHAMOS</div>
            <div style={{ border: '1px solid var(--border)', borderRadius: 10, overflow: 'hidden' }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
                <div style={{ ...tableHeader, color: 'var(--danger)' }}>Antes</div>
                <div style={{ ...tableHeader, color: 'var(--success)' }}>Depois</div>
              </div>
              {[
                ['Abrir 14 módulos para saber o que se passa',   '1 ecrã com sinais + Digi'],
                ['Chat sem contexto do módulo',                   'Digi com SP_MARKETING carregado'],
                ['Sem memória entre respostas',                   '5 camadas de memória persistente'],
                ['Notificações fragmentadas em vários locais',    'Thread único · iniciativa dentro dele'],
                ['Aprovações espalhadas por módulos',              'Fila centralizada por role'],
                ['Digi genérica sem permissões',                   'Respostas filtradas por role'],
                ['Sub-agentes escolhidos manualmente',             'Digi decide autonomamente'],
                ['Alertas ad-hoc por email',                       'Proactivos dentro do thread'],
              ].map(([a, b], i) => (
                <div key={i} style={{ display: 'grid', gridTemplateColumns: '1fr 1fr' }}>
                  <div style={{ ...tableCellMuted, fontSize: 11 }}>{a}</div>
                  <div style={{ ...tableCell, fontSize: 11 }}>{b}</div>
                </div>
              ))}
            </div>
          </div>

          {/* BD */}
          <div>
            <div style={sectionLabel}>BD</div>
            <div style={{ ...cardStyle, fontFamily: 'var(--font-mono)', fontSize: 11, lineHeight: 1.8, color: 'var(--text-muted)' }}>
              <div><span style={{ color: 'var(--success)' }}>briefings · conteudo_campanhas</span> ✅</div>
              <div><span style={{ color: 'var(--success)' }}>agent_runs · budget_expenses</span> ✅</div>
              <div><span style={{ color: 'var(--success)' }}>FMRS_API_* (Gestor)</span> ✅</div>
              <div><span style={{ color: 'var(--success)' }}>contact_memory · heydigi_sessions</span> ✅</div>
              <div style={{ marginTop: 6, color: 'var(--warning)' }}>Por criar (local):</div>
              <div><span style={{ color: 'var(--ai-500)' }}>digi_ai_messages</span> — thread persistente</div>
              <div><span style={{ color: 'var(--ai-500)' }}>digi_ai_memory_snapshots</span> — 5 camadas</div>
              <div><span style={{ color: 'var(--ai-500)' }}>digi_ai_triggers</span> — regras proactivas</div>
              <div><span style={{ color: 'var(--ai-500)' }}>digi_ai_actions</span> — quick actions</div>
              <div><span style={{ color: 'var(--ai-500)' }}>inicio_summary_cache</span> — KPI rollup</div>
              <div style={{ marginTop: 6, color: 'var(--warning)' }}>Por criar (deploy JP):</div>
              <div><span style={{ color: 'var(--ai-500)' }}>notificacoes_globais</span> — sino portal</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

window.MktInicioScreen = MktInicioScreen;
