/* Audit log + Version history — wired to live /api/audit.
   /api/audit?limit=N&offset=N → { logs: [...], total, limit, offset }.
   Each log entry has time, actor, action, target, and optionally
   ip/method. Shape varies — render defensively. */

function AL_methodTone(method) {
  const m = (method || '').toLowerCase();
  if (m.includes('delete')) return 'is-delete';
  if (m.includes('post') || m.includes('put') || m.includes('patch') || m === 'write') return 'is-write';
  if (m.includes('login') || m === 'auth') return 'is-auth';
  return '';
}

const AL_LIMIT = 50;
const AL_ENTITY_TYPES = ['', 'species', 'campaign', 'screen', 'zone', 'site', 'user', 'asset'];

function AuditLogScreen() {
  const [logs, setLogs] = useState([]);
  const [total, setTotal] = useState(0);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [offset, setOffset] = useState(0);
  const [entityType, setEntityType] = useState('');
  const [entityId, setEntityId] = useState('');
  const [range, setRange] = useState('all'); /* all | 7d | 30d | 90d */

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    const params = new URLSearchParams({ limit: AL_LIMIT, offset });
    if (entityType) params.set('entity_type', entityType);
    if (entityId) params.set('entity_id', entityId);
    /* Derive a from-date from the chosen range. Backend accepts a
       `since` ISO timestamp for filtering. */
    if (range !== 'all') {
      const days = range === '7d' ? 7 : range === '30d' ? 30 : 90;
      const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
      params.set('since', since);
    }
    apiFetch(`/api/audit?${params.toString()}`)
      .then((res) => {
        if (cancelled) return;
        setLogs(res.logs || []);
        setTotal(res.total || 0);
        setLoading(false);
      })
      .catch((err) => {
        if (cancelled) return;
        setError(err.message);
        setLoading(false);
      });
    return () => { cancelled = true; };
  }, [offset, entityType, entityId, range]);

  /* Some audit rows reference a target entity. Map type → hash route so
     the curator can jump straight to the affected record. */
  function openTarget(e) {
    const t = e.entity_type || e.target_type;
    const id = e.entity_id || e.target_id;
    if (!t || !id) return;
    const route = ({
      species: 'species', campaign: 'campaign', screen: 'screen',
      zone: 'zones', site: 'site', asset: 'media',
    })[t];
    if (route) window.location.hash = `#${route}/${id}`;
  }

  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 1280 }}>
        <header style={{ marginBottom: 16 }}>
          <div className="aq-eyebrow">
            <span>Slate</span>
            <span className="aq-sep">·</span>
            <span>Immutable event stream</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--aq-ff-display)', fontSize: 26, fontWeight: 500,
            letterSpacing: '-0.012em', color: 'var(--aq-text)', margin: '4px 0 4px',
          }}>Audit log</h1>
          <p style={{ fontSize: 13, color: 'var(--aq-text-faint)', margin: 0 }}>
            Append-only log of every action across the platform. {total > 0 ? `${total.toLocaleString()} entries.` : ''}
          </p>
        </header>

        {/* Filter + pagination strip — mirrors the original CMS audit
            toolbar (entity type dropdown, free-text id, prev/next). */}
        <div style={{
          display: 'flex', gap: 8, padding: 8, marginBottom: 12,
          background: 'var(--aq-surface)', border: '1px solid var(--aq-line)',
          borderRadius: 8, alignItems: 'center', flexWrap: 'wrap',
        }}>
          <select
            value={entityType}
            onChange={(e) => { setEntityType(e.target.value); setOffset(0); }}
            style={{
              background: 'var(--aq-surface-2)', border: '1px solid var(--aq-line)',
              borderRadius: 6, padding: '6px 9px', color: 'var(--aq-text)',
              fontSize: 12, outline: 0, cursor: 'pointer',
            }}
          >
            {AL_ENTITY_TYPES.map((t) => (
              <option key={t || 'all'} value={t}>{t ? t : 'All entity types'}</option>
            ))}
          </select>
          <div style={{
            display: 'flex', gap: 2, padding: 2,
            background: 'var(--aq-surface-2)',
            border: '1px solid var(--aq-line)', borderRadius: 7,
          }}>
            {[
              ['all', 'All time'],
              ['7d',  'Last 7d'],
              ['30d', '30d'],
              ['90d', '90d'],
            ].map(([id, label]) => (
              <button
                key={id}
                onClick={() => { setRange(id); setOffset(0); }}
                style={{
                  padding: '4px 9px', borderRadius: 4, border: 0,
                  background: range === id ? 'var(--aq-surface-3, var(--aq-surface))' : 'transparent',
                  color: range === id ? 'var(--aq-text)' : 'var(--aq-text-faint)',
                  fontFamily: 'var(--aq-ff-mono)', fontSize: 10,
                  letterSpacing: '0.06em', cursor: 'pointer',
                }}
              >{label}</button>
            ))}
          </div>
          <input
            type="text"
            value={entityId}
            onChange={(e) => setEntityId(e.target.value)}
            onKeyDown={(e) => { if (e.key === 'Enter') setOffset(0); }}
            placeholder="Filter by entity ID…"
            style={{
              flex: '1 1 220px',
              background: 'var(--aq-surface-2)', border: '1px solid var(--aq-line)',
              borderRadius: 6, padding: '6px 9px', color: 'var(--aq-text)',
              fontSize: 12, outline: 0,
            }}
          />
          <span style={{ flex: 1 }} />
          <span style={{
            fontFamily: 'var(--aq-ff-mono)', fontSize: 10.5,
            color: 'var(--aq-text-faint)', letterSpacing: '0.06em',
          }}>
            {total === 0 ? '0' : `${offset + 1}–${Math.min(offset + AL_LIMIT, total)}`} of {total.toLocaleString()}
          </span>
          <button
            onClick={() => setOffset((o) => Math.max(0, o - AL_LIMIT))}
            disabled={offset === 0}
            className="x-btn ghost sm"
          >Previous</button>
          <button
            onClick={() => setOffset((o) => o + AL_LIMIT)}
            disabled={offset + AL_LIMIT >= total}
            className="x-btn ghost sm"
          >Next</button>
        </div>

        {loading && (
          <div style={{ padding: 60, textAlign: 'center', color: 'var(--aq-text-faint)' }}>
            Loading audit log…
          </div>
        )}
        {error && (
          <div style={{
            padding: '10px 14px',
            background: 'color-mix(in srgb, var(--aq-danger) 12%, transparent)',
            border: '1px solid color-mix(in srgb, var(--aq-danger) 30%, transparent)',
            borderRadius: 6, color: 'var(--aq-danger)', fontSize: 12,
          }}>{error}</div>
        )}

        {!loading && !error && logs.length === 0 && (
          <div className="x-card" style={{ padding: '60px 24px', textAlign: 'center' }}>
            <div style={{ fontSize: 13, color: 'var(--aq-text-faint)' }}>
              No audit entries yet.
            </div>
          </div>
        )}

        {!loading && !error && logs.length > 0 && (
          <div className="x-card x-audit-table" style={{ overflow: 'hidden' }}>
            <div className="x-audit-row is-head">
              <div>Time</div>
              <div></div>
              <div>Actor</div>
              <div>Action</div>
              <div>IP</div>
              <div>Method</div>
            </div>
            {logs.map((e) => {
              const time = e.created_at || e.time || e.timestamp;
              const actor = e.actor_name || e.user_name || e.actor || e.user_id || 'System';
              const action = e.action || e.event_type || 'event';
              const target = e.target || e.target_id || e.entity_type || '';
              const ip = e.ip_address || e.ip || '—';
              const method = e.method || e.kind || e.event_type || '';
              const hasTarget = !!(e.entity_type || e.target_type) && !!(e.entity_id || e.target_id);
              return (
                <div
                  key={e.id}
                  className="x-audit-row"
                  onClick={() => hasTarget && openTarget(e)}
                  style={{ cursor: hasTarget ? 'pointer' : 'default' }}
                  title={hasTarget ? `Open ${e.entity_type || e.target_type}` : undefined}
                >
                  <div className="x-audit-time">
                    {time ? new Date(time).toLocaleString() : '—'}
                  </div>
                  <div>
                    <span className="x-avatar" style={{
                      background: actor === 'System' ? 'var(--aq-text-faint)' : 'var(--aq-accent)',
                    }}>{(actor || '?')[0].toUpperCase()}</span>
                  </div>
                  <div className="x-audit-actor">{actor}</div>
                  <div className="x-audit-action">
                    <b>{action}</b>
                    {target && <> <span className="x-audit-target">{(target + '').slice(0, 32)}</span></>}
                  </div>
                  <div className="x-audit-ip">{ip}</div>
                  <div>
                    <span className={`x-audit-method ${AL_methodTone(method)}`}>{method || '—'}</span>
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

/* Version history — no dedicated /api/versions endpoint. Shows a
   placeholder until the route lands. */
function VersionHistoryScreen() {
  return (
    <div className="aq-content">
      <div className="aq-content-inner" style={{ maxWidth: 1100 }}>
        <header style={{ marginBottom: 16 }}>
          <div className="aq-eyebrow">
            <span>Slate</span>
            <span className="aq-sep">·</span>
            <span>Version history</span>
          </div>
          <h1 style={{
            fontFamily: 'var(--aq-ff-display)', fontSize: 26, fontWeight: 500,
            letterSpacing: '-0.012em', color: 'var(--aq-text)', margin: '4px 0 4px',
          }}>Version history</h1>
          <p style={{ fontSize: 13, color: 'var(--aq-text-faint)', margin: 0 }}>
            Per-entity revision timelines. Versioned via creatives table — drilldown
            available from each campaign's edit page.
          </p>
        </header>

        <div className="x-card" style={{ padding: '60px 24px', textAlign: 'center' }}>
          <div style={{ fontSize: 13, color: 'var(--aq-text-faint)', maxWidth: 480, margin: '0 auto' }}>
            Open a campaign or species record and use the in-page version control
            to see its revision history. A consolidated view across all entities
            isn't wired yet.
          </div>
        </div>
      </div>
    </div>
  );
}

window.AuditLogScreen = AuditLogScreen;
window.VersionHistoryScreen = VersionHistoryScreen;
