// AUTOMATION PLATFORM — Reliability sub-platform
// Views: SLA · DLQ · Traces · Scheduler · Run Controls · Dependency Graph
const { useState: useRelState } = React;
const Trel = window.ArbiterTokens;

const REL_VIEWS = [
  { id: 'sla',       label: 'SLA / SLO' },
  { id: 'dlq',       label: 'Dead-Letter Queue' },
  { id: 'traces',    label: 'Traces' },
  { id: 'scheduler', label: 'Scheduler' },
  { id: 'runctl',    label: 'Run Controls' },
  { id: 'graph',     label: 'Dependency Graph' },
];

function RBadge({ 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 ? Trel.font.mono : Trel.font.family }}>{children}</span>;
}

// ─── SLA ──────────────────────────────────────────────────────────────────────
function RelSLA({ data }) {
  const au = window.__au;
  const sla = data.slaTargets;
  const k = data.reliabilityKpis;
  const atRisk = sla.filter(s => s.status === 'At Risk').length;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.lime}`, background: au.limeBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.limeDeep, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ SLA / SLO — {k.slaTargetMet}% attainment · {k.errorBudgetRemainingPct}% error budget</div>
          <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Per-workflow latency + success targets. <b>{atRisk}</b> workflow(s) at risk. MTTR <b>{k.mttrMin}m</b>. {k.slaBreaches30d} breaches in last 30 days.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Targets tracked</span><span style={au.statValue}>{sla.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Attainment</span><span style={{ ...au.statValue, color: au.emerald }}>{k.slaTargetMet}%</span></div>
        <div style={au.stat}><span style={au.statLabel}>Breaches (30d)</span><span style={{ ...au.statValue, color: k.slaBreaches30d > 5 ? au.amber : au.emerald }}>{k.slaBreaches30d}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Error budget</span><span style={{ ...au.statValue, color: au.lime }}>{k.errorBudgetRemainingPct}%</span><span style={{ ...au.statDelta, color: Trel.color.text.tertiary }}>remaining</span></div>
        <div style={au.stat}><span style={au.statLabel}>MTTR</span><span style={au.statValue}>{k.mttrMin}m</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>SLO targets — per workflow</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={au.btnSecondary}>Export SLO report</button>
            <button style={au.btnPrimary}>+ New target</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>ID</th>
              <th style={au.th}>Workflow</th>
              <th style={au.th}>Target</th>
              <th style={au.th}>Actual p95</th>
              <th style={au.th}>Attainment</th>
              <th style={au.th}>Error budget</th>
              <th style={au.th}>Breaches (30d)</th>
              <th style={au.th}>Owner</th>
              <th style={au.th}>Priority</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {sla.map(s => {
              const st = au.statusColor(s.status === 'Healthy' ? 'Succeeded' : 'Paused');
              const prio = au.priorityColor(s.priority);
              const budgetColor = s.errorBudgetPct >= 60 ? au.emerald : s.errorBudgetPct >= 25 ? au.amber : au.crimson;
              return (
                <tr key={s.id}>
                  <td style={{ ...au.td, fontFamily: Trel.font.mono, fontWeight: 700, color: au.limeDeep }}>{s.id}</td>
                  <td style={{ ...au.td, fontWeight: 600, color: Trel.color.text.primary }}>{s.workflow}</td>
                  <td style={{ ...au.td, fontFamily: Trel.font.mono, color: Trel.color.text.secondary, fontSize: '11px' }}>{s.target}</td>
                  <td style={{ ...au.td, fontFamily: Trel.font.mono, fontWeight: 700, color: Trel.color.text.primary }}>{s.actualP95}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '60px', height: '6px', background: Trel.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${s.attainmentPct}%`, height: '100%', background: s.attainmentPct >= 99 ? au.emerald : s.attainmentPct >= 95 ? au.amber : au.crimson }} />
                      </div>
                      <span style={{ fontSize: '11px', fontFamily: Trel.font.mono, fontWeight: 700, color: s.attainmentPct >= 99 ? au.emerald : au.amber }}>{s.attainmentPct}%</span>
                    </div>
                  </td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '50px', height: '6px', background: Trel.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${s.errorBudgetPct}%`, height: '100%', background: budgetColor }} />
                      </div>
                      <span style={{ fontSize: '11px', fontFamily: Trel.font.mono, fontWeight: 700, color: budgetColor }}>{s.errorBudgetPct}%</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, textAlign: 'center', fontFamily: Trel.font.mono, fontWeight: 700, color: s.breaches30d > 0 ? au.amber : au.emerald }}>{s.breaches30d}</td>
                  <td style={{ ...au.td, color: Trel.color.text.secondary, fontSize: '11px' }}>{s.owner}</td>
                  <td style={au.td}><RBadge color={prio.color} bg={prio.bg}>{s.priority}</RBadge></td>
                  <td style={au.td}><RBadge color={st.color} bg={st.bg}>{s.status}</RBadge></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── DLQ ──────────────────────────────────────────────────────────────────────
function RelDLQ({ data }) {
  const au = window.__au;
  const k = data.reliabilityKpis;
  const [selected, setSelected] = useRelState({});
  const toggle = (id) => setSelected(s => ({ ...s, [id]: !s[id] }));
  const selCount = Object.values(selected).filter(Boolean).length;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.crimson}`, background: au.crimsonBg }}>
        <div style={{ padding: '12px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: '12px', fontWeight: 700, color: au.crimson, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Dead-letter queue — {k.dlqDepth} poisoned runs</div>
            <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
              Oldest quarantined <b>{k.dlqOldestMinutes}m ago</b>. <b>{k.dlqRedrivenYtd}</b> redriven YTD · <b>{k.dlqDiscardedYtd}</b> discarded after categorization.
            </div>
          </div>
          {selCount > 0 && (
            <div style={{ display: 'flex', gap: '6px' }}>
              <button style={{ ...au.btnPrimary, background: au.lime }}>↻ Redrive {selCount}</button>
              <button style={au.btnSecondary}>x Discard {selCount}</button>
            </div>
          )}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Queue depth</span><span style={{ ...au.statValue, color: au.crimson }}>{k.dlqDepth}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Oldest</span><span style={au.statValue}>{k.dlqOldestMinutes}m</span></div>
        <div style={au.stat}><span style={au.statLabel}>Redriven YTD</span><span style={{ ...au.statValue, color: au.emerald }}>{k.dlqRedrivenYtd}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Discarded YTD</span><span style={au.statValue}>{k.dlqDiscardedYtd}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Poisoned runs — {data.dlq.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <button style={au.btnSecondary}>Group by error code</button>
            <button style={au.btnSecondary}>Export forensics</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={{ ...au.th, width: '32px' }}></th>
              <th style={au.th}>DLQ ID</th>
              <th style={au.th}>Run</th>
              <th style={au.th}>Workflow / Step</th>
              <th style={au.th}>Error code</th>
              <th style={au.th}>Message</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Attempts</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Quarantine</th>
              <th style={au.th}>Next retry</th>
              <th style={au.th}>Actions</th>
            </tr>
          </thead>
          <tbody>
            {data.dlq.map(d => (
              <tr key={d.id} style={{ background: selected[d.id] ? au.limeBg : 'transparent' }}>
                <td style={{ ...au.td, textAlign: 'center' }}><input type="checkbox" checked={!!selected[d.id]} onChange={() => toggle(d.id)} /></td>
                <td style={{ ...au.td, fontFamily: Trel.font.mono, fontWeight: 700, color: au.crimson }}>{d.id}</td>
                <td style={{ ...au.td, fontFamily: Trel.font.mono, color: au.lime, fontWeight: 700 }}>{d.runId}</td>
                <td style={{ ...au.td, fontSize: '11px', maxWidth: '220px' }}>
                  <div style={{ color: Trel.color.text.primary, fontWeight: 500 }}>{d.workflow}</div>
                  <div style={{ color: Trel.color.text.tertiary, fontSize: '10px' }}>{d.step}</div>
                </td>
                <td style={au.td}><RBadge color={au.crimson} bg={au.crimsonBg} mono>{d.errorCode}</RBadge></td>
                <td style={{ ...au.td, color: Trel.color.text.secondary, fontSize: '11px', maxWidth: '280px' }}>{d.errorMessage}</td>
                <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, fontWeight: 700, color: d.attempts >= 5 ? au.crimson : au.amber }}>{d.attempts}</td>
                <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, color: Trel.color.text.secondary, fontSize: '11px' }}>{d.quarantineMin < 60 ? `${d.quarantineMin}m` : `${(d.quarantineMin / 60).toFixed(1)}h`}</td>
                <td style={{ ...au.td, fontFamily: Trel.font.mono, fontSize: '11px', color: d.nextRetryAt ? au.amber : Trel.color.text.tertiary }}>{d.nextRetryAt || '—'}</td>
                <td style={au.td}>
                  <div style={{ display: 'flex', gap: '4px' }}>
                    {d.canRedrive && <button style={{ ...au.btnGhost, color: au.lime }}>Redrive</button>}
                    {d.canDiscard && <button style={{ ...au.btnGhost, color: au.crimson }}>Discard</button>}
                  </div>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── TRACES ───────────────────────────────────────────────────────────────────
function RelTraces({ data }) {
  const au = window.__au;
  const k = data.reliabilityKpis;
  const colorMap = { lime: au.lime, cobalt: au.cobalt, violet: au.violet, amber: au.amber, fuchsia: au.fuchsia, teal: au.teal, emerald: au.emerald, crimson: au.crimson };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.cobalt}`, background: au.cobaltBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.cobalt, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Distributed traces — step-level latency waterfalls</div>
          <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Per-run span timeline. Bottlenecks surface as red spans. Click a span to drill into logs and outbound integration calls.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Active traces</span><span style={{ ...au.statValue, color: au.lime }}>{k.activeTraces}</span></div>
        <div style={au.stat}><span style={au.statLabel}>p50</span><span style={au.statValue}>{k.p50Ms}ms</span></div>
        <div style={au.stat}><span style={au.statLabel}>p95</span><span style={{ ...au.statValue, color: au.amber }}>{(k.p95Ms / 1000).toFixed(1)}s</span></div>
        <div style={au.stat}><span style={au.statLabel}>p99</span><span style={{ ...au.statValue, color: au.crimson }}>{(k.p99Ms / 1000).toFixed(1)}s</span></div>
      </div>

      {data.traces.map(t => {
        const max = t.total;
        return (
          <div key={t.id} style={{ ...au.card }}>
            <div style={au.cardH}>
              <span><b style={{ color: au.cobalt, fontFamily: Trel.font.mono }}>{t.id}</b> · {t.workflow} · run <b style={{ color: au.lime, fontFamily: Trel.font.mono }}>{t.runId}</b></span>
              <div style={{ display: 'flex', gap: '8px', alignItems: 'center' }}>
                <span style={{ fontSize: '11px', color: Trel.color.text.tertiary, fontFamily: Trel.font.mono }}>{t.started}</span>
                <RBadge color={t.status === 'Succeeded' ? au.emerald : t.status === 'Failed' ? au.crimson : au.lime} bg={t.status === 'Succeeded' ? au.emeraldBg : t.status === 'Failed' ? au.crimsonBg : au.limeBg}>{t.status}</RBadge>
                <span style={{ fontSize: '11px', color: Trel.color.text.secondary, fontFamily: Trel.font.mono }}>{(t.total / 60).toFixed(1)}m total</span>
              </div>
            </div>
            <div style={{ padding: '14px 16px' }}>
              {t.spans.map((sp, i) => {
                const c = colorMap[sp.color] || au.lime;
                const leftPct = (sp.start / max) * 100;
                const widthPct = (sp.duration / max) * 100;
                const opacity = sp.status === 'queued' ? 0.3 : 1;
                return (
                  <div key={i} style={{ marginBottom: '6px', position: 'relative' }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '11px', marginBottom: '3px' }}>
                      <span style={{ color: Trel.color.text.primary, fontWeight: 500 }}>{i + 1}. {sp.name}</span>
                      <span style={{ fontFamily: Trel.font.mono, color: sp.status === 'slow' ? au.amber : sp.status === 'failed' ? au.crimson : Trel.color.text.secondary }}>
                        {sp.duration}s {sp.status === 'failed' && ' x'}{sp.status === 'slow' && ' !'}
                      </span>
                    </div>
                    <div style={{ height: '14px', background: Trel.color.border.light, borderRadius: '3px', position: 'relative', overflow: 'hidden' }}>
                      <div style={{ position: 'absolute', left: `${leftPct}%`, width: `${widthPct}%`, height: '100%', background: sp.status === 'failed' ? au.crimson : sp.status === 'queued' ? Trel.color.border.strong || '#94a3b8' : `linear-gradient(90deg, ${c}, ${c}dd)`, opacity, borderRadius: '3px' }} />
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── SCHEDULER ────────────────────────────────────────────────────────────────
function RelScheduler({ data }) {
  const au = window.__au;
  const k = data.reliabilityKpis;

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.violet}`, background: au.violetBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.violet, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Scheduler — priority queues with backpressure</div>
          <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Concurrency and throttle controls per queue. Backpressure applied automatically when workers saturate; callers see 429 + retry-after.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: '12px', marginBottom: '14px' }}>
        <div style={au.stat}><span style={au.statLabel}>Queue depth (total)</span><span style={au.statValue}>{k.queueDepth}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Oldest waiting</span><span style={au.statValue}>{k.queueOldestMin}m</span></div>
        <div style={au.stat}><span style={au.statLabel}>Throttled / hr</span><span style={{ ...au.statValue, color: au.amber }}>{k.throttledPerHour}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Backpressure active</span><span style={{ ...au.statValue, color: k.backpressureActive > 0 ? au.amber : au.emerald }}>{k.backpressureActive}</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Queues — {data.queues.length}</span>
          <button style={au.btnPrimary}>+ New queue</button>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Queue</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Concurrency</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Workers</th>
              <th style={au.th}>Utilization</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Depth</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Oldest</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Wait avg</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Throttled/hr</th>
              <th style={au.th}>Backpressure</th>
              <th style={au.th}>Owner</th>
            </tr>
          </thead>
          <tbody>
            {data.queues.map(q => {
              const utilPct = Math.min(100, Math.round((q.depth / Math.max(1, q.concurrency * 2)) * 100));
              return (
                <tr key={q.id}>
                  <td style={{ ...au.td, fontWeight: 700, color: Trel.color.text.primary }}>{q.name} <span style={{ fontFamily: Trel.font.mono, color: Trel.color.text.tertiary, fontWeight: 400, fontSize: '10px' }}>{q.id}</span></td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, color: Trel.color.text.primary, fontWeight: 700 }}>{q.concurrency}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, color: Trel.color.text.secondary }}>{q.workers}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                      <div style={{ width: '80px', height: '6px', background: Trel.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${utilPct}%`, height: '100%', background: utilPct >= 80 ? au.amber : au.lime }} />
                      </div>
                      <span style={{ fontSize: '11px', fontFamily: Trel.font.mono, color: Trel.color.text.secondary }}>{utilPct}%</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, fontWeight: 700, color: q.depth > 10 ? au.amber : Trel.color.text.primary }}>{q.depth}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, color: Trel.color.text.tertiary, fontSize: '11px' }}>{q.oldestMin}m</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, color: Trel.color.text.tertiary, fontSize: '11px' }}>{(q.waitAvgMs / 1000).toFixed(1)}s</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Trel.font.mono, color: q.throttledHr > 0 ? au.amber : Trel.color.text.tertiary }}>{q.throttledHr}</td>
                  <td style={au.td}>{q.backpressure
                    ? <RBadge color={au.amber} bg={au.amberBg}>ACTIVE</RBadge>
                    : <RBadge color={au.emerald} bg={au.emeraldBg}>normal</RBadge>}</td>
                  <td style={{ ...au.td, color: Trel.color.text.tertiary, fontSize: '11px' }}>{q.owner}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

// ─── RUN CONTROLS ─────────────────────────────────────────────────────────────
function RelRunControls({ data }) {
  const au = window.__au;
  const stateStyle = (s) => {
    const m = {
      'Running':  { bg: au.limeBg, color: au.lime },
      'Paused':   { bg: au.amberBg, color: au.amber },
      'Retrying': { bg: au.cobaltBg, color: au.cobalt },
      'Stuck':    { bg: au.crimsonBg, color: au.crimson },
    };
    return m[s] || { bg: Trel.color.bg.secondary, color: Trel.color.text.secondary };
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.teal}`, background: au.tealBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.teal, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Run controls — pause · resume · checkpoint · cancel</div>
          <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Long-running runs can be paused, checkpointed, resumed, or killed. WIP limits bound concurrent work per workflow. Timeout overrides available for stuck runs.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: '14px' }}>
        {data.runControls.map(r => {
          const st = stateStyle(r.state);
          const progressPct = Math.min(100, Math.round((r.elapsedMin / (r.elapsedMin + r.remainingMin || 1)) * 100));
          return (
            <div key={r.id} style={{ ...au.card, borderLeft: `3px solid ${st.color}`, marginBottom: 0 }}>
              <div style={{ ...au.cardH, background: st.bg, color: st.color }}>
                <span><b style={{ fontFamily: Trel.font.mono }}>{r.id}</b> · {r.workflow}</span>
                <RBadge color={st.color} bg="rgba(255,255,255,0.7)">{r.state}</RBadge>
              </div>
              <div style={{ padding: '14px 16px' }}>
                <div style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: '10px', color: Trel.color.text.tertiary, marginBottom: '4px', textTransform: 'uppercase', letterSpacing: '0.06em' }}>
                    <span>Elapsed {r.elapsedMin}m · ETA +{r.remainingMin}m</span>
                    <span style={{ fontFamily: Trel.font.mono, color: st.color, fontWeight: 700 }}>{progressPct}%</span>
                  </div>
                  <div style={{ height: '8px', background: Trel.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                    <div style={{ width: `${progressPct}%`, height: '100%', background: st.color }} />
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: '10px', fontSize: '11px', marginBottom: '10px' }}>
                  <div><span style={{ color: Trel.color.text.tertiary }}>Checkpoints</span><div style={{ color: Trel.color.text.primary, fontWeight: 700, fontFamily: Trel.font.mono }}>{r.checkpointsMade}</div></div>
                  <div><span style={{ color: Trel.color.text.tertiary }}>WIP</span><div style={{ color: Trel.color.text.primary, fontWeight: 700, fontFamily: Trel.font.mono }}>{r.wipInUse} / {r.wipLimit}</div></div>
                  <div><span style={{ color: Trel.color.text.tertiary }}>State</span><div style={{ color: st.color, fontWeight: 700 }}>{r.state}</div></div>
                </div>
                <div style={{ fontSize: '11px', color: Trel.color.text.secondary, paddingTop: '10px', borderTop: `1px solid ${Trel.color.border.light}`, marginBottom: '10px' }}>{r.note}</div>
                <div style={{ display: 'flex', gap: '6px', flexWrap: 'wrap' }}>
                  {r.canPause && <button style={{ ...au.btnSecondary, color: au.amber }}> Pause</button>}
                  {r.state === 'Paused' && <button style={{ ...au.btnPrimary, background: au.lime }}>▶ Resume</button>}
                  {r.canCheckpoint && <button style={au.btnSecondary}>flag Checkpoint</button>}
                  {r.state === 'Stuck' && <button style={au.btnSecondary}>⟳ Override timeout</button>}
                  {r.canCancel && <button style={{ ...au.btnSecondary, color: au.crimson }}>x Cancel</button>}
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ─── DEPENDENCY GRAPH ─────────────────────────────────────────────────────────
function RelGraph({ data }) {
  const au = window.__au;
  const k = data.reliabilityKpis;
  const nodes = data.dependencyNodes;
  const edges = data.dependencyEdges;
  const [highlighted, setHighlighted] = useRelState(null);

  const typeStyle = (t) => {
    if (t === 'workflow')   return { bg: au.limeBg,    color: au.lime,     shape: '10px' };
    if (t === 'trigger')    return { bg: au.violetBg,  color: au.violet,   shape: '50%' };
    if (t === 'event')      return { bg: au.cobaltBg,  color: au.cobalt,   shape: '10px' };
    if (t === 'integration')return { bg: au.tealBg,    color: au.teal,     shape: '10px' };
    return { bg: Trel.color.bg.secondary, color: Trel.color.text.secondary, shape: '10px' };
  };

  const isConnected = (nodeId) => {
    if (!highlighted) return true;
    if (highlighted === nodeId) return true;
    return edges.some(e => (e.from === highlighted && e.to === nodeId) || (e.to === highlighted && e.from === nodeId));
  };

  const impactedBy = (nodeId) => {
    const downstream = new Set();
    const visit = (id) => edges.filter(e => e.from === id).forEach(e => { if (!downstream.has(e.to)) { downstream.add(e.to); visit(e.to); } });
    visit(nodeId);
    return Array.from(downstream).map(id => nodes.find(n => n.id === id)).filter(Boolean);
  };

  return (
    <div>
      <div style={{ ...au.card, borderLeft: `3px solid ${au.fuchsia}`, background: au.fuchsiaBg }}>
        <div style={{ padding: '12px 16px' }}>
          <div style={{ fontSize: '12px', fontWeight: 700, color: au.fuchsia, textTransform: 'uppercase', letterSpacing: '0.08em' }}>◆ Dependency graph — blast-radius analysis</div>
          <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginTop: '4px', lineHeight: 1.55 }}>
            Click any node to highlight connected nodes and see downstream impact — "what breaks if I disable this?" <b>{k.dependencyNodes}</b> nodes · <b>{k.dependencyEdges}</b> edges · <b>{k.criticalPaths}</b> critical paths.
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 280px', gap: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Graph</span>
            <div style={{ display: 'flex', gap: '10px', fontSize: '10px', color: Trel.color.text.secondary }}>
              <span><span style={{ display: 'inline-block', width: '10px', height: '10px', background: au.lime, marginRight: '4px', verticalAlign: 'middle' }} />workflow</span>
              <span><span style={{ display: 'inline-block', width: '10px', height: '10px', background: au.violet, borderRadius: '50%', marginRight: '4px', verticalAlign: 'middle' }} />trigger</span>
              <span><span style={{ display: 'inline-block', width: '10px', height: '10px', background: au.cobalt, marginRight: '4px', verticalAlign: 'middle' }} />event</span>
              <span><span style={{ display: 'inline-block', width: '10px', height: '10px', background: au.teal, marginRight: '4px', verticalAlign: 'middle' }} />integration</span>
            </div>
          </div>
          <div style={{ padding: '16px', position: 'relative', height: '480px', background: 'linear-gradient(180deg, rgba(101,163,13,0.02), transparent)' }}>
            <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{ position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', pointerEvents: 'none' }}>
              {edges.map((e, i) => {
                const a = nodes.find(n => n.id === e.from);
                const b = nodes.find(n => n.id === e.to);
                if (!a || !b) return null;
                const active = !highlighted || highlighted === a.id || highlighted === b.id;
                return (
                  <line key={i} x1={a.x} y1={a.y} x2={b.x} y2={b.y}
                    stroke={active ? au.fuchsia : Trel.color.border.light}
                    strokeWidth="0.25" strokeOpacity={active ? 0.8 : 0.3}
                    vectorEffect="non-scaling-stroke"
                  />
                );
              })}
            </svg>
            {nodes.map(n => {
              const ts = typeStyle(n.type);
              const active = isConnected(n.id);
              const isHi = highlighted === n.id;
              return (
                <div key={n.id} onClick={() => setHighlighted(isHi ? null : n.id)}
                  style={{
                    position: 'absolute', left: `${n.x}%`, top: `${n.y}%`,
                    transform: 'translate(-50%, -50%)',
                    padding: '6px 10px', background: ts.bg, color: ts.color,
                    border: `${isHi ? '2px' : '1px'} solid ${ts.color}`,
                    borderRadius: ts.shape, fontSize: '10px', fontWeight: 700,
                    cursor: 'pointer', whiteSpace: 'nowrap', userSelect: 'none',
                    opacity: active ? 1 : 0.3,
                    transition: 'opacity 0.15s',
                    boxShadow: isHi ? `0 0 0 4px ${ts.color}33` : 'none',
                  }}
                >{n.label}</div>
              );
            })}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Blast-radius</div>
          <div style={{ padding: '12px 16px' }}>
            {highlighted ? (
              <>
                <div style={{ fontSize: '11px', color: Trel.color.text.secondary, marginBottom: '8px' }}>If you disable:</div>
                <div style={{ fontSize: '13px', color: au.fuchsia, fontWeight: 700, fontFamily: Trel.font.family, marginBottom: '14px' }}>{nodes.find(n => n.id === highlighted)?.label}</div>
                <div style={{ fontSize: '10px', color: Trel.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '6px' }}>Downstream impact</div>
                {impactedBy(highlighted).length === 0
                  ? <div style={{ fontSize: '11px', color: au.emerald }}>No downstream nodes.</div>
                  : impactedBy(highlighted).map(n => (
                      <div key={n.id} style={{ padding: '6px 8px', marginBottom: '4px', border: `1px solid ${Trel.color.border.light}`, borderRadius: '4px', fontSize: '11px', background: Trel.color.bg.secondary }}>
                        <div style={{ color: Trel.color.text.primary, fontWeight: 500 }}>{n.label}</div>
                        <div style={{ color: Trel.color.text.tertiary, fontSize: '10px' }}>{n.type} · {n.criticality}</div>
                      </div>
                    ))}
              </>
            ) : (
              <div style={{ fontSize: '11px', color: Trel.color.text.tertiary, lineHeight: 1.65 }}>Click any node to see its downstream impact and connected chain.</div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

// ─── ROOT ─────────────────────────────────────────────────────────────────────
function AutoReliability({ data }) {
  const au = window.__au;
  const [view, setView] = useRelState('sla');
  const renderView = () => {
    switch (view) {
      case 'sla':       return <RelSLA         data={data} />;
      case 'dlq':       return <RelDLQ         data={data} />;
      case 'traces':    return <RelTraces      data={data} />;
      case 'scheduler': return <RelScheduler   data={data} />;
      case 'runctl':    return <RelRunControls data={data} />;
      case 'graph':     return <RelGraph       data={data} />;
      default:          return <RelSLA         data={data} />;
    }
  };
  return (<div><AuSubNav views={REL_VIEWS} active={view} onChange={setView} accent={au.lime} />{renderView()}</div>);
}

window.AutoReliability = AutoReliability;
