// ============================================================
// WORKFLOWS — Grid + state-driven Control Center handoff
// ============================================================

const WORKFLOW_CATEGORIES = {
  capture:      { label: 'Lead Capture',             hue: '#4be8ff' },
  qualify:      { label: 'Lead Qualification',       hue: '#8b6bff' },
  booking:      { label: 'Booking Automation',       hue: '#ff7ad9' },
  sales_fu:     { label: 'Sales Follow-up',          hue: '#5dffb0' },
  ai_call:      { label: 'AI Calling',               hue: '#e8c98a' },
  crm:          { label: 'CRM Sync',                 hue: '#4be8ff' },
  social:       { label: 'Social Automation',        hue: '#ff7ad9' },
  content:      { label: 'Content Generation',       hue: '#ff7ad9' },
  reputation:   { label: 'Reputation Management',    hue: '#e8c98a' },
  reviews:      { label: 'Review Requests',          hue: '#5dffb0' },
  reactivation: { label: 'Reactivation',             hue: '#ffb14b' },
  support:      { label: 'Customer Support',         hue: '#4be8ff' },
  ops:          { label: 'Internal Operations',      hue: '#8b6bff' },
  finance:      { label: 'Finance Automation',       hue: '#5dffb0' },
  team:         { label: 'Team Notifications',       hue: '#eaecf5' },
  multi:        { label: 'Multi-Agent Orchestration', hue: '#ff7ad9' }
};

const WORKFLOW_STATUS = {
  live:       { label: 'LIVE',       color: 'var(--cyan)',     bg: 'rgba(75,232,255,0.08)',  border: 'rgba(75,232,255,0.3)' },
  training:   { label: 'TRAINING',   color: 'var(--violet)',   bg: 'rgba(139,107,255,0.08)', border: 'rgba(139,107,255,0.3)' },
  optimizing: { label: 'OPTIMIZING', color: 'var(--magenta)',  bg: 'rgba(255,122,217,0.08)', border: 'rgba(255,122,217,0.3)' },
  paused:     { label: 'PAUSED',     color: 'var(--text-dim)', bg: 'rgba(255,255,255,0.04)', border: 'rgba(255,255,255,0.1)' },
  warning:    { label: 'WARNING',    color: 'var(--warn)',     bg: 'rgba(255,177,75,0.08)',  border: 'rgba(255,177,75,0.3)' },
  failed:     { label: 'FAILED',     color: 'var(--danger)',   bg: 'rgba(255,93,110,0.08)',  border: 'rgba(255,93,110,0.3)' }
};

const WORKFLOWS = [
  { id: 'wf-clinic-recover', name: 'Clinic · lead recovery',           cat: 'capture',      status: 'live',       health: 0.96, automations: 7,  triggers24h: 1284, success: 96, avgMs: 18420, bottlenecks: 0, aiScore: 8.4, lastExec: 'now',   agents: ['Vesta', 'Hermes', 'Atlas'] },
  { id: 'wf-icp-qualify',    name: 'ICP qualification engine',         cat: 'qualify',      status: 'live',       health: 0.94, automations: 5,  triggers24h: 4218, success: 92, avgMs: 4200,  bottlenecks: 0, aiScore: 9.1, lastExec: '4s',    agents: ['Vesta', 'Iris'] },
  { id: 'wf-booking-engine', name: 'Booking · 7-stage cascade',        cat: 'booking',      status: 'live',       health: 0.91, automations: 9,  triggers24h: 612,  success: 88, avgMs: 92000, bottlenecks: 1, aiScore: 7.6, lastExec: '18s',   agents: ['Hermes', 'Atlas'] },
  { id: 'wf-no-show-rec',    name: 'No-show recovery · D0-D3',         cat: 'sales_fu',     status: 'optimizing', health: 0.82, automations: 6,  triggers24h: 184,  success: 78, avgMs: 280000, bottlenecks: 1, aiScore: 7.9, lastExec: '38s',   agents: ['Hermes', 'Calliope'] },
  { id: 'wf-cold-call-cas',  name: 'AI cold-call cadence',             cat: 'ai_call',      status: 'live',       health: 0.88, automations: 4,  triggers24h: 8412, success: 64, avgMs: 184000,bottlenecks: 0, aiScore: 8.8, lastExec: '2s',    agents: ['Hermes'] },
  { id: 'wf-crm-bidirect',   name: 'CRM bi-directional sync',          cat: 'crm',          status: 'live',       health: 0.99, automations: 3,  triggers24h: 14802, success: 99, avgMs: 280,  bottlenecks: 0, aiScore: 6.2, lastExec: '<1s',   agents: ['system'] },
  { id: 'wf-social-broad',   name: 'Social broadcast · 11 platforms',  cat: 'social',       status: 'live',       health: 0.94, automations: 11, triggers24h: 184,  success: 96, avgMs: 12400, bottlenecks: 0, aiScore: 8.2, lastExec: '12m',   agents: ['Calliope', 'Orion'] },
  { id: 'wf-content-pipe',   name: 'Content production pipeline',      cat: 'content',      status: 'live',       health: 0.92, automations: 8,  triggers24h: 412,  success: 94, avgMs: 84000, bottlenecks: 0, aiScore: 8.7, lastExec: '4m',    agents: ['Calliope'] },
  { id: 'wf-rep-monitor',    name: 'Reputation monitor · 24 sources',  cat: 'reputation',   status: 'warning',    health: 0.62, automations: 5,  triggers24h: 84,   success: 72, avgMs: 14200, bottlenecks: 2, aiScore: 6.4, lastExec: '14m',   agents: ['Iris', 'Hermes'] },
  { id: 'wf-review-ask',     name: 'Review request · post-service',    cat: 'reviews',      status: 'live',       health: 0.93, automations: 4,  triggers24h: 184,  success: 84, avgMs: 8400,  bottlenecks: 0, aiScore: 8.4, lastExec: '6m',    agents: ['Hermes', 'Calliope'] },
  { id: 'wf-react-lapsed',   name: 'Lapsed-account reactivation',      cat: 'reactivation', status: 'optimizing', health: 0.78, automations: 6,  triggers24h: 412,  success: 32, avgMs: 4200000, bottlenecks: 1, aiScore: 7.2, lastExec: '24m',   agents: ['Calliope', 'Hermes'] },
  { id: 'wf-tier1-support',  name: 'Tier-1 support · auto-resolve',    cat: 'support',      status: 'live',       health: 0.97, automations: 7,  triggers24h: 1840, success: 96, avgMs: 22000, bottlenecks: 0, aiScore: 9.4, lastExec: '<1s',   agents: ['Iris'] },
  { id: 'wf-ops-runbook',    name: 'Ops runbook · daily',              cat: 'ops',          status: 'live',       health: 0.95, automations: 12, triggers24h: 84,   success: 99, avgMs: 184000,bottlenecks: 0, aiScore: 7.4, lastExec: '1h',    agents: ['system', 'Vulcan'] },
  { id: 'wf-fin-recon',      name: 'Finance reconciliation',           cat: 'finance',      status: 'live',       health: 0.98, automations: 6,  triggers24h: 412,  success: 99, avgMs: 4200,  bottlenecks: 0, aiScore: 6.8, lastExec: '12m',   agents: ['system'] },
  { id: 'wf-team-alerts',    name: 'Team notifications · digest',      cat: 'team',         status: 'live',       health: 0.92, automations: 4,  triggers24h: 184,  success: 98, avgMs: 184,   bottlenecks: 0, aiScore: 5.4, lastExec: '4m',    agents: ['system'] },
  { id: 'wf-multi-close',    name: 'Multi-agent close · enterprise',   cat: 'multi',        status: 'training',   health: 0.74, automations: 14, triggers24h: 28,   success: 68, avgMs: 480000, bottlenecks: 1, aiScore: 8.9, lastExec: '38s',   agents: ['Atlas','Vesta','Hermes','Calliope','Iris','Orion'] }
];

function formatDuration(ms) {
  if (ms < 1000) return `${ms}ms`;
  if (ms < 60000) return `${(ms/1000).toFixed(1)}s`;
  if (ms < 3600000) return `${(ms/60000).toFixed(1)}m`;
  return `${(ms/3600000).toFixed(1)}h`;
}

function WorkflowMiniGraph({ wf }) {
  const sparkData = React.useMemo(
    () => Array.from({length: 28}, (_, i) => 30 + Math.sin(i * 0.6 + wf.id.charCodeAt(3)) * 18 + Math.random() * 8),
    [wf.id]
  );
  const max = Math.max(...sparkData);
  const min = Math.min(...sparkData);
  const range = max - min || 1;
  const pts = sparkData.map((v, i) => `${(i / (sparkData.length - 1)) * 100},${100 - ((v - min) / range) * 100}`).join(' ');
  const hue = WORKFLOW_CATEGORIES[wf.cat].hue;
  const id = `wf-g-${wf.id}`;
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{width: '100%', height: 32}}>
      <defs>
        <linearGradient id={id} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={hue} stopOpacity="0.4"/>
          <stop offset="100%" stopColor={hue} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <polygon points={`0,100 ${pts} 100,100`} fill={`url(#${id})`}/>
      <polyline points={pts} fill="none" stroke={hue} strokeWidth="1.4" vectorEffect="non-scaling-stroke"/>
    </svg>
  );
}

function WorkflowCard({ wf, onOpen }) {
  const cat = WORKFLOW_CATEGORIES[wf.cat];
  const st = WORKFLOW_STATUS[wf.status];
  const healthColor = wf.health > 0.85 ? 'var(--good)' : wf.health > 0.7 ? 'var(--cyan)' : wf.health > 0.5 ? 'var(--warn)' : 'var(--danger)';

  return (
    <div
      className="wf-card"
      role="button"
      tabIndex={0}
      onClick={() => onOpen(wf)}
      onKeyDown={e => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); onOpen(wf); }}}
    >
      <span className="wf-card-sash" style={{background: cat.hue}}/>
      <span className="br-bl"></span>
      <span className="br-br"></span>

      <div className="wf-card-hd">
        <div className="wf-card-cat" style={{color: cat.hue, borderColor: `${cat.hue}30`, background: `${cat.hue}08`}}>
          {cat.label}
        </div>
        <div className="wf-card-status" style={{color: st.color, background: st.bg, borderColor: st.border}}>
          <span className="pip" style={{background: st.color, boxShadow: wf.status === 'paused' ? 'none' : `0 0 6px ${st.color}`}}/>
          {st.label}
        </div>
      </div>

      <div className="wf-card-name">{wf.name}</div>

      <div className="wf-card-stats">
        <div className="wf-stat">
          <div className="lbl">Triggers / 24h</div>
          <div className="val">{wf.triggers24h.toLocaleString()}</div>
        </div>
        <div className="wf-stat">
          <div className="lbl">Success</div>
          <div className="val" style={{color: wf.success >= 90 ? 'var(--good)' : wf.success >= 75 ? 'var(--cyan)' : 'var(--warn)'}}>{wf.success}<span className="u">%</span></div>
        </div>
        <div className="wf-stat">
          <div className="lbl">Avg time</div>
          <div className="val">{formatDuration(wf.avgMs)}</div>
        </div>
        <div className="wf-stat">
          <div className="lbl">Automations</div>
          <div className="val" style={{color: 'var(--violet)'}}>{wf.automations}</div>
        </div>
      </div>

      <WorkflowMiniGraph wf={wf}/>

      <div className="wf-card-meta">
        <div style={{display: 'flex', alignItems: 'center', gap: 8}}>
          <span className="mono faint" style={{fontSize: 9.5, letterSpacing: '0.14em', textTransform: 'uppercase'}}>Health</span>
          <div className="bar-track" style={{width: 50, height: 3}}>
            <div className="bar-fill" style={{width: `${wf.health * 100}%`, background: healthColor, boxShadow: `0 0 6px ${healthColor}`}}/>
          </div>
          <span className="mono" style={{fontSize: 10, color: healthColor}}>{Math.round(wf.health * 100)}</span>
        </div>
        {wf.bottlenecks > 0 ? (
          <span className="mono" style={{fontSize: 10, color: 'var(--warn)', letterSpacing: '0.12em', textTransform: 'uppercase'}}>
            ⚠ {wf.bottlenecks} bottleneck
          </span>
        ) : (
          <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.1em'}}>AI {wf.aiScore}/10</span>
        )}
      </div>

      <div className="wf-card-agents">
        {wf.agents.slice(0, 5).map(a => (
          <span key={a} className="wf-agent-pill">{a.toUpperCase()}</span>
        ))}
        {wf.agents.length > 5 && <span className="wf-agent-pill more">+{wf.agents.length - 5}</span>}
      </div>

      <div className="wf-card-foot">
        <span className="mono faint" style={{fontSize: 10, letterSpacing: '0.1em'}}>
          last <span style={{color: 'var(--text-dim)'}}>{wf.lastExec}</span>
        </span>
        <span className="wf-card-open">Open command center <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M9 6l6 6-6 6"/></svg></span>
      </div>
      <div className="wf-card-hover-glow"></div>
    </div>
  );
}

function Workflows() {
  const [filter, setFilter] = React.useState('all');
  const [search, setSearch] = React.useState('');
  const [selected, setSelected] = React.useState(null);

  React.useEffect(() => {
    if (!selected) return;
    const onKey = (e) => { if (e.key === 'Escape') setSelected(null); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [selected]);

  if (selected) {
    return (
      <div className="ch-fade-in">
        <WorkflowControlCenter workflow={selected} onBack={() => setSelected(null)}/>
      </div>
    );
  }

  const filtered = WORKFLOWS.filter(w => {
    if (filter !== 'all' && w.status !== filter && w.cat !== filter) return false;
    if (search && !`${w.name} ${WORKFLOW_CATEGORIES[w.cat].label} ${w.agents.join(' ')}`.toLowerCase().includes(search.toLowerCase())) return false;
    return true;
  });
  const total = WORKFLOWS.length;
  const live = WORKFLOWS.filter(w => w.status === 'live').length;
  const totalTriggers = WORKFLOWS.reduce((s, w) => s + w.triggers24h, 0);
  const totalBottlenecks = WORKFLOWS.reduce((s, w) => s + w.bottlenecks, 0);

  return (
    <div>
      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">Autonomous nervous system · {live} of {total} live · {totalTriggers.toLocaleString()} triggers / 24h</div>
          <h1 className="page-title"><em>Workflow</em> <strong>· orchestration</strong></h1>
          <div className="page-sub">Every workflow chains operators, integrations, and conditions into a single autonomous loop. Click any to open its command center — flow builder, agent graph, executions, AI optimization, and a full audit trail.</div>
        </div>
        <div className="page-hd-r">
          <button className="btn" data-handled="1" onClick={() => window.demiurgeNav?.('templates')}><Icon.Plus className="icon"/>From template</button>
          <button className="btn primary" data-handled="1" onClick={() => window.runAction('deployWorkflow')}><Icon.Sparkles className="icon"/>AI generate workflow</button>
        </div>
      </div>

      {/* Search bar */}
      <div style={{padding: '20px 32px 0'}}>
        <div className="as-cmd">
          <Icon.Sparkles style={{width: 16, height: 16, color: 'var(--brass-bright, #e8c98a)'}}/>
          <input
            value={search}
            onChange={e => setSearch(e.target.value)}
            placeholder='Ask Demiurge Orchestrator  ·  "Show failed booking automations"  ·  "Which workflow generated most revenue?"  ·  "Where are leads dropping?"'
            style={{flex: 1, fontSize: 13, padding: '6px 0', fontFamily: 'var(--font-mono)', color: 'var(--text)'}}
          />
          <span className="kbd">⌘ W</span>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{padding: '24px 32px 0', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14}}>
        <div className="kpi-block">
          <div className="kpi-label">Triggers fired · 24h</div>
          <div className="kpi-val tnum">{totalTriggers.toLocaleString()}</div>
          <div className="kpi-meta"><span className="delta up">+18%</span><span className="dim">vs avg</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Avg success rate</div>
          <div className="kpi-val tnum">{Math.round(WORKFLOWS.reduce((s, w) => s + w.success, 0) / WORKFLOWS.length)}<span className="unit">%</span></div>
          <div className="kpi-meta"><span className="delta up">+2.4pp</span><span className="dim">network-wide</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Bottlenecks active</div>
          <div className="kpi-val tnum" style={{color: totalBottlenecks > 0 ? 'var(--warn)' : 'var(--text)'}}>{totalBottlenecks}</div>
          <div className="kpi-meta"><span className="dim">{totalBottlenecks > 0 ? 'AI optimizing' : 'all clear'}</span></div>
        </div>
        <div className="kpi-block">
          <div className="kpi-label">Multi-agent orchestrations</div>
          <div className="kpi-val tnum">{WORKFLOWS.filter(w => w.agents.length > 2).length}</div>
          <div className="kpi-meta"><span className="dim">{WORKFLOWS.reduce((s, w) => s + w.agents.length, 0)} agents in motion</span></div>
        </div>
      </div>

      {/* Filter pills */}
      <div style={{padding: '20px 32px 0', display: 'flex', flexWrap: 'wrap', gap: 8}}>
        <button className={`ccc-pill ${filter === 'all' ? 'on' : ''}`} onClick={() => setFilter('all')}>All</button>
        {Object.entries(WORKFLOW_STATUS).map(([k, s]) => {
          const n = WORKFLOWS.filter(w => w.status === k).length;
          if (n === 0) return null;
          return <button key={k} className={`ccc-pill ${filter === k ? 'on' : ''}`} onClick={() => setFilter(k)}>{s.label} <span style={{opacity: 0.6, marginLeft: 4}}>{n}</span></button>;
        })}
      </div>

      <div style={{padding: '20px 32px 36px'}}>
        <div className="wf-grid">
          {filtered.map(w => <WorkflowCard key={w.id} wf={w} onOpen={setSelected}/>)}
        </div>
        {filtered.length === 0 && (
          <div className="empty" style={{padding: 80}}>
            <span className="mono faint" style={{letterSpacing: '0.16em', textTransform: 'uppercase'}}>No workflows match this query</span>
          </div>
        )}
      </div>
    </div>
  );
}

window.Workflows = Workflows;
window.WORKFLOWS = WORKFLOWS;
window.WORKFLOW_CATEGORIES = WORKFLOW_CATEGORIES;
window.WORKFLOW_STATUS = WORKFLOW_STATUS;
window.formatDuration = formatDuration;
