function statusClass(status) {
  if (status === 'healthy') return 'health-ok'
  if (status === 'degraded') return 'health-warn'
  if (status === 'critical') return 'health-bad'
  return 'health-unknown'
}

function statusLabel(status) {
  if (status === 'healthy') return 'Saudável'
  if (status === 'degraded') return 'Degradado'
  if (status === 'critical') return 'Crítico'
  return 'Desconhecido'
}

export default function HealthCards({ tenants }) {
  if (!tenants?.length) {
    return (
      <div className="card">
        <p style={{ margin: 0, color: 'var(--lb-text-secondary)' }}>Nenhum tenant auditado. Aguarde ciclo de auditoria ou complete onboarding.</p>
      </div>
    )
  }

  return (
    <div className="health-grid">
      {tenants.map((t) => {
        const pass = t.score?.pass ?? 0
        const total = t.score?.total ?? 8
        const warn = t.score?.warn ?? 0
        const fail = t.score?.fail ?? 0
        const cls = statusClass(t.status)
        return (
          <div key={t.tenant_id || t.name} className={`health-card health-card--${cls}`}>
            <div className="health-card-head">
              <div>
                <h3>{t.name}</h3>
                <p className="health-card-meta">
                  <code>{t.ip}</code>
                  {' · '}
                  <strong>{t.domains_count ?? 0}</strong> domínio(s)
                </p>
              </div>
              <span className={`health-badge health-badge--${cls}`}>{statusLabel(t.status)}</span>
            </div>
            <p className="health-score-line">
              {pass}/{total} pass · {warn} warn · {fail} fail
            </p>
            {t.kind === 'wazuh_soc' && t.alerts_count != null ? (
              <p className="health-card-meta">Alertas Wazuh: {t.alerts_count} · max L{t.max_level ?? '—'}</p>
            ) : null}
            {t.top_issues?.length ? (
              <ul className="health-issue-list">
                {t.top_issues.slice(0, 3).map((i) => (
                  <li key={`${i.domain}-${i.check_id}`}>
                    <code>{i.domain}</code> · {i.check_id} — {i.message || i.status}
                  </li>
                ))}
              </ul>
            ) : (
              <p className="health-card-meta">Sem issues críticas no último audit</p>
            )}
          </div>
        )
      })}
    </div>
  )
}
