const PURPOSE = {
  mx: 'MX',
  spf: 'SPF',
  dkim: 'DKIM',
  dmarc: 'DMARC',
  'mail-host': 'Mail host',
  autodiscover: 'Autodiscover',
  'mail-alias': 'Alias',
  other: 'Outro',
}

const SOURCE = {
  cf_ligbox: 'CF Ligbox',
  cf_byo: 'CF cliente',
  public_resolver: 'Público',
  planned_ligbox: 'Planeado',
  openpanel_bind: 'OpenPanel',
}

function checkIcon(c) {
  if (!c) return '—'
  if (c.ok) return '✅'
  if (c.warn) return '⚠'
  return '❌'
}

export default function DnsViewerPanel({ data, loading, error }) {
  if (loading) return <p className="loading">Carregando DNS…</p>
  if (error) return <p className="error-text">{error}</p>
  if (!data) return <p className="loading">Sem dados DNS.</p>

  const summary = data.summary || {}
  const checks = data.public_checks || {}
  const ns = data.nameservers || {}

  return (
    <div className="dns-viewer-panel card">
      <div className="dns-viewer-head">
        <span className={`badge ${data.display_mode === 'planned' ? 'badge-warn' : 'badge-ok'}`}>
          {data.mode_label || data.dns_mode}
        </span>
        {data.email_service ? <span className="badge badge-ok">E-mail</span> : null}
      </div>

      {data.mode_message ? <p className="dns-viewer-msg">{data.mode_message}</p> : null}

      {ns.current_public?.length ? (
        <p className="dns-viewer-meta">
          NS: {ns.current_public.join(' · ')}
          {ns.match_ligbox ? ' · ✅ Cloudflare' : data.dns_mode === 'openpanel_bind' ? ' · OpenPanel BIND' : ''}
        </p>
      ) : null}

      {data.openpanel?.zone_responds ? (
        <p className="dns-viewer-meta">
          BIND OpenPanel ({data.openpanel.bind_host}) — zona activa
        </p>
      ) : null}

      <div className="kpi-inline">
        <span><strong>{summary.total || 0}</strong> registos</span>
        <span><strong>{summary.email_related || 0}</strong> e-mail</span>
      </div>

      {Object.keys(checks).length ? (
        <p className="dns-viewer-meta">
          Público: MX {checkIcon(checks.mx)} · SPF {checkIcon(checks.spf)} · DKIM {checkIcon(checks.dkim)} · DMARC {checkIcon(checks.dmarc)}
        </p>
      ) : null}

      <div className="table-wrap">
        <table className="data-table">
          <thead>
            <tr>
              <th>Função</th><th>Nome</th><th>Tipo</th><th>Conteúdo</th><th>Origem</th>
            </tr>
          </thead>
          <tbody>
            {(data.records || []).length ? (data.records || []).map((r, i) => (
              <tr key={`${r.name}-${r.type}-${i}`} className={r.email_related ? 'dns-email-row' : ''}>
                <td>{PURPOSE[r.purpose] || r.purpose || '—'}</td>
                <td><code>{r.name}</code></td>
                <td><strong>{r.type}</strong>{r.priority != null ? ` (${r.priority})` : ''}</td>
                <td className="dns-content">{r.content}</td>
                <td>{SOURCE[r.source] || r.source || '—'}</td>
              </tr>
            )) : (
              <tr><td colSpan={5}>Sem registos para este domínio.</td></tr>
            )}
          </tbody>
        </table>
      </div>

      {(data.planned_records || []).length ? (
        <>
          <h4 className="dns-viewer-sub">Planeados (após NS)</h4>
          <div className="table-wrap">
            <table className="data-table">
              <thead>
                <tr><th>Função</th><th>Nome</th><th>Tipo</th><th>Conteúdo</th></tr>
              </thead>
              <tbody>
                {data.planned_records.map((r, i) => (
                  <tr key={`p-${i}`}>
                    <td>{PURPOSE[r.purpose] || '—'}</td>
                    <td><code>{r.name}</code></td>
                    <td>{r.type}</td>
                    <td>{r.content}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </>
      ) : null}

      {data.edit_links?.length ? (
        <div className="dns-viewer-actions">
          {data.edit_links.map((l) => (
            <a key={l.url} className="btn btn-ghost btn-sm" href={l.url} target="_blank" rel="noopener noreferrer">
              {l.label} ↗
            </a>
          ))}
        </div>
      ) : null}

      {data.errors?.length ? (
        <p className="error-text">{data.errors.join(' · ')}</p>
      ) : null}
    </div>
  )
}
