// ============================================================
// DEMIURGE — WORKFLOW VISUALIZATION + COMPARISON
// Animated live-feel automation canvas.
// ============================================================

const NODE_LIB = [
  { id: 'sig',   x: 60,  y: 80,  w: 200, label: 'Signal · Inbound lead',     kind: 'TRIGGER', agent: 'Artemis', body: [['Source', 'paid · google'], ['Score', '0.92']], status: 'fired' },
  { id: 'enr',   x: 320, y: 80,  w: 200, label: 'Enrich & qualify',          kind: 'STEP',    agent: 'Iris',    body: [['ICP fit', '92%'], ['Budget', '$28k']], status: 'running' },
  { id: 'rout',  x: 580, y: 80,  w: 200, label: 'Route to specialist',       kind: 'DECISION', agent: 'Iris',    body: [['Branch', 'enterprise'], ['Latency', '38ms']], status: 'done' },
  { id: 'reach', x: 60,  y: 240, w: 200, label: 'Personalized outreach',     kind: 'ACTION',  agent: 'Atlas',   body: [['Channel', 'email + sms'], ['Variant', 'C-3']], status: 'running' },
  { id: 'reply', x: 320, y: 240, w: 200, label: 'Reply received',            kind: 'TRIGGER', agent: 'Hermes',  body: [['Sentiment', 'positive'], ['Intent', 'demo']], status: 'fired' },
  { id: 'book',  x: 580, y: 240, w: 200, label: 'Book discovery call',       kind: 'ACTION',  agent: 'Hermes',  body: [['Slot', 'Tue 2:30p'], ['Calendar', 'confirmed']], status: 'done' },
  { id: 'prep',  x: 60,  y: 400, w: 200, label: 'Brief & research',          kind: 'STEP',    agent: 'Iris',    body: [['Sources', '14 docs'], ['Pages', '83']], status: 'done' },
  { id: 'meet',  x: 320, y: 400, w: 200, label: 'Live transcribe & cue',     kind: 'STEP',    agent: 'Mercury', body: [['Duration', '00:38:42'], ['Cues sent', '7']], status: 'running' },
  { id: 'quote', x: 580, y: 400, w: 200, label: 'Generate quote',            kind: 'ACTION',  agent: 'Midas',   body: [['Margin', '74%'], ['Discount', 'tier-2']], status: 'queued' }
];

const EDGES = [
  ['sig', 'enr'], ['enr', 'rout'], ['rout', 'reach'],
  ['reach', 'reply'], ['reply', 'book'], ['book', 'prep'],
  ['prep', 'meet'], ['meet', 'quote']
];

const WorkflowNode = ({ n, onHover }) => {
  const statusColor = {
    running: '#4be8ff',
    fired: '#5dffb0',
    done: '#8b6bff',
    queued: '#8388a8'
  }[n.status];
  return (
    <div
      style={{
        position: 'absolute',
        left: n.x, top: n.y,
        width: n.w,
        background: 'linear-gradient(180deg, rgba(255,255,255,0.04), rgba(255,255,255,0.005)), rgba(7,9,26,0.85)',
        border: `1px solid ${n.status === 'running' ? 'rgba(75,232,255,0.4)' : 'rgba(255,255,255,0.1)'}`,
        borderRadius: 4,
        overflow: 'hidden',
        backdropFilter: 'blur(12px)',
        boxShadow: n.status === 'running' ? '0 0 32px rgba(75,232,255,0.2)' : '0 8px 24px rgba(0,0,0,0.4)',
        transition: 'all 0.3s',
        zIndex: 2
      }}
      onMouseEnter={() => onHover(n.id)}
    >
      <div style={{
        padding: '8px 12px',
        display: 'flex', alignItems: 'center', gap: 8,
        borderBottom: '1px solid rgba(255,255,255,0.06)',
        background: 'rgba(0,0,0,0.3)'
      }}>
        <div style={{
          width: 6, height: 6, borderRadius: '50%',
          background: statusColor,
          boxShadow: `0 0 6px ${statusColor}`,
          animation: n.status === 'running' ? 'pulse 1.4s infinite' : 'none'
        }}/>
        <span style={{
          fontFamily: 'Geist Mono',
          fontSize: 9,
          color: '#c9a674',
          letterSpacing: 1.6,
          textTransform: 'uppercase'
        }}>{n.kind}</span>
        <span style={{
          marginLeft: 'auto',
          fontFamily: 'Geist Mono',
          fontSize: 9,
          color: '#8388a8',
          letterSpacing: 1.2,
          textTransform: 'uppercase'
        }}>{n.agent}</span>
      </div>
      <div style={{ padding: '10px 12px' }}>
        <div style={{ color: '#f5f1e6', fontSize: 13, marginBottom: 8 }}>{n.label}</div>
        {n.body.map(([k, v], i) => (
          <div key={i} style={{
            display: 'flex', justifyContent: 'space-between',
            fontFamily: 'Geist Mono', fontSize: 10, marginTop: 3
          }}>
            <span style={{color: '#4a4f6b'}}>{k}</span>
            <span style={{color: '#b8bccf'}}>{v}</span>
          </div>
        ))}
      </div>
      {/* Ports */}
      <div style={{
        position: 'absolute', right: -5, top: 18,
        width: 10, height: 10, borderRadius: '50%',
        background: '#03040c', border: '1px solid #4be8ff'
      }}/>
      <div style={{
        position: 'absolute', left: -5, top: 18,
        width: 10, height: 10, borderRadius: '50%',
        background: '#03040c', border: '1px solid rgba(255,255,255,0.2)'
      }}/>
    </div>
  );
};

const WorkflowEdges = ({ tick }) => {
  // Curved edges between nodes
  const lookup = Object.fromEntries(NODE_LIB.map(n => [n.id, n]));
  return (
    <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', zIndex: 1, overflow: 'visible' }}>
      <defs>
        <linearGradient id="wf-edge" x1="0%" x2="100%">
          <stop offset="0%" stopColor="rgba(75, 232, 255, 0.4)"/>
          <stop offset="100%" stopColor="rgba(139, 107, 255, 0.6)"/>
        </linearGradient>
        <radialGradient id="wf-pulse">
          <stop offset="0%" stopColor="#4be8ff"/>
          <stop offset="100%" stopColor="rgba(75, 232, 255, 0)"/>
        </radialGradient>
      </defs>
      {EDGES.map(([a, b], i) => {
        const na = lookup[a], nb = lookup[b];
        const x1 = na.x + na.w + 5, y1 = na.y + 23;
        const x2 = nb.x - 5, y2 = nb.y + 23;
        const midX = (x1 + x2) / 2;
        const path = `M ${x1} ${y1} C ${midX} ${y1}, ${midX} ${y2}, ${x2} ${y2}`;
        // Pulse particle position
        const phase = ((tick / 60) + i * 0.15) % 1;
        return (
          <g key={i}>
            <path d={path} fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="1" strokeDasharray="2 4"/>
            <path d={path} fill="none" stroke="url(#wf-edge)" strokeWidth="1.2" opacity="0.6" pathLength="1" strokeDasharray="0.2 0.8" strokeDashoffset={-phase}/>
            {/* moving particle */}
            <circle r="3.5" fill="url(#wf-pulse)">
              <animateMotion dur="3.5s" repeatCount="indefinite" path={path} begin={`-${i * 0.5}s`}/>
            </circle>
          </g>
        );
      })}
    </svg>
  );
};

const WorkflowSection = () => {
  const [tick, setTick] = React.useState(0);
  React.useEffect(() => {
    let raf;
    const loop = () => { setTick(t => t + 1); raf = requestAnimationFrame(loop); };
    raf = requestAnimationFrame(loop);
    return () => cancelAnimationFrame(raf);
  }, []);

  return (
    <section className="lp-section" id="workflows">
      <div className="lp">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 48, flexWrap: 'wrap'}}>
          <div style={{maxWidth: 720}}>
            <div className="lp-eyebrow">/ 07 · Live operations</div>
            <h2 className="lp-h2" style={{marginTop: 18}}>
              The work happens<br/>
              <em className="lp-brass">while you sleep</em>.
            </h2>
          </div>
          <p className="lp-lede" style={{maxWidth: 380, fontSize: 15.5}}>
            A single inbound signal triggers a cascade across the team. No drag-and-drop builders.
            No flowchart maintenance. The OS composes the workflow itself.
          </p>
        </div>

        <div className="lp-workflow">
          <div className="corner tl"></div>
          <div className="corner tr"></div>
          <div className="corner bl"></div>
          <div className="corner br"></div>
          <div className="lp-workflow-coord">[ DMG/OPS · TRACE · LIVE ]</div>
          <div className="lp-workflow-cap">SAMPLE CASE · ENTERPRISE LEAD · $28K MRR</div>

          <div style={{ position: 'relative', height: 540, width: '100%' }}>
            <WorkflowEdges tick={tick}/>
            {NODE_LIB.map(n => <WorkflowNode key={n.id} n={n} onHover={() => {}}/>)}

            {/* Floating telemetry overlays */}
            <div style={{
              position: 'absolute', top: 10, right: 10,
              padding: '10px 14px',
              background: 'rgba(3,4,12,0.7)',
              border: '1px solid rgba(75,232,255,0.25)',
              borderRadius: 3,
              fontFamily: 'Geist Mono',
              fontSize: 10,
              color: '#8388a8',
              letterSpacing: 1.2,
              textTransform: 'uppercase',
              backdropFilter: 'blur(8px)',
              zIndex: 3
            }}>
              <div style={{display: 'flex', gap: 16, alignItems: 'center'}}>
                <span><span style={{color: '#4a4f6b'}}>elapsed</span> <span style={{color:'#4be8ff'}}>00:02:14</span></span>
                <span><span style={{color: '#4a4f6b'}}>active</span> <span style={{color:'#5dffb0'}}>4</span></span>
                <span><span style={{color: '#4a4f6b'}}>queued</span> <span style={{color:'#e8c98a'}}>1</span></span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// COMPARISON TABLE
// ============================================================

const ComparisonSection = () => {
  const rows = [
    ['Setup time',          '7 days',            '6–12 months',              '4–8 weeks',           'Weeks of prompt work'],
    ['Total cost / yr',     '£28,800',           '£420K+ (5 FTEs)',          '£120K+',              '£24K + your time'],
    ['Coverage',            '24 / 7 / 365',      '40 hrs / wk / FTE',        'Business hours',      'When you remember'],
    ['Domain expertise',    'Industry-tuned',    'Hire-dependent',           'Generalist',          'You teach it'],
    ['Accountability',      'SLA on contract',   'Manager + reviews',        'Account manager',     'Yours alone'],
    ['Scaling cost',        'Flat',              'Linear w/ headcount',      'Linear w/ retainer',  'Engineer-hours']
  ];
  const yes = (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4"><path d="M5 12l5 5L20 7"/></svg>
  );
  return (
    <section className="lp-section" id="compare">
      <div className="lp">
        <div style={{maxWidth: 820}}>
          <div className="lp-eyebrow">/ 08 · The unit economics</div>
          <h2 className="lp-h2" style={{marginTop: 18}}>
            Why operators are<br/>
            <em className="lp-brass">re-platforming</em> their P&amp;L.
          </h2>
        </div>
        <div className="lp-compare">
          <div className="lp-compare-row hd">
            <div className="c"></div>
            <div className="c us">Demiurge</div>
            <div className="c">In-house team</div>
            <div className="c">Agency</div>
            <div className="c" style={{borderRight: 'none'}}>DIY tools</div>
          </div>
          {rows.map((r, i) => (
            <div className="lp-compare-row" key={i}>
              <div className="c label">{r[0]}</div>
              <div className="c us"><span style={{color: '#5dffb0'}}>{yes}</span>{r[1]}</div>
              <div className="c"><span className="n">{r[2]}</span></div>
              <div className="c"><span className="n">{r[3]}</span></div>
              <div className="c" style={{borderRight: 'none'}}><span className="n">{r[4]}</span></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
};

window.WorkflowSection = WorkflowSection;
window.ComparisonSection = ComparisonSection;
