// ============================================================
// WORKFLOW CONTROL CENTER — Integrations · Executions · AI Optimization · Logs
// + main WorkflowControlCenter shell
// ============================================================

// ===================== INTEGRATIONS TAB =====================
function WorkflowIntegrationsTab({ workflow, onPushToast }) {
  const INTEGRATIONS_LIST = [
    { name: 'GoHighLevel',      kind: 'CRM',       status: 'healthy',  reqs: 14820, errRate: 0.04, lat: '38ms',  last: '<1s',  apiHealth: 0.99 },
    { name: 'VAPI',             kind: 'Voice',     status: 'healthy',  reqs: 8412,  errRate: 0.08, lat: '184ms', last: '2s',   apiHealth: 0.97 },
    { name: 'Twilio',           kind: 'SMS · Voice', status: 'healthy', reqs: 4218, errRate: 0.02, lat: '74ms',  last: '4s',   apiHealth: 0.99 },
    { name: 'Stripe',           kind: 'Payments',  status: 'healthy',  reqs: 218,   errRate: 0,    lat: '142ms', last: '12m',  apiHealth: 1.0  },
    { name: 'Meta Ads',         kind: 'Paid',      status: 'degraded', reqs: 1840,  errRate: 0.18, lat: '420ms', last: '14m',  apiHealth: 0.82 },
    { name: 'Google Ads',       kind: 'Paid',      status: 'healthy',  reqs: 2412,  errRate: 0.06, lat: '184ms', last: '8m',   apiHealth: 0.96 },
    { name: 'TikTok',           kind: 'Social',    status: 'healthy',  reqs: 1218,  errRate: 0.04, lat: '212ms', last: '22m',  apiHealth: 0.97 },
    { name: 'WhatsApp',         kind: 'Messaging', status: 'healthy',  reqs: 824,   errRate: 0.01, lat: '94ms',  last: '<1s',  apiHealth: 0.99 },
    { name: 'Telegram',         kind: 'Messaging', status: 'healthy',  reqs: 412,   errRate: 0.02, lat: '64ms',  last: '<1s',  apiHealth: 0.99 },
    { name: 'Email · SendGrid', kind: 'Email',     status: 'healthy',  reqs: 12400, errRate: 0.01, lat: '38ms',  last: '<1s',  apiHealth: 1.0  },
    { name: 'Google Calendar',  kind: 'Calendar',  status: 'healthy',  reqs: 2104,  errRate: 0.03, lat: '124ms', last: '4s',   apiHealth: 0.98 },
    { name: 'HubSpot',          kind: 'CRM',       status: 'healthy',  reqs: 612,   errRate: 0.02, lat: '92ms',  last: '14s',  apiHealth: 0.99 },
    { name: 'Salesforce',       kind: 'CRM',       status: 'healthy',  reqs: 184,   errRate: 0.04, lat: '184ms', last: '38s',  apiHealth: 0.96 },
    { name: 'Webhooks',         kind: 'System',    status: 'healthy',  reqs: 4218,  errRate: 0.02, lat: '12ms',  last: '<1s',  apiHealth: 0.99 },
    { name: 'Custom APIs · 14', kind: 'System',    status: 'healthy',  reqs: 612,   errRate: 0.06, lat: '64ms',  last: '24s',  apiHealth: 0.96 }
  ];

  const statusMap = {
    healthy:  { color: 'var(--good)',     label: 'HEALTHY' },
    degraded: { color: 'var(--warn)',     label: 'DEGRADED' },
    down:     { color: 'var(--danger)',   label: 'DOWN' }
  };

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
      <div className="fcc-trf-summary">
        <div className="fcc-trf-stat"><div className="lbl">Integrations live</div><div className="val">{INTEGRATIONS_LIST.filter(i => i.status === 'healthy').length} / {INTEGRATIONS_LIST.length}</div></div>
        <div className="fcc-trf-stat"><div className="lbl">Requests · 24h</div><div className="val" style={{color: 'var(--cyan)'}}>{INTEGRATIONS_LIST.reduce((s, i) => s + i.reqs, 0).toLocaleString()}</div></div>
        <div className="fcc-trf-stat"><div className="lbl">Avg latency</div><div className="val">{Math.round(INTEGRATIONS_LIST.reduce((s, i) => s + parseInt(i.lat), 0) / INTEGRATIONS_LIST.length)}<span style={{fontSize: 14, fontFamily: 'var(--font-mono)', fontStyle: 'normal', marginLeft: 2}}>ms</span></div></div>
        <div className="fcc-trf-stat"><div className="lbl">Error rate · agg</div><div className="val" style={{color: 'var(--warn)'}}>{(INTEGRATIONS_LIST.reduce((s, i) => s + i.errRate * i.reqs, 0) / INTEGRATIONS_LIST.reduce((s, i) => s + i.reqs, 0) * 100).toFixed(2)}<span style={{fontSize: 14, fontFamily: 'var(--font-mono)', fontStyle: 'normal', marginLeft: 2}}>%</span></div></div>
      </div>

      <div className="fcc-mini-card">
        <div className="ccc-setting-hd" style={{padding: '14px 18px'}}>Live connection health · pulse refreshes every 4s</div>
        <div style={{padding: '14px 18px', display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 8}}>
          {INTEGRATIONS_LIST.map(int => (
            <div key={int.name} className="wfc-int-tile" onClick={() => onPushToast(`Connection panel · ${int.name}`)}>
              <div style={{display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8}}>
                <span style={{fontSize: 12, color: 'var(--text)', fontWeight: 500, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{int.name}</span>
                <span className="wfc-int-pip" style={{
                  background: statusMap[int.status].color,
                  boxShadow: `0 0 8px ${statusMap[int.status].color}`,
                  animation: int.status === 'healthy' ? 'pulse 1.6s infinite' : 'none'
                }}/>
              </div>
              <div className="mono faint" style={{fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', marginTop: 3}}>{int.kind}</div>
              <div className="bar-track" style={{marginTop: 8, height: 3}}>
                <div className="bar-fill" style={{
                  width: `${int.apiHealth * 100}%`,
                  background: statusMap[int.status].color,
                  boxShadow: `0 0 6px ${statusMap[int.status].color}`
                }}/>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* Detail table */}
      <div className="fcc-trf-table">
        <div className="fcc-trf-row hd" style={{gridTemplateColumns: '1.6fr 1fr 90px 100px 90px 90px 90px 220px'}}>
          <div className="c">Integration</div>
          <div className="c">Kind</div>
          <div className="c">Status</div>
          <div className="c">Reqs / 24h</div>
          <div className="c">Latency</div>
          <div className="c">Err %</div>
          <div className="c">Last sync</div>
          <div className="c">Controls</div>
        </div>
        {INTEGRATIONS_LIST.map((int, i) => (
          <div key={i} className="fcc-trf-row" style={{gridTemplateColumns: '1.6fr 1fr 90px 100px 90px 90px 90px 220px'}}>
            <div className="c">
              <span className="fcc-trf-dot" style={{background: statusMap[int.status].color, boxShadow: `0 0 6px ${statusMap[int.status].color}`}}/>
              <span style={{color: 'var(--text)', fontSize: 13}}>{int.name}</span>
            </div>
            <div className="c mono dim" style={{fontSize: 11, letterSpacing: '0.06em'}}>{int.kind}</div>
            <div className="c">
              <span style={{
                fontFamily: 'var(--font-mono)', fontSize: 9.5,
                padding: '2px 7px', letterSpacing: '0.14em',
                color: statusMap[int.status].color,
                background: `${statusMap[int.status].color.startsWith('var') ? 'rgba(93,255,176,0.08)' : statusMap[int.status].color}`,
                border: `1px solid ${statusMap[int.status].color}40`,
                borderRadius: 2
              }}>{statusMap[int.status].label}</span>
            </div>
            <div className="c mono tnum" style={{fontSize: 12}}>{int.reqs.toLocaleString()}</div>
            <div className="c mono" style={{fontSize: 12, color: parseInt(int.lat) > 200 ? 'var(--warn)' : 'var(--text-dim)'}}>{int.lat}</div>
            <div className="c mono" style={{fontSize: 12, color: int.errRate > 0.1 ? 'var(--danger)' : int.errRate > 0.05 ? 'var(--warn)' : 'var(--good)'}}>{(int.errRate * 100).toFixed(2)}%</div>
            <div className="c mono faint" style={{fontSize: 11}}>{int.last}</div>
            <div className="c" style={{display: 'flex', gap: 4, padding: '4px 10px'}}>
              <button className="ccc-iconbtn" title="Reconnect" onClick={() => onPushToast(`Reconnecting · ${int.name}`)}><Icon.Refresh style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="Rotate API key" onClick={() => onPushToast(`API key rotated · ${int.name}`)}><Icon.Code style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="Test connection" onClick={() => onPushToast(`Test ping · ${int.name} OK`)}><Icon.Bolt style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="View logs" onClick={() => onPushToast(`Logs · ${int.name}`)}><Icon.Book style={{width: 12, height: 12}}/></button>
              <button className="ccc-iconbtn" title="Pause sync" onClick={() => onPushToast(`Sync paused · ${int.name}`)}><Icon.Pause style={{width: 12, height: 12}}/></button>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ===================== EXECUTIONS TAB =====================
function WorkflowExecutionsTab({ workflow, onPushToast }) {
  const [filter, setFilter] = React.useState('all');
  const [openRun, setOpenRun] = React.useState(null);
  const seed = workflow.id.charCodeAt(3);

  const executions = React.useMemo(() => {
    const arr = [];
    const triggers = ['Form submit', 'Call missed', 'SMS received', 'Lead created', 'Webhook · stripe', 'Calendar booking', 'Social comment', 'Ad click', 'CRM update'];
    const statuses = ['success', 'success', 'success', 'success', 'success', 'warning', 'success', 'failure', 'success', 'success'];
    for (let i = 0; i < 26; i++) {
      const min = (i + seed * 7) % 60;
      const hr = Math.floor((i * 11 + seed) / 6) % 24;
      const status = statuses[(i + seed) % statuses.length];
      const ag = workflow.agents.filter(a => a !== 'system');
      arr.push({
        id: `EX-${(seed * 1000 + i).toString(36).toUpperCase()}`,
        trigger: triggers[(i + seed) % triggers.length],
        agents: ag.length > 0 ? ag.slice(0, 3 + (i % 3)) : ['system'],
        duration: (workflow.avgMs / (0.6 + Math.random())) | 0,
        status,
        revenue: status === 'success' ? Math.round(Math.random() * 480 + 80) : 0,
        errors: status === 'failure' ? 1 : status === 'warning' ? 1 : 0,
        time: `${String(hr).padStart(2, '0')}:${String(min).padStart(2, '0')}:${String((i * 11) % 60).padStart(2, '0')}`
      });
    }
    return arr;
  }, [workflow.id, workflow.avgMs, workflow.agents, seed]);

  const filtered = filter === 'all' ? executions : executions.filter(e => e.status === filter);

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
      <div style={{display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap'}}>
        {[['all','All'],['success','Success'],['warning','Warning'],['failure','Failure']].map(([k, l]) => (
          <button key={k} className={`ccc-pill ${filter === k ? 'on' : ''}`} onClick={() => setFilter(k)}>{l}</button>
        ))}
        <span style={{flex: 1}}/>
        <button className="btn sm" onClick={() => onPushToast('Export started · 26 executions')}>Export</button>
        <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase'}}>
          {filtered.length} runs · streaming
        </span>
      </div>

      <div className="fcc-trf-table">
        <div className="fcc-trf-row hd" style={{gridTemplateColumns: '110px 90px 1.4fr 1.4fr 90px 100px 100px 80px'}}>
          <div className="c">Execution ID</div>
          <div className="c">Time</div>
          <div className="c">Trigger</div>
          <div className="c">Agent chain</div>
          <div className="c">Duration</div>
          <div className="c">Status</div>
          <div className="c">Revenue</div>
          <div className="c">Errors</div>
        </div>
        {filtered.map((e, i) => {
          const statusColor = e.status === 'success' ? 'var(--good)' : e.status === 'warning' ? 'var(--warn)' : 'var(--danger)';
          return (
            <React.Fragment key={e.id}>
              <div className="fcc-trf-row" style={{gridTemplateColumns: '110px 90px 1.4fr 1.4fr 90px 100px 100px 80px', cursor: 'pointer'}} onClick={() => setOpenRun(openRun === e.id ? null : e.id)}>
                <div className="c mono" style={{fontSize: 11, color: 'var(--cyan)', letterSpacing: '0.06em'}}>{e.id}</div>
                <div className="c mono faint" style={{fontSize: 10.5}}>{e.time}</div>
                <div className="c" style={{fontSize: 12.5, color: 'var(--text)'}}>{e.trigger}</div>
                <div className="c" style={{display: 'flex', gap: 3, flexWrap: 'wrap'}}>
                  {e.agents.map((a, ai) => (
                    <span key={ai} className="wf-agent-pill" style={{fontSize: 9}}>{a.toUpperCase()}</span>
                  ))}
                </div>
                <div className="c mono" style={{fontSize: 11}}>{formatDuration(e.duration)}</div>
                <div className="c">
                  <span style={{
                    fontFamily: 'var(--font-mono)', fontSize: 9.5,
                    padding: '2px 7px', letterSpacing: '0.14em',
                    color: statusColor,
                    background: `${statusColor}12`,
                    border: `1px solid ${statusColor}40`,
                    borderRadius: 2
                  }}>{e.status.toUpperCase()}</span>
                </div>
                <div className="c mono" style={{fontSize: 12, color: e.revenue > 0 ? 'var(--good)' : 'var(--text-faint)'}}>{e.revenue > 0 ? `£${e.revenue}` : '—'}</div>
                <div className="c mono" style={{fontSize: 12, color: e.errors > 0 ? 'var(--danger)' : 'var(--text-faint)'}}>{e.errors}</div>
              </div>
              {openRun === e.id && (
                <div style={{
                  gridColumn: '1 / -1',
                  padding: '14px 24px 18px',
                  background: 'rgba(75,232,255,0.03)',
                  borderBottom: '1px solid var(--border)'
                }}>
                  <div className="mono" style={{fontSize: 10.5, color: 'var(--brass-bright, #e8c98a)', letterSpacing: '0.18em', textTransform: 'uppercase', marginBottom: 12}}>
                    / Execution playback · trace
                  </div>
                  <div className="wfc-exec-trace">
                    {[
                      { ok: true,  step: e.trigger,                  detail: 'Trigger fired'},
                      { ok: true,  step: 'Enrich profile',           detail: 'Vesta · 1.2s'},
                      { ok: true,  step: 'ICP score 0.84',           detail: 'Pass threshold'},
                      { ok: e.status !== 'failure', step: 'SMS sent', detail: 'Twilio · delivered'},
                      { ok: e.status === 'success', step: 'AI call · Hermes', detail: e.status === 'failure' ? 'No-answer · 3 retries' : 'Connected · 4m talk-time'},
                      { ok: e.status === 'success', step: 'Booking secured', detail: e.status === 'success' ? 'Slot held · Tue 14:30' : 'Routed to nurture'}
                    ].map((step, si) => (
                      <div key={si} className="wfc-exec-step">
                        <span className="wfc-exec-dot" style={{background: step.ok ? 'var(--good)' : 'var(--danger)', boxShadow: `0 0 6px ${step.ok ? 'var(--good)' : 'var(--danger)'}`}}/>
                        <div style={{flex: 1, minWidth: 0}}>
                          <div style={{fontSize: 12.5, color: 'var(--text)'}}>{step.step}</div>
                          <div className="mono faint" style={{fontSize: 10, letterSpacing: '0.06em'}}>{step.detail}</div>
                        </div>
                        {!step.ok && (
                          <span className="mono" style={{fontSize: 9.5, color: 'var(--warn)', letterSpacing: '0.12em', textTransform: 'uppercase'}}>↻ retry 2/3</span>
                        )}
                      </div>
                    ))}
                  </div>
                </div>
              )}
            </React.Fragment>
          );
        })}
      </div>
    </div>
  );
}

// ===================== AI OPTIMIZATION TAB =====================
function WorkflowOptimizationTab({ workflow, onPushToast }) {
  const [busy, setBusy] = React.useState(null);
  const [simResult, setSimResult] = React.useState(null);

  const RECOMMENDATIONS = [
    { p: 'high', id: 'r1', text: 'Move SMS before email at stage 4', impact: '+14% reply rate', detail: 'Email open-rate is 22% on this audience but SMS pickup is 78%. Reordering reduces drop at qualification.', before: 18, after: 32 },
    { p: 'high', id: 'r2', text: 'Trigger AI call after 8 minutes (currently 2 hours)', impact: '+18 booked / mo', detail: 'Speed-to-lead data: below 8 min, close rate is 28%. Above 1h, it falls to 9%.', before: 9, after: 28 },
    { p: 'med',  id: 'r3', text: 'Add personalisation to email subject', impact: '+4% open rate', detail: 'Brand-voice subject lines outperform templated by 4-6pp on tested cohorts.', before: 22, after: 26 },
    { p: 'med',  id: 'r4', text: 'Increase retry attempts on AI call from 3 → 5', impact: '+8% pickup', detail: 'Diminishing returns past 5 but 4th and 5th attempts still convert at 12%.', before: 64, after: 72 },
    { p: 'low',  id: 'r5', text: 'Test brass-foil CTA on confirmation email', impact: '+0.4pp CTR', detail: 'Visual difference plays well in luxury verticals.', before: 8, after: 8.4 }
  ];

  const runSim = async (rec) => {
    setBusy(rec.id);
    setSimResult(null);
    await new Promise(r => setTimeout(r, 700));
    setSimResult({ rec, computed: { before: rec.before, after: rec.after } });
    setBusy(null);
    onPushToast(`Simulation complete · ${rec.text}`);
  };

  return (
    <div style={{display: 'flex', flexDirection: 'column', gap: 14}}>
      {/* Score cards */}
      <div style={{display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 12}}>
        {[
          ['Optimization score', '8.4', '/ 10', 'var(--good)'],
          ['Revenue opportunity', '£42k', '/ mo', 'var(--good)'],
          ['Risk detection', '3 ⚠', 'active', 'var(--warn)'],
          ['Speed improvements', '+38%', 'potential', 'var(--cyan)'],
          ['Recovery potential', '17', 'leads / wk', 'var(--magenta)']
        ].map(([lbl, v, sub, color], i) => (
          <div key={i} className="fcc-kpi-mini">
            <div className="lbl">{lbl}</div>
            <div className="val" style={{color}}>{v}</div>
            <div className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.12em', marginTop: 4}}>{sub}</div>
          </div>
        ))}
      </div>

      <div className="fcc-alert info">
        <span className="fcc-alert-icon" style={{color: 'var(--brass-bright, #e8c98a)'}}>✦</span>
        <div style={{flex: 1}}>
          <div className="fcc-alert-title">Iris analyzed {workflow.triggers24h.toLocaleString()} executions over the last 14 days · 5 candidate optimizations</div>
          <div className="fcc-alert-body">
            Combined recommendations project <span style={{color: 'var(--good)'}}>+£42k/month</span> if applied. Run simulation per recommendation to see before-vs-after.
          </div>
        </div>
        <button className="btn primary sm" onClick={() => onPushToast('Auto-optimize started · safe-mode')}>Auto-optimize all</button>
      </div>

      <div className="fcc-mini-card">
        <div className="ccc-setting-hd" style={{padding: '14px 18px'}}>Ranked recommendations</div>
        <div style={{padding: '8px 0'}}>
          {RECOMMENDATIONS.map(r => (
            <div key={r.id} className="as-insight">
              <div className="as-insight-score" style={{
                color: r.p === 'high' ? 'var(--danger)' : r.p === 'med' ? 'var(--warn)' : 'var(--text-dim)',
                background: r.p === 'high' ? 'rgba(255,93,110,0.08)' : r.p === 'med' ? 'rgba(255,177,75,0.08)' : 'rgba(255,255,255,0.04)',
                border: `1px solid ${r.p === 'high' ? 'rgba(255,93,110,0.3)' : r.p === 'med' ? 'rgba(255,177,75,0.3)' : 'rgba(255,255,255,0.12)'}`,
                fontSize: 14
              }}>
                {r.p.toUpperCase()}
              </div>
              <div style={{flex: 1, minWidth: 0}}>
                <div style={{fontSize: 13.5, color: 'var(--text)', marginBottom: 4}}>{r.text}</div>
                <div style={{fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.5}}>{r.detail}</div>
              </div>
              <div style={{display: 'flex', flexDirection: 'column', gap: 6, alignItems: 'flex-end', flexShrink: 0}}>
                <span className="mono" style={{fontSize: 11, color: 'var(--good)', letterSpacing: '0.06em'}}>{r.impact}</span>
                <div style={{display: 'flex', gap: 4}}>
                  <button className="btn ghost sm" onClick={() => onPushToast(`Assigned to operator · ${r.text.slice(0, 32)}…`)}>Assign</button>
                  <button className="btn ghost sm" onClick={() => runSim(r)} disabled={busy === r.id}>{busy === r.id ? '…' : 'Simulate'}</button>
                  <button className="btn ghost sm" onClick={() => onPushToast(`A/B test launched · split 20%`)}>A/B test</button>
                  <button className="btn primary sm" onClick={() => onPushToast(`Applied · ${r.text.slice(0, 24)}…`)}>Apply</button>
                </div>
              </div>
            </div>
          ))}
        </div>
      </div>

      {simResult && (
        <div className="fcc-mini-card">
          <div className="ccc-setting-hd" style={{padding: '14px 18px'}}>Simulation · {simResult.rec.text}</div>
          <div style={{padding: '16px 18px', display: 'grid', gridTemplateColumns: '1fr 60px 1fr', gap: 18, alignItems: 'center'}}>
            <div style={{padding: 16, background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border)', borderRadius: 'var(--radius)'}}>
              <div className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.16em', textTransform: 'uppercase'}}>Before</div>
              <div style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 36, color: 'var(--text-dim)', letterSpacing: '-0.02em', marginTop: 6}}>{simResult.computed.before}%</div>
              <div className="mono faint" style={{fontSize: 10, marginTop: 4}}>baseline · 14d</div>
            </div>
            <div style={{textAlign: 'center', color: 'var(--brass-bright, #e8c98a)', fontSize: 22}}>→</div>
            <div style={{padding: 16, background: 'rgba(93,255,176,0.04)', border: '1px solid rgba(93,255,176,0.3)', borderRadius: 'var(--radius)'}}>
              <div className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.16em', textTransform: 'uppercase'}}>Projected after</div>
              <div style={{fontFamily: 'var(--font-display)', fontStyle: 'italic', fontSize: 36, color: 'var(--good)', letterSpacing: '-0.02em', marginTop: 6}}>{simResult.computed.after}%</div>
              <div className="mono" style={{fontSize: 10, marginTop: 4, color: 'var(--good)'}}>+{(simResult.computed.after - simResult.computed.before).toFixed(1)}pp · {simResult.rec.impact}</div>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

// ===================== LOGS TAB =====================
function WorkflowLogsTab({ workflow }) {
  const [filter, setFilter] = React.useState('all');
  const seed = workflow.id.charCodeAt(3);

  const events = React.useMemo(() => {
    const types = [
      { k: 'start',     icon: '⏵', color: 'var(--good)',     label: 'workflow_started',     verbs: ['Workflow run started for', 'New execution initiated on', 'Run kicked off for'] },
      { k: 'node',      icon: '◆', color: 'var(--cyan)',     label: 'node_triggered',       verbs: ['Node executed:', 'Step fired:', 'Action ran:'] },
      { k: 'ai',        icon: '✦', color: 'var(--magenta)',  label: 'ai_decision',          verbs: ['AI decision: route to', 'Confidence threshold met for', 'Agent selected:'] },
      { k: 'fallback',  icon: '↻', color: 'var(--warn)',     label: 'fallback_activated',   verbs: ['Fallback engaged for', 'Retry policy fired on', 'Alternative path taken for'] },
      { k: 'api',       icon: '⚡', color: 'var(--danger)',   label: 'api_error',            verbs: ['API error from', 'Provider timeout on', '503 received from'] },
      { k: 'retry',     icon: '↺', color: 'var(--warn)',     label: 'retry_fired',          verbs: ['Retry 2/3 on', 'Backoff retry for', 'Re-attempt fired:'] },
      { k: 'complete',  icon: '✓', color: 'var(--good)',     label: 'workflow_completed',   verbs: ['Run completed for', 'Execution finished on', 'Loop closed for'] },
      { k: 'human',     icon: '◑', color: 'var(--brass-bright, #e8c98a)', label: 'human_intervention', verbs: ['Operator paused', 'Manual override on', 'Reza intervened on'] },
      { k: 'optim',     icon: '◐', color: 'var(--violet)',   label: 'optimization_applied', verbs: ['Recommendation applied to', 'AI optimization committed:', 'Auto-tuning shifted on'] }
    ];
    const stageNames = ['lead_capture', 'enrich', 'icp_score', 'sms_send', 'ai_call', 'booking', 'reminder', 'close'];
    const arr = [];
    for (let i = 0; i < 42; i++) {
      const tIdx = (seed + i * 5) % types.length;
      const type = types[tIdx];
      const stage = stageNames[(i + seed) % stageNames.length];
      const min = (i + seed * 7) % 60;
      const hr = Math.floor((i * 13 + seed) / 6) % 24;
      const verb = type.verbs[i % type.verbs.length];
      arr.push({
        time: `${String(hr).padStart(2, '0')}:${String(min).padStart(2, '0')}:${String((i * 11) % 60).padStart(2, '0')}`,
        type,
        msg: `${verb} ${stage}`,
        actor: ['system', 'Iris', 'Calliope', 'Hermes', 'Atlas', 'Reza', 'Vesta'][(i + seed) % 7]
      });
    }
    return arr;
  }, [workflow.id, seed]);

  const sets = {
    ai:       new Set(['ai', 'optim']),
    system:   new Set(['start', 'node', 'complete', 'fallback']),
    human:    new Set(['human']),
    critical: new Set(['api']),
    warning:  new Set(['fallback', 'retry']),
    success:  new Set(['complete', 'start', 'optim']),
    failure:  new Set(['api'])
  };

  const filtered = filter === 'all' ? events
    : sets[filter] ? events.filter(e => sets[filter].has(e.type.k))
    : events;

  return (
    <div>
      <div style={{display: 'flex', alignItems: 'center', gap: 10, padding: '0 4px 14px', flexWrap: 'wrap'}}>
        {[['all','All'],['ai','AI'],['system','System'],['human','Human'],['critical','Critical'],['warning','Warning'],['success','Success'],['failure','Failure']].map(([k, l]) => (
          <button key={k} onClick={() => setFilter(k)} className={`ccc-pill ${filter === k ? 'on' : ''}`}>{l}</button>
        ))}
        <span style={{flex: 1}}/>
        <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase'}}>
          Streaming · {filtered.length} events
        </span>
      </div>
      <div className="ccc-logs">
        {filtered.map((e, i) => (
          <div key={i} className="ccc-log-row">
            <span className="mono faint" style={{fontSize: 10.5, color: 'var(--text-faint)', minWidth: 64}}>{e.time}</span>
            <span style={{
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              width: 20, height: 20, borderRadius: 3,
              background: `${e.type.color}15`, color: e.type.color,
              fontSize: 11, border: `1px solid ${e.type.color}40`
            }}>{e.type.icon}</span>
            <span className="mono" style={{fontSize: 10, color: e.type.color, letterSpacing: '0.12em', textTransform: 'uppercase', minWidth: 140}}>{e.type.label}</span>
            <span style={{fontSize: 12.5, color: 'var(--text)', flex: 1, minWidth: 0, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis'}}>{e.msg}</span>
            <span className="mono faint" style={{fontSize: 10}}>{e.actor}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

// ===================== MAIN CONTROL CENTER =====================
function WorkflowControlCenter({ workflow, onBack }) {
  const [tab, setTab] = React.useState('overview');
  const [toast, setToast] = React.useState(null);

  const pushToast = (msg) => {
    setToast({ msg, id: Date.now() });
    setTimeout(() => setToast(t => (t && t.msg === msg ? null : t)), 2400);
  };

  const cat = WORKFLOW_CATEGORIES[workflow.cat];
  const st = WORKFLOW_STATUS[workflow.status];

  return (
    <div className="ccc-shell">
      <div className="ccc-hd">
        <button className="ccc-back" onClick={onBack}>
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M19 12H5M11 18l-6-6 6-6"/></svg>
          <span>Workflows</span>
        </button>
        <div className="ccc-hd-glyph" style={{color: cat.hue, background: `linear-gradient(135deg, ${cat.hue}25, ${cat.hue}05)`, borderColor: `${cat.hue}30`}}>
          <Icon.Flow style={{width: 28, height: 28}}/>
        </div>
        <div className="ccc-hd-info">
          <div className="ccc-hd-title"><em>{workflow.name}</em></div>
          <div className="ccc-hd-sub">
            {cat.label} · {workflow.automations} automations · {workflow.triggers24h.toLocaleString()} triggers / 24h · {workflow.agents.length} operators
          </div>
        </div>
        <div className="ccc-hd-actions">
          <span style={{display: 'inline-flex', alignItems: 'center', gap: 6, padding: '6px 12px', fontFamily: 'var(--font-mono)', fontSize: 10.5, letterSpacing: '0.14em', color: st.color, background: st.bg, border: `1px solid ${st.border}`, borderRadius: 3}}>
            <span className="pip" style={{width: 5, height: 5, borderRadius: '50%', background: st.color, boxShadow: workflow.status === 'paused' ? 'none' : `0 0 6px ${st.color}`, animation: workflow.status === 'paused' ? 'none' : 'pulse 1.6s infinite'}}/>
            {st.label}
          </span>
          <button className="btn primary sm" onClick={() => pushToast('Workflow cloned as draft v.2')}>Clone</button>
        </div>
      </div>

      {/* Aggregate stats */}
      <div className="ccc-stats">
        {[
          { lbl: 'Health',          v: `${Math.round(workflow.health * 100)}`, color: workflow.health > 0.85 ? 'var(--good)' : workflow.health > 0.6 ? 'var(--cyan)' : 'var(--warn)' },
          { lbl: 'Triggers / 24h',  v: workflow.triggers24h.toLocaleString(), color: 'var(--cyan)' },
          { lbl: 'Success',         v: `${workflow.success}%`, color: workflow.success >= 90 ? 'var(--good)' : 'var(--cyan)' },
          { lbl: 'Avg speed',       v: formatDuration(workflow.avgMs), color: 'var(--text)' },
          { lbl: 'Automations',     v: workflow.automations, color: 'var(--violet)' },
          { lbl: 'Bottlenecks',     v: workflow.bottlenecks, color: workflow.bottlenecks > 0 ? 'var(--warn)' : 'var(--text-faint)' },
          { lbl: 'AI score',        v: `${workflow.aiScore}/10`, color: 'var(--magenta)' },
          { lbl: 'Operators',       v: workflow.agents.length, color: 'var(--brass-bright, #e8c98a)' },
          { lbl: 'Last exec',       v: workflow.lastExec, color: 'var(--text-dim)' }
        ].map((s, i) => (
          <div key={i} className="ccc-stat">
            <div className="lbl">{s.lbl}</div>
            <div className="val" style={{color: s.color}}>{s.v}</div>
          </div>
        ))}
      </div>

      <div className="ccc-tabs">
        {[
          ['overview',     'Overview'],
          ['builder',      'Flow Builder'],
          ['agents',       'Agents',       `${workflow.agents.length}`],
          ['integrations', 'Integrations'],
          ['executions',   'Executions'],
          ['ai',           'AI Optimization'],
          ['logs',         'Logs']
        ].map(([k, l, badge]) => (
          <button key={k} className={`ccc-tab ${tab === k ? 'on' : ''}`} onClick={() => setTab(k)}>
            {l} {badge ? <span className="ccc-tab-badge">{badge}</span> : null}
          </button>
        ))}
        <div style={{flex: 1, borderBottom: '1px solid var(--border)'}}/>
      </div>

      <div className="ccc-body">
        {tab === 'overview'     && <WorkflowOverviewTab     workflow={workflow} onPushToast={pushToast}/>}
        {tab === 'builder'      && <WorkflowFlowBuilderTab  workflow={workflow} onPushToast={pushToast}/>}
        {tab === 'agents'       && <WorkflowAgentsTab       workflow={workflow} onPushToast={pushToast}/>}
        {tab === 'integrations' && <WorkflowIntegrationsTab workflow={workflow} onPushToast={pushToast}/>}
        {tab === 'executions'   && <WorkflowExecutionsTab   workflow={workflow} onPushToast={pushToast}/>}
        {tab === 'ai'           && <WorkflowOptimizationTab workflow={workflow} onPushToast={pushToast}/>}
        {tab === 'logs'         && <WorkflowLogsTab         workflow={workflow}/>}
      </div>

      {toast && (
        <div className="ccc-toast" key={toast.id}>
          <span className="pip" style={{background: 'var(--cyan)', boxShadow: '0 0 6px var(--cyan)'}}/>
          {toast.msg}
        </div>
      )}
    </div>
  );
}

window.WorkflowControlCenter = WorkflowControlCenter;
