// AUTOMATION PLATFORM — Audit Log + Scripts + Activity tabs
const { useState: useAuAuState, useMemo: useAuAuMemo } = React;
const Taua = window.ArbiterTokens;

function AutoAudit({ data }) {
  const au = window.__au;
  const [actionFilter, setActionFilter] = useAuAuState('All');
  const [search, setSearch] = useAuAuState('');

  const actions = useAuAuMemo(() => ['All', ...new Set(data.audit.map(a => a.action))], [data]);
  const filtered = data.audit.filter(a =>
    (actionFilter === 'All' || a.action === actionFilter) &&
    (!search || a.object.toLowerCase().includes(search.toLowerCase()) || a.actor.toLowerCase().includes(search.toLowerCase()))
  );

  const successCount = data.audit.filter(a => a.outcome === 'success').length;
  const failCount    = data.audit.filter(a => a.outcome === 'failed').length;

  return (
    <div>
      <AuHero
        accent={au.slate} bg={au.slateBg}
        title={`Audit log — ${au.num(data.kpis.auditEventsYtd)} events YTD`}
        description={<>
          Compliance-grade audit trail with SHA-256 hash chain. Every trigger fire, workflow run, integration sync, and credential access logged. <b style={{ color: au.emerald, fontFamily: Taua.font.mono }}>{successCount}</b> success · <b style={{ color: au.crimson, fontFamily: Taua.font.mono }}>{failCount}</b> failed in visible window.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Events YTD</span><span style={au.statValue}>{au.num(data.kpis.auditEventsYtd)}</span><span style={{ ...au.statDelta, color: Taua.color.text.tertiary }}>compliance-grade</span></div>
        <div style={au.stat}><span style={au.statLabel}>Shown</span><span style={au.statValue}>{filtered.length}</span><span style={{ ...au.statDelta, color: Taua.color.text.tertiary }}>of {data.audit.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Success</span><span style={{ ...au.statValue, color: au.emerald }}>{successCount}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Failures</span><span style={{ ...au.statValue, color: au.crimson }}>{failCount}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Integrity</span><span style={{ ...au.statValue, color: au.emerald }}><Icons.Check size={11}/></span><span style={{ ...au.statDelta, color: Taua.color.text.tertiary, fontFamily: Taua.font.mono }}>SHA-256 chain</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Audit log — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search actor / object…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taua.color.border.light}`, borderRadius: '5px', background: Taua.color.bg.card, color: Taua.color.text.primary, minWidth: '220px', fontFamily: Taua.font.family }} />
            <select value={actionFilter} onChange={e => setActionFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Taua.color.border.light}`, borderRadius: '5px', background: Taua.color.bg.card, color: Taua.color.text.secondary }}>
              {actions.map(a => <option key={a} value={a}>Action: {a}</option>)}
            </select>
            <button style={au.btnSecondary}>⇩ Export CSV</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Event ID</th>
              <th style={au.th}>Timestamp</th>
              <th style={au.th}>Actor</th>
              <th style={au.th}>Action</th>
              <th style={au.th}>Object</th>
              <th style={au.th}>Outcome</th>
              <th style={au.th}>Hash</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(a => {
              const outcomeColor = a.outcome === 'success' ? au.emerald : au.crimson;
              return (
                <tr key={a.id}>
                  <td style={{ ...au.td, fontFamily: Taua.font.mono, fontSize: '10px', color: au.lime, fontWeight: 700 }}>{a.id}</td>
                  <td style={{ ...au.td, fontFamily: Taua.font.mono, fontSize: '10px', color: Taua.color.text.tertiary }}>{a.at}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taua.color.text.primary, fontWeight: 600 }}>{a.actor}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: au.limeBg, color: au.limeDeep, fontFamily: Taua.font.mono }}>{a.action}</span></td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taua.color.text.secondary, maxWidth: '320px' }}>{a.object}</td>
                  <td style={au.td}>
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', fontSize: '11px', fontWeight: 700, color: outcomeColor, textTransform: 'capitalize' }}>
                      {a.outcome === 'success' ? 'ok' : 'x'} {a.outcome}
                    </span>
                  </td>
                  <td style={{ ...au.td, fontFamily: Taua.font.mono, fontSize: '10px', color: Taua.color.text.tertiary }}>{a.hash}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AutoScripts({ data }) {
  const au = window.__au;

  return (
    <div>
      <AuHero
        accent={au.lime} bg={au.limeBg}
        title={`Scripts — ${data.scripts.length} executable actions`}
        description={<>
          Custom code consumed by workflow steps. <b style={{ color: au.cobalt, fontFamily: Taua.font.mono }}>{au.num(data.scripts.reduce((s, x) => s + x.linesOfCode, 0))}</b> lines across <b>{new Set(data.scripts.map(s => s.language)).size}</b> languages. Every publish passes SAST and policy checks.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Scripts</span><span style={au.statValue}>{data.scripts.length}</span><span style={{ ...au.statDelta, color: Taua.color.text.tertiary }}>custom code</span></div>
        <div style={au.stat}><span style={au.statLabel}>Total LoC</span><span style={{ ...au.statValue, color: au.cobalt }}>{au.num(data.scripts.reduce((s, x) => s + x.linesOfCode, 0))}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Active</span><span style={{ ...au.statValue, color: au.emerald }}>{data.scripts.filter(s => s.status === 'Active').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Languages</span><span style={au.statValue}>{new Set(data.scripts.map(s => s.language)).size}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Script library — {data.scripts.length}</span>
          <button style={au.btnPrimary}>+ New script</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Name / Description</th>
              <th style={au.th}>Language</th>
              <th style={au.th}>Owner</th>
              <th style={{ ...au.th, textAlign: 'right' }}>LoC</th>
              <th style={au.th}>Last run</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {data.scripts.map(s => {
              const ss = au.statusColor(s.status);
              return (
                <tr key={s.id}>
                  <td style={{ ...au.td, fontFamily: Taua.font.mono, color: au.lime, fontWeight: 700 }}>{s.id}</td>
                  <td style={{ ...au.td, maxWidth: '420px' }}>
                    <div style={{ fontFamily: Taua.font.mono, fontSize: '11px', fontWeight: 700, color: Taua.color.text.primary }}>{s.name}</div>
                    <div style={{ fontSize: '10px', color: Taua.color.text.tertiary, marginTop: '3px', lineHeight: 1.4 }}>{s.description}</div>
                  </td>
                  <td style={au.td}><span style={{ ...au.tag, background: au.cobaltBg, color: au.cobalt, fontFamily: Taua.font.mono }}>{s.language}</span></td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taua.color.text.secondary }}>{s.owner}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Taua.font.mono, color: Taua.color.text.primary }}>{au.num(s.linesOfCode)}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Taua.color.text.tertiary }}>{s.lastRun}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{s.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AutoActivity({ data }) {
  const au = window.__au;
  const warnCount = data.activity.filter(a => a.severity === 'warn').length;
  const critCount = data.activity.filter(a => a.severity === 'critical').length;
  return (
    <div>
      <AuHero
        accent={au.slate} bg={au.slateBg}
        title="Activity stream — live platform chatter"
        description={<>
          Human-readable stream of what just happened. Triggers, workflow completions, integration syncs, user actions. <b style={{ color: au.amber, fontFamily: Taua.font.mono }}>{warnCount}</b> warning · <b style={{ color: au.crimson, fontFamily: Taua.font.mono }}>{critCount}</b> critical in visible window.
        </>}
      />
      <div style={au.card}>
        <div style={au.cardH}>
          <span>Platform activity stream — {data.activity.length}</span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: '5px', fontSize: '10px', color: au.emerald, fontWeight: 600 }}><span style={{ width: '6px', height: '6px', background: au.emerald, borderRadius: '50%' }} />LIVE</span>
        </div>
        <div>
          {data.activity.map(a => {
            const sev = a.severity === 'warn' ? au.amber : a.severity === 'critical' ? au.crimson : au.lime;
            return (
              <div key={a.id} style={{ padding: '10px 16px', borderBottom: `1px solid ${Taua.color.border.light}`, borderLeft: `3px solid ${sev}`, display: 'grid', gridTemplateColumns: '90px 140px 1fr 1fr', gap: '12px', alignItems: 'center' }}>
                <span style={{ fontFamily: Taua.font.mono, fontSize: '10px', color: Taua.color.text.tertiary }}>{a.time}</span>
                <span style={{ fontSize: '11px', fontWeight: 600, color: Taua.color.text.primary }}>{a.actor}</span>
                <span style={{ fontSize: '11px', color: Taua.color.text.secondary }}>{a.action}</span>
                <span style={{ fontSize: '11px', color: Taua.color.text.primary, fontWeight: 500 }}>{a.target}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

window.AutoAudit    = AutoAudit;
window.AutoScripts  = AutoScripts;
window.AutoActivity = AutoActivity;
