// AUTOMATION PLATFORM — Workflows + Workflow Runs tabs
const { useState: useAuWfState, useMemo: useAuWfMemo } = React;
const Tauw = window.ArbiterTokens;

function AutoWorkflows({ data }) {
  const au = window.__au;
  const [categoryFilter, setCategoryFilter] = useAuWfState('All');
  const [search, setSearch] = useAuWfState('');

  const categories = useAuWfMemo(() => ['All', ...new Set(data.workflows.map(w => w.category))], [data]);

  const filtered = data.workflows.filter(w =>
    (categoryFilter === 'All' || w.category === categoryFilter) &&
    (!search || w.name.toLowerCase().includes(search.toLowerCase()) || w.description.toLowerCase().includes(search.toLowerCase()))
  );

  // Runs by category (aggregate)
  const byCategory = {};
  data.workflows.forEach(w => {
    if (!byCategory[w.category]) byCategory[w.category] = { runs: 0, active: 0, workflows: 0, avgSuccess: 0 };
    byCategory[w.category].runs += w.totalRuns;
    byCategory[w.category].active += w.activeRuns;
    byCategory[w.category].workflows += 1;
    byCategory[w.category].avgSuccess += w.successRate;
  });
  const categoryData = Object.entries(byCategory).map(([cat, d]) => ({
    category: cat, runs: d.runs, active: d.active, workflows: d.workflows,
    avgSuccess: d.avgSuccess / d.workflows,
  })).sort((a, b) => b.runs - a.runs);
  const totalRuns = categoryData.reduce((s, c) => s + c.runs, 0);

  // Top workflows by volume
  const topByVolume = [...data.workflows].sort((a, b) => b.totalRuns - a.totalRuns).slice(0, 8);
  const maxVolume = Math.max(...topByVolume.map(w => w.totalRuns));

  // Avg duration by workflow (top 8 longest)
  const longest = [...data.workflows].sort((a, b) => b.avgMinutes - a.avgMinutes).slice(0, 8);
  const maxMinutes = Math.max(...longest.map(w => w.avgMinutes));

  // Active runs mini-gantt
  const activeRunsList = [...data.workflowRuns].sort((a, b) => b.progress - a.progress);

  // Palette cycle for categories
  const catColors = [au.lime, au.cobalt, au.violet, au.teal, au.amber, au.crimson, au.fuchsia, au.emerald, au.slate, au.orange];

  return (
    <div>
      <AuHero
        accent={au.cobalt} bg={au.cobaltBg}
        title={`Workflows — ${data.workflows.length} defined`}
        description={<>
          Multi-step processes executed end-to-end. Group by category, search by name. <b style={{ fontFamily: Tauw.font.mono }}>{data.workflows.reduce((s, w) => s + w.activeRuns, 0)}</b> active runs across <b>{categories.length - 1}</b> domains at <b style={{ color: au.emerald, fontFamily: Tauw.font.mono }}>{(data.workflows.reduce((s, w) => s + w.successRate, 0) / data.workflows.length).toFixed(1)}%</b> average success.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Workflows</span><span style={au.statValue}>{data.workflows.length}</span><span style={{ ...au.statDelta, color: Tauw.color.text.tertiary }}>{data.workflows.filter(w => w.status === 'Active').length} active</span></div>
        <div style={au.stat}><span style={au.statLabel}>Active runs</span><span style={{ ...au.statValue, color: au.lime }}>{data.workflows.reduce((s, w) => s + w.activeRuns, 0)}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Total runs YTD</span><span style={au.statValue}>{au.num(data.workflows.reduce((s, w) => s + w.totalRuns, 0))}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg success rate</span><span style={{ ...au.statValue, color: au.emerald }}>{(data.workflows.reduce((s, w) => s + w.successRate, 0) / data.workflows.length).toFixed(1)}%</span></div>
        <div style={au.stat}><span style={au.statLabel}>Categories</span><span style={au.statValue}>{categories.length - 1}</span><span style={{ ...au.statDelta, color: Tauw.color.text.tertiary }}>domain coverage</span></div>
      </div>

      {/* Row 1: Category breakdown + Top by volume */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>Runs by category — YTD</div>
          <div style={{ padding: '14px 16px' }}>
            <div style={{ display: 'flex', height: '14px', borderRadius: '4px', overflow: 'hidden', marginBottom: '12px' }}>
              {categoryData.map((c, i) => (
                <div key={c.category} title={`${c.category}: ${c.runs}`} style={{ width: `${(c.runs / totalRuns) * 100}%`, background: catColors[i % catColors.length] }} />
              ))}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr', gap: '5px' }}>
              {categoryData.map((c, i) => (
                <div key={c.category} style={{ display: 'flex', alignItems: 'center', gap: '8px', fontSize: '11px' }}>
                  <span style={{ width: '10px', height: '10px', borderRadius: '2px', background: catColors[i % catColors.length], flexShrink: 0 }} />
                  <span style={{ color: Tauw.color.text.primary, fontWeight: 600 }}>{c.category}</span>
                  <span style={{ color: Tauw.color.text.tertiary, fontFamily: Tauw.font.mono, marginLeft: 'auto' }}>
                    {au.num(c.runs)} <span style={{ color: c.avgSuccess >= 99 ? au.emerald : c.avgSuccess >= 95 ? au.lime : au.amber, fontWeight: 700 }}>· {c.avgSuccess.toFixed(1)}%</span>
                  </span>
                </div>
              ))}
            </div>
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>Top workflows by volume — YTD</div>
          <div style={{ padding: '14px 16px' }}>
            {topByVolume.map(w => {
              const rateColor = w.successRate >= 99 ? au.emerald : w.successRate >= 97 ? au.lime : w.successRate >= 90 ? au.amber : au.crimson;
              return (
                <div key={w.id} style={{ marginBottom: '10px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontFamily: Tauw.font.mono, fontWeight: 600, color: Tauw.color.text.primary }}>{w.name}</span>
                    <span style={{ fontSize: '11px', fontFamily: Tauw.font.mono }}>
                      <span style={{ color: Tauw.color.text.primary, fontWeight: 700 }}>{au.num(w.totalRuns)}</span>
                      <span style={{ color: rateColor, fontWeight: 700 }}> · {w.successRate}%</span>
                    </span>
                  </div>
                  <div style={{ height: '6px', background: Tauw.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(w.totalRuns / maxVolume) * 100}%`, height: '100%', background: `linear-gradient(90deg, ${au.limeLight} 0%, ${au.lime} 100%)` }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      {/* Row 2: Duration + Active runs */}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1.3fr', gap: '14px', marginBottom: '14px' }}>
        <div style={au.card}>
          <div style={au.cardH}>
            <span>Avg duration (min)</span>
            <span style={{ fontSize: '10px', color: Tauw.color.text.tertiary, fontWeight: 500 }}>top 8 longest</span>
          </div>
          <div style={{ padding: '14px 16px' }}>
            {longest.map(w => {
              const durColor = w.avgMinutes > 400 ? au.crimson : w.avgMinutes > 100 ? au.amber : au.lime;
              return (
                <div key={w.id} style={{ marginBottom: '9px' }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontFamily: Tauw.font.mono, fontWeight: 600, color: Tauw.color.text.primary }}>{w.name}</span>
                    <span style={{ fontSize: '11px', fontFamily: Tauw.font.mono, color: durColor, fontWeight: 700 }}>{au.num(w.avgMinutes)}m</span>
                  </div>
                  <div style={{ height: '5px', background: Tauw.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${(w.avgMinutes / maxMinutes) * 100}%`, height: '100%', background: durColor }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <div style={au.card}>
          <div style={au.cardH}>
            <span>Active runs in flight · {activeRunsList.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>
            {activeRunsList.map(r => {
              const ss = au.statusColor(r.status);
              const progColor = r.status === 'Blocked' ? au.crimson : r.status === 'Waiting' ? au.amber : au.lime;
              return (
                <div key={r.id} style={{ padding: '9px 16px', borderBottom: `1px solid ${Tauw.color.border.light}` }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '3px' }}>
                    <span style={{ fontSize: '11px', fontFamily: Tauw.font.mono, fontWeight: 600, color: Tauw.color.text.primary }}>{r.workflow}</span>
                    <div style={{ display: 'flex', gap: '6px', alignItems: 'center' }}>
                      <span style={{ ...au.tag, background: ss.bg, color: ss.color, fontSize: '9px' }}>{r.status}</span>
                      <span style={{ fontFamily: Tauw.font.mono, fontSize: '11px', color: progColor, fontWeight: 700, minWidth: '32px', textAlign: 'right' }}>{r.progress}%</span>
                    </div>
                  </div>
                  <div style={{ fontSize: '10px', color: Tauw.color.text.tertiary, marginBottom: '4px' }}>{r.matter} · {r.currentStep}</div>
                  <div style={{ height: '5px', background: Tauw.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                    <div style={{ width: `${r.progress}%`, height: '100%', background: progColor }} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Workflow library — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search name / description…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tauw.color.border.light}`, borderRadius: '5px', background: Tauw.color.bg.card, color: Tauw.color.text.primary, minWidth: '240px', fontFamily: Tauw.font.family }} />
            <select value={categoryFilter} onChange={e => setCategoryFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tauw.color.border.light}`, borderRadius: '5px', background: Tauw.color.bg.card, color: Tauw.color.text.secondary }}>
              {categories.map(c => <option key={c} value={c}>Category: {c}</option>)}
            </select>
            <button style={au.btnPrimary}>+ New workflow</button>
          </div>
        </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}>Category</th>
              <th style={au.th}>Owner</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Steps</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Active</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Total YTD</th>
              <th style={au.th}>Success</th>
              <th style={{ ...au.th, textAlign: 'right' }}>Avg min</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(w => {
              const ss = au.statusColor(w.status);
              const rateColor = w.successRate >= 99 ? au.emerald : w.successRate >= 95 ? au.lime : w.successRate >= 90 ? au.amber : au.crimson;
              return (
                <tr key={w.id}>
                  <td style={{ ...au.td, fontFamily: Tauw.font.mono, color: au.lime, fontWeight: 700 }}>{w.id}</td>
                  <td style={{ ...au.td, maxWidth: '420px' }}>
                    <div style={{ fontWeight: 600, color: Tauw.color.text.primary, fontFamily: Tauw.font.mono, fontSize: '11px' }}>{w.name}</div>
                    <div style={{ fontSize: '11px', color: Tauw.color.text.tertiary, marginTop: '3px', lineHeight: 1.4 }}>{w.description}</div>
                  </td>
                  <td style={au.td}><span style={{ ...au.tag, background: au.limeBg, color: au.limeDeep }}>{w.category}</span></td>
                  <td style={{ ...au.td, fontSize: '11px', color: Tauw.color.text.secondary }}>{w.owner}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauw.font.mono, color: Tauw.color.text.primary, fontWeight: 600 }}>{w.steps}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauw.font.mono, color: au.lime, fontWeight: 700 }}>{w.activeRuns}</td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauw.font.mono, color: Tauw.color.text.primary }}>{au.num(w.totalRuns)}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '80px', height: '5px', background: Tauw.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${w.successRate}%`, height: '100%', background: rateColor }} />
                      </div>
                      <span style={{ fontFamily: Tauw.font.mono, fontSize: '11px', color: rateColor, fontWeight: 700 }}>{w.successRate}%</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, textAlign: 'right', fontFamily: Tauw.font.mono, fontSize: '11px', color: Tauw.color.text.tertiary }}>{w.avgMinutes}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{w.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function AutoRuns({ data }) {
  const au = window.__au;
  const [statusFilter, setStatusFilter] = useAuWfState('All');
  const [search, setSearch] = useAuWfState('');

  const statuses = useAuWfMemo(() => ['All', ...new Set(data.workflowRuns.map(r => r.status))], [data]);

  const filtered = data.workflowRuns.filter(r =>
    (statusFilter === 'All' || r.status === statusFilter) &&
    (!search || r.workflow.toLowerCase().includes(search.toLowerCase()) || r.matter.toLowerCase().includes(search.toLowerCase()))
  );

  return (
    <div>
      <AuHero
        accent={au.lime} bg={au.limeBg}
        title={`Workflow runs — ${data.workflowRuns.length} in flight`}
        description={<>
          Live run monitor with step progress and assigned operator. Filter by status, search by workflow or matter. <b style={{ color: au.lime, fontFamily: Tauw.font.mono }}>{data.workflowRuns.filter(r => r.status === 'Running').length}</b> running · <b style={{ color: au.amber, fontFamily: Tauw.font.mono }}>{data.workflowRuns.filter(r => r.status === 'Waiting').length}</b> waiting · <b style={{ color: au.crimson, fontFamily: Tauw.font.mono }}>{data.workflowRuns.filter(r => r.status === 'Blocked').length}</b> blocked.
        </>}
      />
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: '12px', marginBottom: '16px' }}>
        <div style={au.stat}><span style={au.statLabel}>Active runs</span><span style={au.statValue}>{filtered.length}</span><span style={{ ...au.statDelta, color: Tauw.color.text.tertiary }}>of {data.workflowRuns.length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Running</span><span style={{ ...au.statValue, color: au.lime }}>{data.workflowRuns.filter(r => r.status === 'Running').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Waiting</span><span style={{ ...au.statValue, color: au.amber }}>{data.workflowRuns.filter(r => r.status === 'Waiting').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Blocked</span><span style={{ ...au.statValue, color: au.crimson }}>{data.workflowRuns.filter(r => r.status === 'Blocked').length}</span></div>
        <div style={au.stat}><span style={au.statLabel}>Avg progress</span><span style={au.statValue}>{Math.round(data.workflowRuns.reduce((s, r) => s + r.progress, 0) / data.workflowRuns.length)}%</span></div>
      </div>

      <div style={au.card}>
        <div style={au.cardH}>
          <span>Active runs — {filtered.length}</span>
          <div style={{ display: 'flex', gap: '6px' }}>
            <input value={search} onChange={e => setSearch(e.target.value)} placeholder="Search workflow / matter…"
              style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tauw.color.border.light}`, borderRadius: '5px', background: Tauw.color.bg.card, color: Tauw.color.text.primary, minWidth: '220px', fontFamily: Tauw.font.family }} />
            <select value={statusFilter} onChange={e => setStatusFilter(e.target.value)} style={{ padding: '3px 8px', fontSize: '11px', border: `1px solid ${Tauw.color.border.light}`, borderRadius: '5px', background: Tauw.color.bg.card, color: Tauw.color.text.secondary }}>
              {statuses.map(s => <option key={s} value={s}>Status: {s}</option>)}
            </select>
            <button style={au.btnSecondary}>↻ Refresh</button>
          </div>
        </div>
        <table style={{ width: '100%', borderCollapse: 'collapse' }}>
          <thead>
            <tr>
              <th style={au.th}>Run ID</th>
              <th style={au.th}>Workflow</th>
              <th style={au.th}>Matter</th>
              <th style={au.th}>Started by</th>
              <th style={au.th}>Started</th>
              <th style={au.th}>Current step</th>
              <th style={au.th}>Progress</th>
              <th style={au.th}>Expected end</th>
              <th style={au.th}>Status</th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(r => {
              const ss = au.statusColor(r.status);
              const progColor = r.status === 'Blocked' ? au.crimson : r.status === 'Waiting' ? au.amber : au.lime;
              return (
                <tr key={r.id}>
                  <td style={{ ...au.td, fontFamily: Tauw.font.mono, color: au.lime, fontWeight: 700 }}>{r.id}</td>
                  <td style={{ ...au.td, fontFamily: Tauw.font.mono, fontSize: '11px', color: Tauw.color.text.primary, fontWeight: 600 }}>{r.workflow}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Tauw.color.text.secondary, maxWidth: '180px' }}>{r.matter}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Tauw.color.text.secondary }}>{r.startedBy}</td>
                  <td style={{ ...au.td, fontFamily: Tauw.font.mono, fontSize: '10px', color: Tauw.color.text.tertiary }}>{r.startedAt}</td>
                  <td style={{ ...au.td, fontSize: '11px', color: Tauw.color.text.primary }}>{r.currentStep}</td>
                  <td style={au.td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                      <div style={{ width: '100px', height: '6px', background: Tauw.color.border.light, borderRadius: '3px', overflow: 'hidden' }}>
                        <div style={{ width: `${r.progress}%`, height: '100%', background: progColor }} />
                      </div>
                      <span style={{ fontFamily: Tauw.font.mono, fontSize: '11px', color: progColor, fontWeight: 700 }}>{r.progress}%</span>
                    </div>
                  </td>
                  <td style={{ ...au.td, fontFamily: Tauw.font.mono, fontSize: '10px', color: Tauw.color.text.tertiary }}>{r.expectedEnd}</td>
                  <td style={au.td}><span style={{ ...au.tag, background: ss.bg, color: ss.color }}>{r.status}</span></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </div>
  );
}

window.AutoWorkflows = AutoWorkflows;
window.AutoRuns      = AutoRuns;
