// AUTOMATION — WORKFLOWS sub-platform (5 tabs: Dashboard · Active Runs · Performance · Designer · Activity)
const { useState: useWspState } = React;
const Twsp = window.ArbiterTokens;

// ── Performance ──────────────────────────────────────────────────────────
function AutoWorkflowsPerformance({ data }) {
  const au = window.__au;

  // Group by category
  const byCat = {};
  data.workflows.forEach(w => {
    if (!byCat[w.category]) byCat[w.category] = { runs: 0, minutes: 0, successSum: 0, count: 0, active: 0 };
    byCat[w.category].runs += w.totalRuns;
    byCat[w.category].minutes += w.avgMinutes * w.totalRuns;
    byCat[w.category].successSum += w.successRate;
    byCat[w.category].count += 1;
    byCat[w.category].active += w.activeRuns;
  });
  const catRows = Object.entries(byCat).map(([c, d]) => ({
    category: c, runs: d.runs, workflows: d.count, active: d.active,
    avgSuccess: d.successSum / d.count,
    avgMin: d.runs > 0 ? d.minutes / d.runs : 0,
  })).sort((a, b) => b.runs - a.runs);

  // Throughput (reuse daily14)
  const daily = data.analytics.daily14;
  const maxDaily = Math.max(...daily.map(d => d.runs));
  const avgDaily = Math.round(daily.reduce((s, d) => s + d.runs, 0) / daily.length);

  // Runtime distribution histogram
  const durBuckets = [
    { label: '< 30 min',   min: 0,    max: 30,   color: au.emerald },
    { label: '30–120 min', min: 30,   max: 120,  color: au.lime },
    { label: '2–6 hrs',    min: 120,  max: 360,  color: au.amber },
    { label: '6+ hrs',     min: 360,  max: 99999,color: au.crimson },
  ].map(b => ({ ...b, count: data.workflows.filter(w => w.avgMinutes >= b.min && w.avgMinutes < b.max).length }));
  const maxBucket = Math.max(...durBuckets.map(b => b.count), 1);

  // Reliability ranking
  const ranked = [...data.workflows].sort((a, b) => b.successRate - a.successRate).slice(0, 6);
  const bottom = [...data.workflows].sort((a, b) => a.successRate - b.successRate).slice(0, 3);

  return (
    <div>
      <AuHero
        accent={au.emerald} bg={au.emeraldBg}
        title="Workflow performance — category analytics"
        description={<>Runtime distribution, reliability ranking, and category throughput. <b style={{ color: au.lime, fontFamily: Twsp.font.mono }}>{avgDaily}</b> runs/day avg · <b style={{ fontFamily: Twsp.font.mono }}>{maxDaily}</b> peak (14d).</>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Runs/day avg</span><span style={{ ...au.statValue, color: au.lime }}>{avgDaily}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Peak (14d)</span><span style={au.statValue}>{maxDaily}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Longest workflow</span><span style={au.statValue}>{Math.max(...data.workflows.map(w => w.avgMinutes))} <span style={{ fontSize: '12px', color: Twsp.color.text.tertiary, fontWeight: 500 }}>min</span></span></div>
        <div style={au.stat}><span style={au.statLabel}>Fastest workflow</span><span style={au.statValue}>{Math.min(...data.workflows.map(w => w.avgMinutes))} <span style={{ fontSize: '12px', color: Twsp.color.text.tertiary, fontWeight: 500 }}>min</span></span></div>
        <div style={au.stat}><span style={au.statLabel}>Failure rate</span><span style={{ ...au.statValue, color: au.amber }}>{(100 - data.kpis.successRatePct).toFixed(1)}%</span></div>
      </div>

      {/* Throughput chart */}
      <div style={au.card}>
        <div style={au.cardH}>
          <span>Workflow throughput — last 14 days</span>
          <span style={{ fontSize: '10px', color: Twsp.color.text.tertiary, fontWeight: 500 }}>avg {avgDaily} / day · peak {maxDaily}</span>
        </div>
        <div style={{ padding: '18px 16px 14px', display: 'flex', gap: '5px', alignItems: 'flex-end', height: '180px' }}>
          {daily.map(d => (
            <div key={d.d} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: '4px' }}>
              <span style={{ fontSize: '10px', color: Twsp.color.text.tertiary, fontFamily: Twsp.font.mono, fontWeight: 600 }}>{d.runs}</span>
              <div style={{ width: '100%', height: '130px', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' }}>
                <div style={{ width: '72%', height: `${(d.runs / maxDaily) * 100}%`, background: `linear-gradient(180deg, ${au.limeLight} 0%, ${au.lime} 100%)`, borderRadius: '3px 3px 0 0' }} />
              </div>
              <span style={{ fontSize: '9px', color: Twsp.color.text.tertiary, fontFamily: Twsp.font.mono }}>{d.d}</span>
            </div>
          ))}
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.2fr 1fr', gap: '14px' }}>
        {/* Category table */}
        <div style={au.card}>
          <div style={au.cardH}>Performance by category</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <thead>
              <tr>
                <th style={au.th}>Category</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Workflows</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Runs YTD</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Active</th>
                <th style={{ ...au.th, textAlign: 'right' }}>Avg min</th>
                <th style={au.th}>Success</th>
              </tr>
            </thead>
            <tbody>
              {catRows.map(c => {
                const rc = c.avgSuccess >= 99 ? au.emerald : c.avgSuccess >= 97 ? au.lime : c.avgSuccess >= 90 ? au.amber : au.crimson;
                return (
                  <tr key={c.category}>
                    <td style={{ ...au.td, fontWeight: 600 }}><span style={{ ...au.tag, background: Twsp.color.bg.secondary, color: Twsp.color.text.secondary }}>{c.category}</span></td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono }}>{c.workflows}</td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono, fontWeight: 700 }}>{au.num(c.runs)}</td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono, color: au.lime, fontWeight: 700 }}>{c.active}</td>
                    <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono, color: Twsp.color.text.tertiary }}>{c.avgMin.toFixed(0)}</td>
                    <td style={au.td}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                        <div style={{ width: '70px', height: '5px', background: Twsp.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                          <div style={{ width: `${c.avgSuccess}%`, height: '100%', background: rc }} />
                        </div>
                        <span style={{ fontFamily: Twsp.font.mono, fontSize: '11px', color: rc, fontWeight: 700 }}>{c.avgSuccess.toFixed(1)}%</span>
                      </div>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>

        {/* Runtime distribution */}
        <div style={au.card}>
          <div style={au.cardH}>Runtime distribution</div>
          <div style={{ padding: '14px 16px' }}>
            {durBuckets.map(b => (
              <div key={b.label} style={{ marginBottom: '10px' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                  <span style={{ fontSize: '11px', fontWeight: 600, color: Twsp.color.text.primary }}>{b.label}</span>
                  <span style={{ fontSize: '11px', fontFamily: Twsp.font.mono, color: b.color, fontWeight: 700 }}>{b.count}</span>
                </div>
                <div style={{ height: '8px', background: Twsp.color.border.light, borderRadius: '4px', overflow: 'hidden' }}>
                  <div style={{ width: `${(b.count / maxBucket) * 100}%`, height: '100%', background: b.color }} />
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* Reliability leaderboard */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: '14px', marginTop: '14px' }}>
        <div style={au.card}>
          <div style={{ ...au.cardH, color: au.emerald }}>ok Most reliable — top 6</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <tbody>
              {ranked.map(w => (
                <tr key={w.id}>
                  <td style={{ ...au.td, fontFamily: Twsp.font.mono, color: au.lime, fontWeight: 700, width: '80px' }}>{w.id}</td>
                  <td style={{ ...au.td, fontFamily: Twsp.font.mono, fontSize: '11px', fontWeight: 600 }}>{w.name}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono, color: au.emerald, fontWeight: 700 }}>{w.successRate}%</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono, color: Twsp.color.text.tertiary, fontSize: '11px' }}>{au.num(w.totalRuns)} runs</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        <div style={au.card}>
          <div style={{ ...au.cardH, color: au.amber }}>! Needs attention — bottom 3</div>
          <table style={{ width: '100%', borderCollapse: 'collapse' }}>
            <tbody>
              {bottom.map(w => (
                <tr key={w.id}>
                  <td style={{ ...au.td, fontFamily: Twsp.font.mono, fontSize: '11px', fontWeight: 600 }}>{w.name}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Twsp.font.mono, color: au.amber, fontWeight: 700 }}>{w.successRate}%</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

// ── Designer (inspect a single workflow) ─────────────────────────────────
function AutoWorkflowsDesigner({ data }) {
  const au = window.__au;
  const [selectedId, setSelectedId] = useWspState(data.workflows[0].id);
  const wf = data.workflows.find(w => w.id === selectedId) || data.workflows[0];

  // Synthetic step names per category (best-effort from description)
  const stepsFor = (w) => {
    if (w.description.includes('→')) {
      return w.description.replace(/\.$/, '').split('→').map(s => s.trim());
    }
    return Array.from({ length: w.steps }, (_, i) => `Step ${i + 1}`);
  };
  const steps = stepsFor(wf);
  const activeRuns = data.workflowRuns.filter(r => r.workflow === wf.name);
  const rateColor = wf.successRate >= 99 ? au.emerald : wf.successRate >= 97 ? au.lime : wf.successRate >= 90 ? au.amber : au.crimson;

  return (
    <div>
      <AuHero
        accent={au.fuchsia} bg={au.fuchsiaBg}
        title={`Workflow designer — ${wf.name}`}
        description={<>Read-only view of step order, owner, category, and runtime stats. For editable canvas with branching, see <b>Authoring → Visual Designer</b>.</>}
      />
      <div style={au.card}>
        <div style={au.cardH}>
          <span>Workflow Designer · {wf.id}</span>
          <select value={selectedId} onChange={e => setSelectedId(e.target.value)}
            style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Twsp.color.border.light}`, borderRadius: '5px', background: Twsp.color.bg.card, color: Twsp.color.text.secondary }}>
            {data.workflows.map(w => <option key={w.id} value={w.id}>{w.name}</option>)}
          </select>
        </div>

        {/* Workflow meta */}
        <div style={{ padding: '16px', borderBottom: `1px solid ${Twsp.color.border.light}`, background: Twsp.color.bg.secondary }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: '8px' }}>
            <div>
              <div style={{ fontSize: '15px', fontWeight: 700, color: Twsp.color.text.primary, fontFamily: Twsp.font.mono, letterSpacing: '-0.01em' }}>{wf.name}</div>
              <div style={{ fontSize: '11px', color: Twsp.color.text.secondary, marginTop: '3px' }}>{wf.description}</div>
            </div>
            <div style={{ display: 'flex', gap: '8px' }}>
              <span style={{ ...au.tag, background: Twsp.color.bg.card, color: Twsp.color.text.secondary, border: `1px solid ${Twsp.color.border.light}` }}>{wf.category}</span>
              <span style={{ ...au.tag, background: au.statusColor(wf.status).bg, color: au.statusColor(wf.status).color }}>{wf.status}</span>
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '10px', marginTop: '12px' }}>
            <div><div style={{ fontSize: '9px', fontWeight: 600, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Steps</div><div style={{ fontSize: '14px', fontWeight: 700, fontFamily: Twsp.font.mono, color: Twsp.color.text.primary }}>{wf.steps}</div></div>
            <div><div style={{ fontSize: '9px', fontWeight: 600, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Active runs</div><div style={{ fontSize: '14px', fontWeight: 700, fontFamily: Twsp.font.mono, color: au.lime }}>{wf.activeRuns}</div></div>
            <div><div style={{ fontSize: '9px', fontWeight: 600, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Total runs</div><div style={{ fontSize: '14px', fontWeight: 700, fontFamily: Twsp.font.mono, color: Twsp.color.text.primary }}>{au.num(wf.totalRuns)}</div></div>
            <div><div style={{ fontSize: '9px', fontWeight: 600, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Success</div><div style={{ fontSize: '14px', fontWeight: 700, fontFamily: Twsp.font.mono, color: rateColor }}>{wf.successRate}%</div></div>
            <div><div style={{ fontSize: '9px', fontWeight: 600, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Avg min</div><div style={{ fontSize: '14px', fontWeight: 700, fontFamily: Twsp.font.mono, color: Twsp.color.text.primary }}>{au.num(wf.avgMinutes)}</div></div>
          </div>
        </div>

        {/* Step pipeline */}
        <div style={{ padding: '18px 16px' }}>
          <div style={{ fontSize: '11px', fontWeight: 700, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em', marginBottom: '12px' }}>Step pipeline</div>
          <div style={{ display: 'flex', gap: '6px', overflowX: 'auto', paddingBottom: '6px' }}>
            {steps.map((s, i) => (
              <div key={i} style={{ flex: 1, minWidth: '120px', position: 'relative' }}>
                <div style={{ padding: '10px 10px', background: Twsp.color.bg.card, border: `1px solid ${Twsp.color.border.light}`, borderRadius: '6px', textAlign: 'center' }}>
                  <div style={{ fontSize: '9px', color: Twsp.color.text.tertiary, fontFamily: Twsp.font.mono, fontWeight: 600, marginBottom: '4px' }}>STEP {i + 1}</div>
                  <div style={{ fontSize: '11px', color: Twsp.color.text.primary, fontWeight: 600, lineHeight: 1.35 }}>{s}</div>
                </div>
                {i < steps.length - 1 && (
                  <div style={{ position: 'absolute', right: '-5px', top: '50%', transform: 'translateY(-50%)', color: Twsp.color.text.tertiary, fontSize: '14px', fontWeight: 500, zIndex: 1 }}>›</div>
                )}
              </div>
            ))}
          </div>
        </div>

        {/* Active runs for this workflow */}
        {activeRuns.length > 0 && (
          <div>
            <div style={{ padding: '12px 16px', borderTop: `1px solid ${Twsp.color.border.light}`, fontSize: '11px', fontWeight: 700, color: Twsp.color.text.tertiary, textTransform: 'uppercase', letterSpacing: '0.06em' }}>Active runs ({activeRuns.length})</div>
            <table style={{ width: '100%', borderCollapse: 'collapse' }}>
              <tbody>
                {activeRuns.map(r => {
                  const ss = au.statusColor(r.status);
                  return (
                    <tr key={r.id}>
                      <td style={{ ...au.td, fontFamily: Twsp.font.mono, color: au.lime, fontWeight: 700 }}>{r.id}</td>
                      <td style={{ ...au.td, fontSize: '11px' }}>{r.matter}</td>
                      <td style={{ ...au.td, fontSize: '11px', color: Twsp.color.text.secondary }}>{r.currentStep}</td>
                      <td style={au.td}>
                        <div style={{ display: 'flex', alignItems: 'center', gap: '6px' }}>
                          <div style={{ width: '80px', height: '5px', background: Twsp.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                            <div style={{ width: `${r.progress}%`, height: '100%', background: au.lime }} />
                          </div>
                          <span style={{ fontFamily: Twsp.font.mono, fontSize: '11px', color: au.lime, fontWeight: 700 }}>{r.progress}%</span>
                        </div>
                      </td>
                      <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{r.status}</span></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>
    </div>
  );
}

// ── Workflows Activity ───────────────────────────────────────────────────
function AutoWorkflowsActivity({ data }) {
  const au = window.__au;
  const wfActivity = data.activity.filter(a => a.action.toLowerCase().includes('workflow') || a.target.toLowerCase().includes('workflow') || a.target.match(/RUN-/));
  const list = wfActivity.length > 0 ? wfActivity : data.activity;
  return (
    <div>
      <AuHero
        accent={au.slate} bg={au.slateBg}
        title="Workflow activity stream"
        description={<>Workflow-related events filtered from the platform activity stream. <b style={{ fontFamily: Twsp.font.mono }}>{list.length}</b> entries.</>}
      />
      <div style={au.card}>
        <div style={au.cardH}><span>Workflow activity — {list.length}</span></div>
        <div>
          {list.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 ${Twsp.color.border.light}`, borderLeft: `3px solid ${sev}`, display: 'grid', gridTemplateColumns: '90px 140px 1fr 1fr', gap: '12px', alignItems: 'center' }}>
                <span style={{ fontFamily: Twsp.font.mono, fontSize: '10px', color: Twsp.color.text.tertiary }}>{a.time}</span>
                <span style={{ fontSize: '11px', fontWeight: 600, color: Twsp.color.text.primary }}>{a.actor}</span>
                <span style={{ fontSize: '11px', color: Twsp.color.text.secondary }}>{a.action}</span>
                <span style={{ fontSize: '11px', color: Twsp.color.text.primary, fontWeight: 500 }}>{a.target}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

// ── Platform entry ───────────────────────────────────────────────────────
function AutoWorkflowsPlatform() {
  const [subTab, setSubTab] = useWspState('dashboard');
  const au = window.__au;
  const data = window.AUTO_DATA;

  const subTabs = [
    { id: 'dashboard',   label: 'Dashboard' },
    { id: 'runs',        label: 'Active Runs' },
    { id: 'performance', label: 'Performance' },
    { id: 'designer',    label: 'Designer' },
    { id: 'editor',      label: 'Visual Editor' },
    { id: 'variants',    label: 'A/B Variants' },
    { id: 'activity',    label: 'Activity' },
  ];

  const renderSub = () => {
    switch (subTab) {
      case 'dashboard':   return <AutoWorkflows            data={data} />;
      case 'runs':        return <AutoRuns                 data={data} />;
      case 'performance': return <AutoWorkflowsPerformance data={data} />;
      case 'designer':    return <AutoWorkflowsDesigner    data={data} />;
      case 'editor':      return <AutoAuthoring            data={data} />;
      case 'variants':    return <AuthVariants             data={data} />;
      case 'activity':    return <AutoWorkflowsActivity    data={data} />;
      default:            return <AutoWorkflows            data={data} />;
    }
  };

  return (
    <div>
      <AuSubNav views={subTabs} active={subTab} onChange={setSubTab} accent={au.lime} />
      {renderSub()}
    </div>
  );
}

window.AutoWorkflowsPerformance = AutoWorkflowsPerformance;
window.AutoWorkflowsDesigner    = AutoWorkflowsDesigner;
window.AutoWorkflowsActivity    = AutoWorkflowsActivity;
window.AutoWorkflowsPlatform    = AutoWorkflowsPlatform;
