/* COBRANÇAS · Vista 1 — RESUMO
   Dashboard agregado · 3 KPIs hero + aging + estados + Coface + calendário + sidebar Digi */

const FinResumoView = ({ ctx, onGoTo }) => {
  const H = window.FinHelpers;
  const K = window.FIN_HEAD_KPIS;
  const dso = window.FIN_DSO_TREND;
  const alerts = window.FIN_LIVE_ALERTS;
  const ESTADOS = window.FIN_ESTADOS;

  const empresaFiltrada = ctx.empresa === 'todas' ? null : window.FIN_EMPRESAS.find(e => e.id === ctx.empresa);

  // KPIs
  const kpiCards = (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 12 }}>
      <KpiHero
        label="Exposição total"
        value={H.fmtEUR(K.exposicaoTotal)}
        delta={K.exposicaoDelta}
        deltaColor="var(--text-muted)"
        accent="#1E40AF"
        sub={empresaFiltrada ? `só ${empresaFiltrada.short}` : 'agregado SGPS · 6 empresas'}
      />
      <KpiHero
        label="Vencidos > 30d"
        value={H.fmtEUR(K.vencidos30d)}
        delta={`${K.vencidos30dClientes} clientes · ${K.vencidos30dDelta}`}
        deltaColor="#F59E0B"
        accent="#F97316"
        action={<button className="btn btn-xs" onClick={() => onGoTo('clientes', { idade: '60' })}>Ver lista →</button>}
      />
      <KpiHero
        label="Encomendas a validar"
        value={`${K.queueCount} · ${H.fmtEUR(K.queueValor)}`}
        delta={`SLA: ${K.queueSLAExpired} fora de prazo`}
        deltaColor="var(--danger)"
        accent="var(--ai-500)"
        action={<button className="btn btn-xs btn-ai" onClick={() => onGoTo('queue')}>Ir para queue →</button>}
        urgent
      />
    </div>
  );

  // Aging — barras horizontais
  const agingTotal = K.estadosAgregados.PEN + K.estadosAgregados.PDT + K.estadosAgregados.FAC;
  const agingBars = [
    { label: '0-30 dias',  v: 1420880, n: 142, color: 'var(--success)' },
    { label: '31-60 dias', v: 912040,  n: 78,  color: '#F59E0B' },
    { label: '61-90 dias', v: 286910,  n: 17,  color: '#F97316' },
    { label: '> 90 dias',  v: 198020,  n: 11,  color: 'var(--danger)' },
  ];
  const agingMax = Math.max(...agingBars.map(b => b.v));

  return (
    <div className="scrollbar" style={{ height: '100%', overflowY: 'auto' }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr) 320px', gap: 16, padding: '4px 4px 80px', alignItems: 'flex-start' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16, minWidth: 0 }}>

          {/* Briefing matinal */}
          <BriefingMatinal onGoTo={onGoTo} />

          {kpiCards}

          {/* Aging */}
          <div className="card" style={{ padding: 16 }}>
            <CardHeader title="Aging · saldos em curso" sub="0-30 verdes · 31-60 amarelos · 61-90 laranja · >90 vermelhos. Distribuição agregada SGPS." />
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 4 }}>
              {agingBars.map(b => (
                <div key={b.label} style={{ display: 'grid', gridTemplateColumns: '120px 1fr 130px 60px', alignItems: 'center', gap: 10, fontSize: 12 }}>
                  <span style={{ color: 'var(--text-muted)' }}>{b.label}</span>
                  <div style={{ height: 14, background: 'var(--bg-sunken)', borderRadius: 3, overflow: 'hidden', position: 'relative' }}>
                    <div style={{ height: '100%', width: `${(b.v / agingMax) * 100}%`, background: b.color, borderRadius: 3 }} />
                  </div>
                  <span className="font-mono" style={{ textAlign: 'right', fontWeight: 600 }}>{H.fmtEUR(b.v)}</span>
                  <span style={{ fontSize: 11, color: 'var(--text-dim)', textAlign: 'right' }}>{b.n} docs</span>
                </div>
              ))}
            </div>
            <div style={{ marginTop: 12, paddingTop: 10, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: 'var(--text-muted)' }}>
              <span>Threshold default <strong style={{ color: 'var(--text)' }}>60 dias</strong> <H.ValidarPatricia>Threshold default 60 dias — configurável por segmento A/B/C ou cliente individual. Confirmar com a Patrícia se 60d é o número certo, ou se vocês já trabalham com 45d.</H.ValidarPatricia></span>
              <button className="btn btn-xs">Configurar thresholds</button>
            </div>
          </div>

          {/* Estados conta corrente */}
          <div className="card" style={{ padding: 16 }}>
            <CardHeader title="Conta corrente · por estado Primavera" sub="Click para filtrar a vista Clientes nesse estado" />
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 10, marginTop: 4 }}>
              {['PEN', 'PDT', 'FAC', 'FAT', 'REC', 'RET'].map(e => {
                const conf = ESTADOS[e];
                const v = K.estadosAgregados[e];
                return (
                  <button key={e} onClick={() => onGoTo('clientes', { estado: e })} style={{
                    display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8,
                    padding: '10px 12px', borderRadius: 6, textAlign: 'left',
                    background: 'var(--bg-sunken)', border: '1px solid var(--border)',
                    cursor: 'pointer',
                  }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <span style={{ width: 4, height: 28, borderRadius: 2, background: conf.color }} />
                      <div>
                        <div className="font-mono" style={{ fontSize: 11, color: conf.color, fontWeight: 700, letterSpacing: '0.06em' }}>{e}</div>
                        <div style={{ fontSize: 10, color: 'var(--text-dim)' }}>{conf.label}</div>
                      </div>
                    </div>
                    <span className="font-mono" style={{ fontWeight: 600, fontSize: 13 }}>{H.fmtEURcompact(v)}</span>
                  </button>
                );
              })}
            </div>
            <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>
                Total exposição limite · <strong style={{ color: 'var(--text)' }}>{H.fmtEUR(K.exposicaoTotal)}</strong>
              </span>
            </div>

            {/* RAP + FAL — exposição especial */}
            <div style={{ marginTop: 12, padding: 10, borderRadius: 6, border: '1px dashed color-mix(in oklch, #A855F7 30%, transparent)', background: 'color-mix(in oklch, #A855F7 4%, transparent)' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
                <span className="font-mono" style={{ fontSize: 9.5, fontWeight: 600, letterSpacing: '0.06em', color: '#A855F7' }}>EXPOSIÇÃO ESPECIAL · NÃO SOMA AO LIMITE</span>
                <H.ValidarPatricia>RAP (rappel) e FAL (acordo de pagamento) ficam fora do limite de crédito, segundo a leitura inicial. Confirma com a Patrícia se a contabilidade SGPS as exclui mesmo do limite, ou se algumas contam.</H.ValidarPatricia>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 4 }}>
                  <span className="font-mono" style={{ color: '#A855F7', fontWeight: 700, fontSize: 11 }}>RAP <span style={{ color: 'var(--text-dim)', fontWeight: 400, marginLeft: 4 }}>· Rappel</span></span>
                  <span className="font-mono" style={{ fontWeight: 600 }}>{H.fmtEUR(K.estadosAgregados.RAP)}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '8px 10px', background: 'var(--bg-elev)', borderRadius: 4 }}>
                  <span className="font-mono" style={{ color: '#F97316', fontWeight: 700, fontSize: 11 }}>FAL <span style={{ color: 'var(--text-dim)', fontWeight: 400, marginLeft: 4 }}>· Falência/Acordo</span></span>
                  <span className="font-mono" style={{ fontWeight: 600 }}>{H.fmtEUR(K.estadosAgregados.FAL)}</span>
                </div>
              </div>
            </div>
          </div>

          {/* Coface + Modo pagamento — duas colunas */}
          <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16 }}>
            <CofaceCard onGoTo={onGoTo} />
            <ModoPagamentoCard />
          </div>

          {/* Calendário cobrança */}
          <CalendarioCobranca onGoTo={onGoTo} />

          {/* DSO trend */}
          <div className="card" style={{ padding: 16 }}>
            <CardHeader title="DSO · últimos 30 dias" sub="Days Sales Outstanding · idade média da conta corrente. Estável em 56d nos últimos 4 dias." />
            <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 24, marginTop: 8 }}>
              <div style={{ display: 'flex', alignItems: 'baseline', gap: 12 }}>
                <span className="font-display" style={{ fontSize: 38, fontWeight: 600 }}>{dso[dso.length - 1]}</span>
                <span style={{ color: 'var(--text-dim)', fontSize: 13 }}>dias</span>
                <span style={{ color: 'var(--success)', fontSize: 11, fontFamily: 'var(--font-mono)' }}>↓ -6d vs início mês</span>
              </div>
              <H.Sparkline data={dso} w={420} h={56} color="var(--ai-500)" />
            </div>
          </div>

          {/* Cards inline — como aparece no chat */}
          <CardsInline />
        </div>

        {/* Sidebar direita — Digi observa */}
        <SidebarDigiObserva alerts={alerts} />
      </div>
    </div>
  );
};

// ─── helpers internos ────────────────────────────────────────────────

const CardHeader = ({ title, sub }) => (
  <div style={{ marginBottom: 12 }}>
    <div className="font-display" style={{ fontSize: 14, fontWeight: 600 }}>{title}</div>
    {sub && <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2 }}>{sub}</div>}
  </div>
);

const KpiHero = ({ label, value, delta, deltaColor, accent, sub, action, urgent }) => (
  <div className="card" style={{
    padding: 16, position: 'relative',
    borderTop: `2px solid ${accent}`,
    background: urgent ? 'color-mix(in oklch, var(--ai-500) 4%, var(--bg-elev))' : 'var(--bg-elev)',
  }}>
    <div className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>{label}</div>
    <div className="font-display" style={{ fontSize: 26, fontWeight: 600, marginTop: 4, letterSpacing: '-0.01em' }}>{value}</div>
    {(delta || sub) && (
      <div style={{ marginTop: 6, fontSize: 11, color: deltaColor || 'var(--text-muted)' }}>
        {delta}
        {sub && <span style={{ color: 'var(--text-dim)', marginLeft: 6 }}>· {sub}</span>}
      </div>
    )}
    {action && <div style={{ marginTop: 10 }}>{action}</div>}
  </div>
);

const BriefingMatinal = ({ onGoTo }) => (
  <div className="ai-surface card" style={{ padding: 16, borderLeft: '3px solid var(--ai-500)' }}>
    <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12 }}>
      <span className="ai-chip" style={{ flexShrink: 0 }}><span className="ai-dot" />Digi · briefing 08:00</span>
    </div>
    <div style={{ fontSize: 13.5, lineHeight: 1.6, marginTop: 10 }}>
      <strong>Bom dia, Patrícia.</strong> Hoje no Cobranças: <strong>9 encomendas portal retidas</strong> (2 com SLA expirado · #44892 Olimpo 8.450 € em limite +4%), <strong>15 cobranças na agenda</strong> (5 críticas &gt;30d), <strong>Coface global em 89%</strong> (+2pp vs ontem). Atender encomendas primeiro?
    </div>
    <div style={{ display: 'flex', gap: 6, marginTop: 12 }}>
      <button className="btn btn-xs btn-ai" onClick={() => onGoTo('queue')}>Abrir queue retidas</button>
      <button className="btn btn-xs" onClick={() => onGoTo('proactiva')}>Ir à agenda</button>
      <button className="btn btn-xs">Ver Coface</button>
    </div>
  </div>
);

const CofaceCard = ({ onGoTo }) => {
  const H = window.FinHelpers;
  const K = window.FIN_HEAD_KPIS;
  const tecto = window.FIN_COFACE_TECTO;
  return (
    <div className="card" style={{ padding: 16 }}>
      <CardHeader title="Coface · saúde do crédito" sub={`Limite agregado ${H.fmtEUR(K.cofaceTotal)} · usado ${H.fmtEUR(K.cofaceUsado)} (${K.cofacePct}%) · alerta a 85%`} />
      {/* barra */}
      <div style={{ height: 10, background: 'var(--bg-sunken)', borderRadius: 5, overflow: 'hidden', position: 'relative', marginBottom: 4 }}>
        <div style={{ position: 'absolute', left: '85%', top: 0, bottom: 0, width: 1, background: '#F59E0B', zIndex: 2 }} />
        <div style={{ height: '100%', width: `${K.cofacePct}%`, background: K.cofacePct >= 85 ? '#F97316' : 'var(--success)' }} />
      </div>
      <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 10, color: 'var(--text-dim)', fontFamily: 'var(--font-mono)' }}>
        <span>0</span><span style={{ marginLeft: 'auto' }}>85% alerta</span><span style={{ marginLeft: 12 }}>{H.fmtEURcompact(K.cofaceTotal)}</span>
      </div>

      <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--border)' }}>
        <div className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)', letterSpacing: '0.08em', marginBottom: 8 }}>TOP 5 PRÓXIMOS DO TECTO</div>
        {tecto.map((t, i) => {
          const c = window.FIN_CLIENTES.find(x => x.id === t.clienteId);
          return (
            <button key={i} onClick={() => onGoTo('clientes', { focus: t.clienteId })} style={{
              width: '100%', textAlign: 'left',
              display: 'grid', gridTemplateColumns: '1fr auto 60px', alignItems: 'center', gap: 10,
              padding: '7px 0', borderBottom: i < 4 ? '1px solid var(--border)' : 'none',
            }}>
              <div style={{ fontSize: 12, fontWeight: 500, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{c?.nome}</div>
              <span className="font-mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{H.fmtEURcompact(t.usado)} / {H.fmtEURcompact(t.lim)}</span>
              <span className="font-mono" style={{
                fontSize: 11, fontWeight: 700, textAlign: 'right',
                color: t.pct >= 90 ? 'var(--danger)' : '#F97316',
              }}>{t.pct}%</span>
            </button>
          );
        })}
      </div>
    </div>
  );
};

const ModoPagamentoCard = () => {
  const H = window.FinHelpers;
  const K = window.FIN_HEAD_KPIS;
  const segs = [
    { k: 'euro',   v: K.modosAgregados.euro,   color: '#1E40AF', label: 'Eurofactor' },
    { k: 'trans',  v: K.modosAgregados.trans,  color: '#0F766E', label: 'Transferência' },
    { k: 'cheque', v: K.modosAgregados.cheque, color: '#A855F7', label: 'Cheque' },
    { k: 'ele',    v: K.modosAgregados.ele,    color: '#F59E0B', label: 'Electrónico' },
  ];
  const total = segs.reduce((s, x) => s + x.v, 0);
  return (
    <div className="card" style={{ padding: 16 }}>
      <CardHeader title="Modo pagamento" sub="Distribuição da exposição actual" />
      <div style={{ display: 'flex', alignItems: 'center', gap: 16, marginTop: 8 }}>
        <H.Donut segs={segs} size={94} thick={14} />
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6, fontSize: 11.5 }}>
          {segs.map(s => (
            <div key={s.k} style={{ display: 'grid', gridTemplateColumns: '12px 1fr auto', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 10, height: 10, background: s.color, borderRadius: 2 }} />
              <span style={{ color: 'var(--text-muted)' }}>{s.label}</span>
              <span className="font-mono" style={{ fontWeight: 600 }}>{Math.round((s.v / total) * 100)}%</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
};

const CalendarioCobranca = ({ onGoTo }) => {
  const H = window.FinHelpers;
  // 30 dias · marcadores em 5/15/25/30 e dia 15 deadline cheques
  const days = Array.from({ length: 30 }, (_, i) => i + 1);
  const eventos = {
    5:  { label: 'venc. transf.', valor: 84200,  cor: 'var(--success)', n: 6 },
    11: { label: 'pré-venc. lote', valor: 124000, cor: '#3B82F6',        n: 12 },
    15: { label: 'deadline cheques', valor: 218400, cor: '#F59E0B', n: 18, isCheque: true },
    20: { label: 'venc. Eurofactor', valor: 184300, cor: 'var(--success)', n: 8 },
    25: { label: 'venc. Eurofactor', valor: 142000, cor: 'var(--success)', n: 5 },
    28: { label: 'fim de mês', valor: 88200,  cor: '#3B82F6', n: 4 },
  };
  return (
    <div className="card" style={{ padding: 16 }}>
      <CardHeader title="Calendário · próximos 30 dias" sub="Marcadores em vencimentos. Dia 15 = deadline cheques (cuidado especial). Click num dia abre vista expandida." />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(30, 1fr)', gap: 2, marginTop: 8 }}>
        {days.map(d => {
          const e = eventos[d];
          return (
            <button key={d} title={e ? `${e.label} · ${e.n} faturas · ${H.fmtEUR(e.valor)}` : `dia ${d}`}
              onClick={() => e && onGoTo('proactiva', { day: d })}
              style={{
                position: 'relative', height: 36, borderRadius: 3,
                background: e ? 'color-mix(in oklch, ' + e.cor + ' 14%, transparent)' : 'var(--bg-sunken)',
                border: e ? `1px solid color-mix(in oklch, ${e.cor} 30%, transparent)` : '1px solid var(--border)',
                cursor: e ? 'pointer' : 'default',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                fontSize: 9, color: e ? e.cor : 'var(--text-dim)',
                fontFamily: 'var(--font-mono)',
              }}>
              <span style={{ fontWeight: e ? 700 : 400 }}>{d}</span>
              {e && <span style={{ width: 4, height: 4, borderRadius: '50%', background: e.cor, marginTop: 2 }} />}
            </button>
          );
        })}
      </div>
      <div style={{ marginTop: 10, display: 'flex', gap: 14, fontSize: 10.5, color: 'var(--text-muted)', flexWrap: 'wrap' }}>
        <Legenda cor="var(--success)" label="venc. normais" />
        <Legenda cor="#F59E0B" label="dia 15 · deadline cheques" />
        <Legenda cor="#3B82F6" label="lotes pré-vencimento" />
      </div>
    </div>
  );
};

const Legenda = ({ cor, label }) => (
  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5 }}>
    <span style={{ width: 8, height: 8, borderRadius: 2, background: cor }} />
    {label}
  </span>
);

const CardsInline = () => {
  const H = window.FinHelpers;
  const olimpo = window.FIN_CLIENTES.find(c => c.id === 'olimpo');
  return (
    <div className="card" style={{ padding: 16 }}>
      <CardHeader title="Como aparece no chat com a Digi" sub="Cards inline que a Digi gera no chat (ex: WhatsApp ou painel de chat) quando responde sobre cobranças." />
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12, marginTop: 4 }}>
        {/* Card cliente cobrança */}
        <ChatCard subtle="card-cliente-cobranca">
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: H.scoreColor(olimpo.score) }} />
            <strong style={{ fontSize: 13 }}>Olimpo Lda</strong>
            <span className="font-mono" style={{ fontSize: 9.5, color: 'var(--text-dim)' }}>C01284</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 4 }}>
            <span style={{ color: 'var(--text-muted)' }}>Exposição</span>
            <span className="font-mono" style={{ fontWeight: 600 }}>{H.fmtEUR(245040)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 4 }}>
            <span style={{ color: 'var(--text-muted)' }}>Limite usado</span>
            <span className="font-mono">69% · {H.fmtEUR(350000)}</span>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 11.5, marginBottom: 8 }}>
            <span style={{ color: 'var(--text-muted)' }}>Aging mais antigo</span>
            <span className="font-mono" style={{ color: '#F97316' }}>90 dias</span>
          </div>
          <button className="btn btn-xs" style={{ width: '100%' }}>Abrir cliente →</button>
        </ChatCard>

        {/* Card encomenda retida */}
        <ChatCard subtle="card-encomenda-retida">
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 8 }}>
            <strong style={{ fontSize: 13 }}>Encomenda #44892</strong>
            <span className="font-mono" style={{ fontSize: 10, padding: '1px 5px', borderRadius: 3, background: 'color-mix(in oklch, var(--danger) 14%, transparent)', color: 'var(--danger)' }}>limite +4%</span>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 8 }}>Olimpo Lda · SA · 8.450 €</div>
          <div style={{ fontSize: 11.5, lineHeight: 1.5, color: 'var(--text-muted)', marginBottom: 8 }}>
            Limite Coface ainda livre (195K€). Recomendo libertar com nota.
          </div>
          <div style={{ display: 'flex', gap: 4 }}>
            <button className="btn btn-xs btn-ai" style={{ flex: 1 }}>Ir validar →</button>
            <button className="btn btn-xs" style={{ flex: 1 }}>Falar c/ Digi</button>
          </div>
        </ChatCard>

        {/* Card cobrança proactiva */}
        <ChatCard subtle="card-cobranca-proactiva">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ fontSize: 18 }}>📋</span>
            <strong style={{ fontSize: 13 }}>15 cobranças hoje</strong>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', lineHeight: 1.5, marginBottom: 8 }}>
            5 críticas (&gt;30d) · 7 lembretes pré-venc · 3 follow-ups
          </div>
          <button className="btn btn-xs btn-ai" style={{ width: '100%' }}>Abrir agenda →</button>
        </ChatCard>

        {/* Card alerta Coface */}
        <ChatCard subtle="card-alerta-coface">
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <span style={{ width: 10, height: 10, borderRadius: '50%', background: 'var(--danger)' }} />
            <strong style={{ fontSize: 13 }}>Meta Print SA</strong>
          </div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 4 }}>Limite Coface a <strong style={{ color: 'var(--danger)' }}>95%</strong> (€398K / €420K)</div>
          <div style={{ fontSize: 11.5, color: 'var(--text-muted)', marginBottom: 8 }}>+5pp em 7 dias · há 1h</div>
          <button className="btn btn-xs">Ver detalhe →</button>
        </ChatCard>
      </div>
    </div>
  );
};

const ChatCard = ({ children, subtle }) => (
  <div data-cardtype={subtle} style={{
    padding: 12, borderRadius: 6,
    background: 'var(--bg-sunken)',
    border: '1px solid var(--border)',
  }}>{children}</div>
);

const SidebarDigiObserva = ({ alerts }) => {
  const colors = {
    critical: { bg: 'color-mix(in oklch, var(--danger) 8%, transparent)', fg: 'var(--danger)', icon: '🚨' },
    warn:     { bg: 'color-mix(in oklch, #F59E0B 8%, transparent)',        fg: '#F59E0B',        icon: '🟡' },
    ok:       { bg: 'color-mix(in oklch, var(--success) 8%, transparent)', fg: 'var(--success)', icon: '🟢' },
  };
  return (
    <div style={{ position: 'sticky', top: 0, display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div className="ai-surface card" style={{ padding: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
          <span className="ai-chip"><span className="ai-dot" />Digi · live</span>
        </div>
        <div className="font-display" style={{ fontSize: 13, fontWeight: 600 }}>O que está a observar</div>
        <div style={{ fontSize: 11, color: 'var(--text-muted)', marginTop: 2, marginBottom: 10 }}>Eventos do Primavera + Coface · últimas 5h</div>

        {alerts.map((a, i) => {
          const c = colors[a.tipo];
          return (
            <div key={i} style={{
              padding: '10px 12px', marginBottom: 8, borderRadius: 5,
              background: c.bg, border: '1px solid color-mix(in oklch, ' + c.fg + ' 16%, transparent)',
            }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 4 }}>
                <span style={{ fontSize: 12 }}>{c.icon}</span>
                <span className="font-mono" style={{ fontSize: 10, color: 'var(--text-dim)' }}>{a.ts}</span>
              </div>
              <div style={{ fontSize: 12, lineHeight: 1.45 }}>{a.msg}</div>
            </div>
          );
        })}

        <button className="btn btn-xs" style={{ width: '100%', marginTop: 4 }}>Ver todos os eventos →</button>
      </div>
    </div>
  );
};

window.FinResumoView = FinResumoView;
