/* screen_sistema_agentes.jsx — Dashboard de estado dos agentes AI */

const _dot   = (c) => ({ width: 7, height: 7, borderRadius: '50%', background: c, flexShrink: 0 });
const _badge = (s) => ({ display: 'flex', alignItems: 'center', gap: 4, fontSize: 10, fontWeight: 600, padding: '2px 8px', borderRadius: 20, flexShrink: 0, ...(s === 'embedded' ? { background: 'rgba(99,102,241,0.12)', color: '#6366f1', border: '1px solid rgba(99,102,241,0.3)' } : s ? { background: 'rgba(22,163,74,0.1)', color: '#16a34a', border: '1px solid rgba(22,163,74,0.3)' } : { background: 'rgba(220,38,38,0.1)', color: '#dc2626', border: '1px solid rgba(220,38,38,0.3)' }) });

const Dot = ({ c }) => <div style={_dot(c)} />;
const Badge = ({ alive }) => (
  <div style={_badge(alive)}>
    <Dot c={alive === 'embedded' ? '#6366f1' : alive ? '#16a34a' : '#dc2626'} />
    {alive === 'embedded' ? 'Integrado' : alive ? 'Online' : 'Offline'}
  </div>
);

const SistemaAgentes = () => {
  const [data,        setData]        = React.useState(null);
  const [loading,     setLoading]     = React.useState(true);
  const [lastUpdated, setLastUpdated] = React.useState(null);
  const [refreshing,  setRefreshing]  = React.useState(false);

  const load = async (manual = false) => {
    if (manual) setRefreshing(true);
    try {
      const r = await fetch('/api/agents/status');
      if (r.ok) { setData(await r.json()); setLastUpdated(new Date()); }
    } catch (_) {}
    finally { setLoading(false); if (manual) setRefreshing(false); }
  };

  React.useEffect(() => {
    load();
    const iv = setInterval(load, 30000);
    return () => clearInterval(iv);
  }, []);

  const navigate = (sub) =>
    window.dispatchEvent(new CustomEvent('digi-subnav', { detail: { storageKey: 'digi-sistema-sub', val: sub } }));

  const minsSince = (ts) => ts ? Math.round((Date.now() - new Date(ts).getTime()) / 60000) : null;

  const fmtTime = (ts) => {
    if (!ts) return '—';
    const d   = new Date(ts);
    const now = new Date();
    const t   = d.toLocaleTimeString('pt-PT', { hour: '2-digit', minute: '2-digit' });
    return d.toDateString() === now.toDateString()
      ? `hoje ${t}`
      : `${d.toLocaleDateString('pt-PT', { day: '2-digit', month: '2-digit' })} ${t}`;
  };

  const fmtRows = (n) => {
    if (!n) return '0';
    if (n >= 1000000) return `${(n / 1000000).toFixed(1)}M`;
    if (n >= 1000)    return `${Math.round(n / 1000)}K`;
    return String(n);
  };

  const minsAgo = (ts) => {
    const m = minsSince(ts);
    if (m === null) return '—';
    if (m === 0)    return 'agora mesmo';
    if (m < 60)     return `há ${m} min`;
    return `há ${Math.round(m / 60)}h`;
  };

  const nextVP = () => {
    const next = new Date();
    next.setHours(3, 0, 0, 0);
    if (next <= new Date()) next.setDate(next.getDate() + 1);
    const label = next.toLocaleDateString('pt-PT', { weekday: 'short', day: '2-digit', month: '2-digit' });
    return `${label} 03:00`;
  };

  // ── Styles ────────────────────────────────────────────────────────────────
  const S = {
    page:        { display: 'flex', flexDirection: 'column', height: '100%', minHeight: 0, overflow: 'hidden', background: 'var(--bg)' },
    header:      { display: 'flex', alignItems: 'center', padding: '16px 24px 12px', borderBottom: '1px solid var(--border)', flexShrink: 0 },
    label:       { fontSize: 10, fontFamily: 'var(--font-mono, monospace)', letterSpacing: '0.1em', color: 'var(--text-muted)', marginBottom: 2 },
    h1:          { fontSize: 17, fontWeight: 700 },
    headerRight: { marginLeft: 'auto', display: 'flex', gap: 8 },
    btn:         { fontSize: 11, padding: '5px 12px', borderRadius: 5, border: '1px solid var(--border)', background: 'var(--surface-muted)', cursor: 'pointer', color: 'inherit' },
    btnPrimary:  { fontSize: 11, padding: '5px 12px', borderRadius: 5, border: '1px solid rgba(99,102,241,0.4)', background: 'rgba(99,102,241,0.15)', color: '#6366f1', cursor: 'pointer' },
    content:     { flex: 1, overflowY: 'auto', padding: '18px 24px' },
    sumBar:      { display: 'flex', gap: 10, marginBottom: 18, flexWrap: 'wrap' },
    chip:        (alert) => ({ display: 'flex', alignItems: 'center', gap: 6, padding: '5px 10px', borderRadius: 6, border: `1px solid ${alert ? 'rgba(239,68,68,0.35)' : 'var(--border)'}`, background: 'var(--surface-muted)', fontSize: 12 }),
    chipLabel:   { color: 'var(--text-muted)' },
    chipVal:     (alert) => ({ fontWeight: 600, color: alert ? '#dc2626' : 'var(--text)' }),
    grid:        { display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 },
    card:        (color) => ({ background: 'var(--bg-elev)', border: '1px solid var(--border)', borderLeft: `3px solid ${color}`, borderRadius: 10, padding: 16, display: 'flex', flexDirection: 'column', gap: 12, boxShadow: 'var(--shadow-sm)' }),
    cardHdr:     { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' },
    cardTitle:   { fontSize: 13.5, fontWeight: 700 },
    cardSub:     { fontSize: 11, color: 'var(--text-muted)', marginTop: 2, display: 'flex', alignItems: 'center', gap: 5, flexWrap: 'wrap' },
    metrics:     { display: 'flex', border: '1px solid var(--border)', borderRadius: 7, overflow: 'hidden', background: 'var(--bg-sunken)' },
    metric:      (last) => ({ flex: 1, padding: '9px 10px', textAlign: 'center', borderRight: last ? 'none' : '1px solid var(--border)' }),
    mVal:        { fontSize: 17, fontWeight: 700, lineHeight: 1 },
    mLabel:      { fontSize: 10, color: 'var(--text-muted)', marginTop: 3, letterSpacing: '0.05em', textTransform: 'uppercase' },
    infoRows:    { display: 'flex', flexDirection: 'column', gap: 4 },
    infoRow:     { display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11.5 },
    infoKey:     { color: 'var(--text-muted)' },
    infoVal:     { fontFamily: 'var(--font-mono, monospace)', fontSize: 11 },
    log:         { background: 'var(--bg-sunken)', border: '1px solid var(--border)', borderRadius: 6, padding: '8px 10px', fontFamily: 'var(--font-mono, monospace)', fontSize: 10.5, lineHeight: 1.7 },
    logRow:      { display: 'flex', gap: 8 },
    logTime:     { color: 'var(--text-dim)', flexShrink: 0 },
    cardActions: { display: 'flex', gap: 6, paddingTop: 4, borderTop: '1px solid var(--border)' },
    cardBtn:     { fontSize: 10.5, padding: '4px 10px', borderRadius: 4, border: '1px solid var(--border)', background: 'var(--surface-muted)', cursor: 'pointer', color: 'inherit' },
    cardBtnP:    { fontSize: 10.5, padding: '4px 10px', borderRadius: 4, border: '1px solid rgba(99,102,241,0.4)', background: 'rgba(99,102,241,0.12)', color: '#6366f1', cursor: 'pointer' },
    modelTag:    { display: 'inline-flex', fontSize: 9.5, padding: '1px 5px', borderRadius: 3, background: 'rgba(99,102,241,0.1)', color: '#6366f1', border: '1px solid rgba(99,102,241,0.25)', fontFamily: 'var(--font-mono, monospace)' },
    modelTagY:   { display: 'inline-flex', fontSize: 9.5, padding: '1px 5px', borderRadius: 3, background: 'rgba(202,138,4,0.1)', color: '#b45309', border: '1px solid rgba(202,138,4,0.25)', fontFamily: 'var(--font-mono, monospace)' },
    footer:      { fontSize: 10, color: 'var(--text-muted)', textAlign: 'right', marginTop: 8 },
  };

  if (loading) return (
    <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: 'var(--text-muted)', fontSize: 13 }}>
      A carregar dados dos agentes…
    </div>
  );

  const { primavera = {}, heydigi = {}, ads = {}, marketing = {} } = data || {};
  const alertCount = [!primavera.alive, !heydigi.alive, !ads.alive].filter(Boolean).length;

  return (
    <div style={S.page}>

      {/* Header */}
      <div style={S.header}>
        <div>
          <div style={S.label}>SISTEMA · AGENTES</div>
          <div style={S.h1}>Estado dos Agentes</div>
        </div>
        <div style={S.headerRight}>
          <button style={S.btn} onClick={() => load(true)}>{refreshing ? 'A actualizar…' : 'Actualizar'}</button>
        </div>
      </div>

      <div style={S.content}>

        {/* Summary bar */}
        <div style={S.sumBar}>
          <div style={S.chip(false)}>
            <Dot c="#22c55e" />
            <span style={S.chipLabel}>Online</span>
            <span style={S.chipVal(false)}>{[primavera.alive, heydigi.alive, ads.alive].filter(Boolean).length} / 3</span>
          </div>
          <div style={S.chip(false)}>
            <Dot c="#6366f1" />
            <span style={S.chipLabel}>Integrado</span>
            <span style={S.chipVal(false)}>1</span>
          </div>
          <div style={S.chip(false)}>
            <Dot c="#22c55e" />
            <span style={S.chipLabel}>WA sessões</span>
            <span style={S.chipVal(false)}>{heydigi.sessions_total ?? '—'}</span>
          </div>
          <div style={S.chip(false)}>
            <Dot c={primavera.vp_snapshot ? '#16a34a' : 'var(--text-dim)'} />
            <span style={S.chipLabel}>Último VP sync</span>
            <span style={S.chipVal(false)}>{fmtTime(primavera.vp_snapshot?.created_at)}</span>
          </div>
          {alertCount > 0 && (
            <div style={S.chip(true)}>
              <Dot c="#ef4444" />
              <span style={S.chipLabel}>Alertas</span>
              <span style={S.chipVal(true)}>{alertCount}</span>
            </div>
          )}
        </div>

        {/* Agent grid */}
        <div style={S.grid}>

          {/* ── Primavera Sync Agent ──────────────────────────────────────── */}
          <div style={S.card(primavera.alive ? '#16a34a' : '#dc2626')}>
            <div style={S.cardHdr}>
              <div>
                <div style={S.cardTitle}>Primavera Sync Agent</div>
                <div style={S.cardSub}>MacBook Marketing · Tailscale 100.74.212.97</div>
              </div>
              <Badge alive={primavera.alive} />
            </div>
            <div style={S.metrics}>
              <div style={S.metric(false)}>
                <div style={{ ...S.mVal, color: primavera.alive ? '#16a34a' : '#dc2626' }}>{primavera.tables ?? '—'}</div>
                <div style={S.mLabel}>Tabelas activas</div>
              </div>
              <div style={S.metric(false)}>
                <div style={S.mVal}>{fmtRows(primavera.total_rows)}</div>
                <div style={S.mLabel}>Linhas sincronizadas</div>
              </div>
              <div style={S.metric(true)}>
                <div style={S.mVal}>{primavera.last_seen_mins != null ? `${primavera.last_seen_mins} min` : '—'}</div>
                <div style={S.mLabel}>Último heartbeat</div>
              </div>
            </div>
            <div style={S.infoRows}>
              <div style={S.infoRow}><span style={S.infoKey}>Último VP snapshot</span><span style={S.infoVal}>{fmtTime(primavera.vp_snapshot?.created_at)}</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Próximo VP snapshot</span><span style={S.infoVal}>{nextVP()}</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Cron VP</span><span style={S.infoVal}>0 3 * * *</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Wake automático</span><span style={{ ...S.infoVal, color: '#16a34a' }}>02:55 diário</span></div>
            </div>
            <div style={S.log}>
              {(primavera.sync_log || []).map((e, i) => (
                <div key={i} style={S.logRow}>
                  <span style={S.logTime}>{fmtTime(e.started_at)}</span>
                  <span style={{ color: e.status === 'ok' ? (e.group_name === 'snapshot' ? '#7c3aed' : '#16a34a') : '#dc2626' }}>
                    {e.group_name === 'snapshot' ? `snapshot · ${e.table_name}` : e.table_name}
                    {e.rows_synced > 0 ? ` · ${fmtRows(e.rows_synced)} rows` : ''}
                    {e.error_msg    ? ` · ${e.error_msg}`                     : ''}
                    {e.duration_ms > 0 ? ` · ${(e.duration_ms / 1000).toFixed(1)}s` : ''}
                  </span>
                </div>
              ))}
              {(!primavera.sync_log?.length) && <span style={{ color: 'var(--text-muted)' }}>Sem registos recentes</span>}
            </div>
            <div style={S.cardActions}>
              <button style={S.cardBtn} onClick={() => navigate('primavera')}>Monitor completo</button>
            </div>
          </div>

          {/* ── Heydigi AI ───────────────────────────────────────────────── */}
          <div style={S.card(heydigi.alive ? '#16a34a' : '#dc2626')}>
            <div style={S.cardHdr}>
              <div>
                <div style={S.cardTitle}>Heydigi AI <span style={{ fontWeight: 400, color: 'var(--text-muted)' }}>· WhatsApp</span></div>
                <div style={S.cardSub}>
                  Prod · farben-holding.ai/heydigi/webhook &nbsp;<span style={S.modelTag}>claude-sonnet-4-6</span>
                </div>
              </div>
              <Badge alive={heydigi.alive} />
            </div>
            <div style={S.metrics}>
              <div style={S.metric(false)}>
                <div style={S.mVal}>{heydigi.sessions_total ?? '—'}</div>
                <div style={S.mLabel}>Sessões totais</div>
              </div>
              <div style={S.metric(false)}>
                <div style={S.mVal}>{(heydigi.msgs_total || 0).toLocaleString('pt-PT')}</div>
                <div style={S.mLabel}>Mensagens</div>
              </div>
              <div style={S.metric(true)}>
                <div style={S.mVal}>{heydigi.sessions_24h ?? '—'}</div>
                <div style={S.mLabel}>Activos 24h</div>
              </div>
            </div>
            <div style={S.infoRows}>
              <div style={S.infoRow}><span style={S.infoKey}>Marcas activas</span><span style={S.infoVal}>{(heydigi.marcas || []).join(' · ') || '—'}</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Última interacção</span><span style={S.infoVal}>{fmtTime(heydigi.last_activity)}</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Webhook status</span><span style={{ ...S.infoVal, color: heydigi.alive ? '#16a34a' : '#dc2626' }}>{heydigi.alive ? '200 OK' : 'Sem resposta'}</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Contactos únicos</span><span style={S.infoVal}>{heydigi.phones ?? '—'}</span></div>
            </div>
            <div style={S.log}>
              {(heydigi.recent || []).map((s, i) => (
                <div key={i} style={S.logRow}>
                  <span style={S.logTime}>{fmtTime(s.updated_at)}</span>
                  <span style={{ color: '#16a34a' }}>{s.visitor_id}{s.marca ? ` · ${s.marca}` : ''}</span>
                </div>
              ))}
              {(!heydigi.recent?.length) && <span style={{ color: 'var(--text-muted)' }}>Sem sessões recentes</span>}
            </div>
            <div style={S.cardActions}>
              <button style={S.cardBtn} onClick={() => navigate('inbox')}>Ver conversas</button>
            </div>
          </div>

          {/* ── Ads Agent ────────────────────────────────────────────────── */}
          <div style={S.card(ads.alive ? '#16a34a' : '#dc2626')}>
            <div style={S.cardHdr}>
              <div>
                <div style={S.cardTitle}>Ads Agent <span style={{ fontWeight: 400, color: 'var(--text-muted)' }}>· Meta / Facebook Ads</span></div>
                <div style={S.cardSub}>localhost:3004 · portal proxy /api/meta-performance</div>
              </div>
              <Badge alive={ads.alive} />
            </div>
            <div style={S.metrics}>
              <div style={S.metric(false)}>
                <div style={{ ...S.mVal, fontSize: 13, color: 'var(--text-muted)' }}>—</div>
                <div style={S.mLabel}>Campanhas activas</div>
              </div>
              <div style={S.metric(false)}>
                <div style={{ ...S.mVal, fontSize: 13, color: 'var(--text-muted)' }}>—</div>
                <div style={S.mLabel}>Impressões hoje</div>
              </div>
              <div style={S.metric(true)}>
                <div style={{ ...S.mVal, fontSize: 13, color: ads.alive ? '#16a34a' : '#dc2626' }}>{ads.alive ? 'Online' : 'Offline'}</div>
                <div style={S.mLabel}>Estado</div>
              </div>
            </div>
            <div style={S.infoRows}>
              <div style={S.infoRow}><span style={S.infoKey}>Health check</span><span style={{ ...S.infoVal, color: ads.alive ? '#16a34a' : '#dc2626' }}>{ads.alive ? '200 OK' : '404 / Sem resposta'}</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Cache portal</span><span style={{ ...S.infoVal, color: '#fbbf24' }}>stale</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Marcas</span><span style={S.infoVal}>Digidelta · Decal · AllDecor · BIOND</span></div>
            </div>
            <div style={S.log}>
              <div style={S.logRow}><span style={S.logTime}>—</span><span style={{ color: 'var(--text-muted)' }}>{ads.alive ? 'Agent online' : 'Sem dados — agent offline'}</span></div>
              <div style={S.logRow}><span style={S.logTime}>—</span><span style={{ color: 'var(--text-muted)' }}>Performance Ads a mostrar dados em cache</span></div>
            </div>
            <div style={S.cardActions}>
              <button style={S.cardBtn} onClick={() => load(true)}>Verificar</button>
            </div>
          </div>

          {/* ── Marketing AI ─────────────────────────────────────────────── */}
          <div style={S.card('#6366f1')}>
            <div style={S.cardHdr}>
              <div>
                <div style={S.cardTitle}>Marketing AI <span style={{ fontWeight: 400, color: 'var(--text-muted)' }}>· Agente integrado</span></div>
                <div style={S.cardSub}>
                  marketing-routes.js · Portal &nbsp;
                  <span style={S.modelTag}>claude-sonnet-4-6</span>
                  <span style={S.modelTagY}>claude-haiku-4-5</span>
                </div>
              </div>
              <Badge alive="embedded" />
            </div>
            <div style={S.metrics}>
              <div style={S.metric(false)}>
                <div style={S.mVal}>{marketing.briefings || '—'}</div>
                <div style={S.mLabel}>Briefings</div>
              </div>
              <div style={S.metric(false)}>
                <div style={S.mVal}>{marketing.strategies || '—'}</div>
                <div style={S.mLabel}>Estratégias</div>
              </div>
              <div style={S.metric(true)}>
                <div style={S.mVal}>{marketing.content_jobs || '—'}</div>
                <div style={S.mLabel}>Conteúdos</div>
              </div>
            </div>
            <div style={S.infoRows}>
              <div style={S.infoRow}><span style={S.infoKey}>Endpoints SSE</span><span style={S.infoVal}>generate · apreciation · suggest-b4b5</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Claude API</span><span style={{ ...S.infoVal, color: '#16a34a' }}>Activa</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Skill</span><span style={S.infoVal}>digidelta-creative-proposal</span></div>
              <div style={S.infoRow}><span style={S.infoKey}>Deploy</span><span style={S.infoVal}>Baked na imagem Docker (portal)</span></div>
            </div>
            <div style={S.log}>
              <div style={S.logRow}><span style={S.logTime}>Note</span><span style={{ color: 'var(--text-muted)' }}>Agente embutido — sem container próprio.</span></div>
              <div style={S.logRow}><span style={S.logTime}>     </span><span style={{ color: 'var(--text-muted)' }}>Métricas obtidas da BD do portal.</span></div>
            </div>
            <div style={S.cardActions}>
              <button style={S.cardBtn} onClick={() => window.dispatchEvent(new CustomEvent('digi-subnav', { detail: { storageKey: 'digi-marketing-sub', val: 'briefings' } }))}>Ver briefings</button>
            </div>
          </div>

        </div>

        <div style={S.footer}>
          {lastUpdated ? `Actualizado ${minsAgo(lastUpdated)} · auto-refresh 30s` : 'A carregar…'}
        </div>
      </div>
    </div>
  );
};

window.SistemaAgentes = SistemaAgentes;
