// AUTOMATION PLATFORM — Ops sub-platform
// Views: Secrets · Cost · HITL Inbox
const { useState: useOpsState } = React;
const Tops = window.ArbiterTokens;

const OPS_VIEWS = [
  { id: 'secrets',   label: 'Secrets Vault' },
  { id: 'cost',      label: 'Cost & Chargeback' },
  { id: 'hitl',      label: 'HITL Inbox' },
  { id: 'analytics', label: 'Analytics' },
  { id: 'audit',     label: 'Audit Log' },
  { id: 'activity',  label: 'Activity' },
];

function OBadge({ color, bg, children, mono = false }) {
  return <span style={{ display: 'inline-flex', alignItems: 'center', padding: '2px 8px', borderRadius: '10px', fontSize: '10px', fontWeight: 700, background: bg, color, fontFamily: mono ? Tops.font.mono : Tops.font.family }}>{children}</span>;
}

// ─── SECRETS ──────────────────────────────────────────────────────────────────
function OpsSecrets({ data }) {
  const au = window.__au;
  const rows = data.secrets;
  const expired = rows.filter(s => s.status === 'Expired').length;
  const dueSoon = rows.filter(s => s.status === 'Due Soon').length;

  const statusStyle = (s) => {
    if (s === 'Expired')  return { bg: au.crimsonBg, color: au.crimson };
    if (s === 'Due Soon') return { bg: au.amberBg, color: au.amber };
    return { bg: au.emeraldBg, color: au.emerald };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.crimson}`, background: au.crimsonBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.crimson, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Secrets vault — {expired} expired · {dueSoon} due soon</div>
          <div style={{ fontSize: '11px', color: Tops.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Azure Key Vault + HSM-backed. Rotation schedule, scope audit, access telemetry. Expired secrets auto-disable integrations.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Secrets managed</span><span style={au.statValue}>{rows.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Expired</span><span style={{ ...au.statValue, color: expired > 0 ? au.crimson : au.emerald }}>{expired}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Due soon (≤30d)</span><span style={{ ...au.statValue, color: au.amber }}>{dueSoon}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Accesses (30d)</span><span style={au.statValue}>{rows.reduce((s, r) => s + r.accesses30d, 0).toLocaleString()}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Vault inventory — {rows.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={au.btnSecondary}>Access audit</button>
            <button style={au.btnSecondary}>Rotation schedule</button>
            <button style={{ ...au.btnPrimary, background: au.teal }}>+ Provision secret</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Name</th>
              <th style={au.th}>Category</th>
              <th style={au.th}>Owner</th>
              <th style={au.th}>Vault</th>
              <th style={au.th}>Last rotated</th>
              <th style={au.th}>Rotate every</th>
              <th style={au.th}>Expires in</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Accesses (30d)</th>
              <th style={au.th}>Scopes</th>
              <th style={au.th}>Status</th>
              <th style={au.th}></th>
            </tr>
          </thead>
          <tbody>
            {rows.map(s => {
              const ss = statusStyle(s.status);
              return (
                <tr key={s.id}>
                  <td style={{ ...au.td, fontFamily: Tops.font.mono, fontWeight: 700, color: au.teal }}>{s.id}</td>
                  <td style={{ ...au.td, fontFamily: Tops.font.mono, color: Tops.color.text.primary, fontWeight: 600, fontSize: '11px' }}>{s.name}</td>
                  <td style={au.td}><OBadge color={au.cobalt} bg={au.cobaltBg}>{s.category}</OBadge></td>
                  <td style={{ ...au.td, color: Tops.color.text.secondary, fontSize: '11px' }}>{s.owner}</td>
                  <td style={{ ...au.td, color: Tops.color.text.tertiary, fontSize: '11px' }}>{s.vault}</td>
                  <td style={{ ...au.td, fontFamily: Tops.font.mono, fontSize: '11px', color: Tops.color.text.tertiary }}>{s.lastRotated}</td>
                  <td style={{ ...au.td, fontFamily: Tops.font.mono, fontSize: '11px', color: Tops.color.text.secondary }}>{s.rotateEvery}d</td>
                  <td style={{ ...au.td, fontFamily: Tops.font.mono, fontSize: '11px', color: s.expiresIn < 0 ? au.crimson : s.expiresIn < 30 ? au.amber : au.emerald, fontWeight: 700 }}>
                    {s.expiresIn < 0 ? `${Math.abs(s.expiresIn)}d ago` : `${s.expiresIn}d`}
                  </td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.primary }}>{s.accesses30d.toLocaleString()}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', gap: '3px', flexWrap: 'wrap' }}>
                      {s.scopes.slice(0, 2).map(sc => <OBadge key={sc} color={au.slate} bg={au.slateBg} mono>{sc}</OBadge>)}
                      {s.scopes.length > 2 && <span style={{ fontSize: '10px', color: Tops.color.text.tertiary }}>+{s.scopes.length - 2}</span>}
                    </div>
                  </td>
                  <td style={au.td}><OBadge color={ss.color} bg={ss.bg}>{s.status}</OBadge></td>
                  <td style={au.td}>
                    {s.status !== 'Healthy' && <button style={{ ...au.btnGhost, color: au.teal }}>Rotate now</button>}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── COST ─────────────────────────────────────────────────────────────────────
function OpsCost({ data }) {
  const au = window.__au;
  const k = data.costKpis;
  const byWf = data.costByWorkflow;
  const byTenant = data.costByTenant;
  const licenses = data.licenses;

  const maxWfMtd = Math.max(...byWf.map(w => w.mtd));
  const maxTenMtd = Math.max(...byTenant.map(t => t.mtd));

  const trendColor = (t) => t.startsWith('+') ? au.amber : t.startsWith('-') ? au.emerald : Tops.color.text.tertiary;

  const licStatus = (s) => {
    if (s === 'Near Cap')  return { bg: au.amberBg, color: au.amber };
    if (s === 'At Cap')    return { bg: au.crimsonBg, color: au.crimson };
    return { bg: au.emeraldBg, color: au.emerald };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.emerald}`, background: au.emeraldBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.emerald, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Cost & chargeback — ${(k.ytd / 1000).toFixed(0)}K YTD · projected {k.projectedEoyPct}% of budget</div>
          <div style={{ fontSize: '11px', color: Tops.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Per-workflow, per-tenant attribution. ${(k.savingsYtd / 1000).toFixed(0)}K saved YTD via automation vs manual equivalent. Chargeback recovered ${(k.chargebackRecovered / 1000).toFixed(0)}K.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>MTD spend</span><span style={au.statValue}>${(k.mtd / 1000).toFixed(1)}K</span></div>
        <div style={au.stat}><span style={au.statLabel}>YTD spend</span><span style={au.statValue}>${(k.ytd / 1000).toFixed(0)}K</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg run cost</span><span style={au.statValue}>${k.avgRunCost.toFixed(2)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Projected EoY</span><span style={{ ...au.statValue, color: k.projectedEoyPct > 100 ? au.amber : au.emerald }}>{k.projectedEoyPct}%</span><span style={{ ...au.statDelta, color: Tops.color.text.tertiary }}>vs budget</span></div>
        <div style={au.stat}><span style={au.statLabel}>Savings vs manual</span><span style={{ ...au.statValue, color: au.emerald }}>${(k.savingsYtd / 1000).toFixed(0)}K</span></div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Cost by workflow</span>
            <button style={au.btnSecondary}>Export</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>Workflow</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Runs</th>
                <th style={au.th}>MTD</th>
                <th style={{ ...au.th, textAlign: 'right' }}>YTD</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Avg / run</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Trend</th>
              </tr>
            </thead>
            <tbody>
              {byWf.map(w => (
                <tr key={w.workflow}>
                  <td style={{ ...au.td, color: Tops.color.text.primary, fontWeight: 600 }}>{w.workflow}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.secondary }}>{w.runs}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '80px', height: '6px', background: Tops.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${(w.mtd / maxWfMtd) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${au.emerald}, ${au.teal})` }} />
                      </div>
                      <span style={{ fontFamily: Tops.font.mono, fontWeight: 700, fontSize: '11px', color: Tops.color.text.primary }}>${(w.mtd / 1000).toFixed(1)}K</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.primary, fontWeight: 700 }}>${(w.ytd / 1000).toFixed(0)}K</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.secondary }}>${w.avgRunCost.toFixed(2)}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: trendColor(w.trend), fontWeight: 700 }}>{w.trend}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>
            <span>Chargeback by tenant</span>
            <button style={au.btnSecondary}>Export</button>
          </div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>Tenant</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Runs</th>
                <th style={au.th}>MTD</th>
                <th style={{ ...au.th, textAlign: 'right' }}>YTD</th>
                <th style={au.th}>Model</th>
              </tr>
            </thead>
            <tbody>
              {byTenant.map(t => (
                <tr key={t.tenant}>
                  <td style={{ ...au.td, color: Tops.color.text.primary, fontWeight: 600 }}>{t.tenant}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.secondary }}>{t.runs}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '60px', height: '6px', background: Tops.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${(t.mtd / maxTenMtd) * 100}%`, height: '100%', background: au.cobalt }} />
                      </div>
                      <span style={{ fontFamily: Tops.font.mono, fontWeight: 700, fontSize: '11px', color: Tops.color.text.primary }}>${(t.mtd / 1000).toFixed(1)}K</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.primary, fontWeight: 700 }}>${(t.ytd / 1000).toFixed(0)}K</td>
                  <td style={au.td}><OBadge color={t.chargeback === 'Enabled' ? au.emerald : au.slate} bg={t.chargeback === 'Enabled' ? au.emeraldBg : au.slateBg}>{t.chargeback}</OBadge></td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>License utilization — {licenses.length} vendors</span>
          <button style={au.btnSecondary}>Manage contracts</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Vendor</th>
              <th style={au.th}>Product</th>
              <th style={au.th}>Commit</th>
              <th style={au.th}>Utilization</th>
              <th style={{ ...au.th, textAlign: 'right' }}>MTD spend</th>
              <th style={{ ...au.th, textAlign: 'right' }}>MTD cap</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {licenses.map(l => {
              const ls = licStatus(l.status);
              const color = l.utilizationPct >= 90 ? au.crimson : l.utilizationPct >= 80 ? au.amber : au.emerald;
              return (
                <tr key={l.vendor + l.product}>
                  <td style={{ ...au.td, color: Tops.color.text.primary, fontWeight: 600 }}>{l.vendor}</td>
                  <td style={{ ...au.td, color: Tops.color.text.secondary, fontSize: '11px' }}>{l.product}</td>
                  <td style={{ ...au.td, fontFamily: Tops.font.mono, color: Tops.color.text.tertiary, fontSize: '11px' }}>{l.commit}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '100px', height: '6px', background: Tops.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${l.utilizationPct}%`, height: '100%', background: color }} />
                      </div>
                      <span style={{ fontFamily: Tops.font.mono, fontWeight: 700, fontSize: '11px', color }}>{l.utilizationPct}%</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.primary, fontWeight: 700 }}>${(l.mtdSpend / 1000).toFixed(1)}K</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tops.font.mono, color: Tops.color.text.tertiary }}>${(l.capMtd / 1000).toFixed(1)}K</td>
                  <td style={au.td}><OBadge color={ls.color} bg={ls.bg}>{l.status}</OBadge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── HITL INBOX ───────────────────────────────────────────────────────────────
function OpsHITL({ data }) {
  const au = window.__au;
  const rows = data.hitlInbox;
  const [selected, setSelected] = useOpsState({});
  const toggle = (id) => setSelected(s => ({ ...s, [id]: !s[id] }));
  const selCount = Object.values(selected).filter(Boolean).length;
  const overdue = rows.filter(r => r.status === 'Overdue').length;

  const slaStyle = (min) => {
    if (min < 0) return { color: au.crimson, label: `${Math.abs(min)}m OVERDUE` };
    if (min < 60) return { color: au.crimson, label: `${min}m left` };
    if (min < 480) return { color: au.amber, label: `${Math.round(min / 60)}h left` };
    return { color: au.emerald, label: `${Math.round(min / 60)}h left` };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.amber}`, background: au.amberBg }}>
        <div style={{ padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700, color: au.amber, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Human-in-loop inbox — {rows.length} waiting · {overdue} overdue</div>
            <div style={{ fontSize: '11px', color: Tops.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
              Approval tasks gating workflow progress. Batch actions, SLA timers, auto-escalation on breach.
            </div>
          </div>
          {selCount > 0 && (
            <div style={{ display: 'flex', gap: '6px' }}>
              <button style={{ ...au.btnPrimary, background: au.emerald }}>ok Approve {selCount}</button>
              <button style={{ ...au.btnSecondary, color: au.crimson }}>x Reject {selCount}</button>
              <button style={au.btnSecondary}>Reassign</button>
            </div>
          )}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Waiting</span><span style={au.statValue}>{rows.filter(r => r.status === 'Waiting').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Overdue</span><span style={{ ...au.statValue, color: au.crimson }}>{overdue}</span></div>
        <div style={au.stat}><span style={au.statLabel}>P0 priority</span><span style={{ ...au.statValue, color: au.crimson }}>{rows.filter(r => r.priority === 'P0').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Batched actions</span><span style={au.statValue}>{rows.reduce((s, r) => s + (r.batch > 1 ? r.batch : 0), 0)}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Inbox — {rows.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={au.btnSecondary}>Delegate all to me</button>
            <button style={au.btnSecondary}>Filter: waiting on me</button>
          </div>
        </div>
        <div>
          {rows.map(h => {
            const sla = slaStyle(h.slaLeftMin);
            const prio = au.priorityColor(h.priority);
            const isOverdue = h.status === 'Overdue';
            return (
              <div key={h.id} style={{ padding: '12px 16px', borderBottom: `1px solid ${Tops.color.border.light}`, background: selected[h.id] ? au.limeBg : isOverdue ? au.crimsonBg : 'transparent', display: 'grid', gridTemplateColumns: '28px 100px 1fr 120px 140px 140px', gap: '12px', alignItems: 'center' }}>
                <input type="checkbox" checked={!!selected[h.id]} onChange={() => toggle(h.id)} />
                <div>
                  <div style={{ fontFamily: Tops.font.mono, fontWeight: 700, color: au.amber, fontSize: '11px' }}>{h.id}</div>
                  <OBadge color={prio.color} bg={prio.bg}>{h.priority}</OBadge>
                </div>
                <div>
                  <div style={{ fontSize: '12px', fontWeight: 600, color: Tops.color.text.primary }}>{h.title}</div>
                  <div style={{ fontSize: '10px', color: Tops.color.text.tertiary, marginTop: '2px' }}>
                    {h.workflow} · <span style={{ fontFamily: Tops.font.mono, color: au.lime }}>{h.runId}</span> · created {h.createdAt}
                    {h.batch > 1 && <span style={{ marginLeft: '8px', padding: '1px 6px', background: au.cobaltBg, color: au.cobalt, borderRadius: '8px', fontWeight: 700 }}>BATCH × {h.batch}</span>}
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: '10px', color: Tops.color.text.tertiary, textTransform: 'uppercase', fontWeight: 700 }}>Waiting on</div>
                  <div style={{ fontSize: '12px', color: Tops.color.text.primary, fontWeight: 600 }}>{h.waitingFor}</div>
                </div>
                <div>
                  <div style={{ fontSize: '10px', color: Tops.color.text.tertiary, textTransform: 'uppercase', fontWeight: 700 }}>SLA</div>
                  <div style={{ fontSize: '12px', color: sla.color, fontWeight: 700, fontFamily: Tops.font.mono }}>{sla.label}</div>
                  <div style={{ fontSize: '10px', color: Tops.color.text.tertiary }}>escalates → <b>{h.escalatesTo}</b></div>
                </div>
                <div style={{ display: 'flex', gap: '4px', justifyContent: 'flex-end' }}>
                  <button style={{ ...au.btnPrimary, background: au.emerald, padding: '4px 10px' }}>ok Approve</button>
                  <button style={{ ...au.btnSecondary, color: au.crimson, padding: '4px 10px' }}><Icons.X size={11}/></button>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ─── ROOT ─────────────────────────────────────────────────────────────────────
function AutoOps({ data }) {
  const au = window.__au;
  const [view, setView] = useOpsState('secrets');
  const renderView = () => {
    switch (view) {
      case 'secrets':   return <OpsSecrets   data={data} />;
      case 'cost':      return <OpsCost      data={data} />;
      case 'hitl':      return <OpsHITL      data={data} />;
      case 'analytics': return <AutoAnalytics data={data} />;
      case 'audit':     return <AutoAudit     data={data} />;
      case 'activity':  return <AutoActivity  data={data} />;
      default:          return <OpsSecrets   data={data} />;
    }
  };
  return (<div><AuSubNav views={OPS_VIEWS} active={view} onChange={setView} accent={au.teal} />{renderView()}</div>);
}

window.AutoOps = AutoOps;
