// ============================================================
// DEMIURGE — PROBLEM AGITATION + LIVE COMMAND CENTER PREVIEW
// ============================================================

const ProblemSection = () => {
  const oldway = [
    { lbl: 'Headcount', v: 'Hire · onboard · train · re-hire' },
    { lbl: 'Tempo',     v: '40 hrs / week, with breaks' },
    { lbl: 'Speed-to-lead', v: '8h · 14h · sometimes never' },
    { lbl: 'Follow-up', v: 'Whoever remembers' },
    { lbl: 'Coverage',  v: 'Mon–Fri · business hours' },
    { lbl: 'Scaling',   v: 'Linear — and you pay the salary' }
  ];
  const newway = [
    { lbl: 'Headcount', v: 'Deploy · once. Operators don’t quit.' },
    { lbl: 'Tempo',     v: '24 / 7 / 365 · concurrent at scale' },
    { lbl: 'Speed-to-lead', v: 'Sub-30-seconds · every channel' },
    { lbl: 'Follow-up', v: 'Programmed cadence · 547 days deep' },
    { lbl: 'Coverage',  v: 'Always-on · in 31 languages' },
    { lbl: 'Scaling',   v: 'Flat fee — operators don’t multiply' }
  ];
  return (
    <section className="lp-section" id="problem">
      <div className="lp">
        <div style={{maxWidth: 820}}>
          <div className="lp-eyebrow">/ 04 · The bottleneck</div>
          <h2 className="lp-h2" style={{marginTop: 18}}>
            Growth breaks when<br/>
            <em className="lp-brass">humans become bottlenecks</em>.
          </h2>
          <p className="lp-lede" style={{marginTop: 22, fontSize: 16.5}}>
            Every lead lost to a slow response. Every campaign that never shipped. Every customer call
            that rang out at 6:03 PM. The leaks aren’t in your strategy — they’re in the gap between
            human capacity and the speed the market now demands.
          </p>
        </div>

        <div className="lp-vs">
          <div className="lp-vs-side old">
            <div className="lp-vs-tag">/ The old way</div>
            <div className="lp-vs-h">Hire. Manage. Wait.</div>
            <ul className="lp-vs-list">
              {oldway.map((r, i) => (
                <li key={i}>
                  <span className="lp-vs-lbl">{r.lbl}</span>
                  <span className="lp-vs-v">{r.v}</span>
                </li>
              ))}
            </ul>
            <div className="lp-vs-foot">
              <span className="lp-vs-leak">Estimated revenue leak</span>
              <span className="lp-vs-leak-v">£12,400 / mo</span>
            </div>
          </div>

          <div className="lp-vs-arrow">
            <svg viewBox="0 0 80 200" xmlns="http://www.w3.org/2000/svg">
              <defs>
                <linearGradient id="vs-arrow" x1="0%" x2="100%">
                  <stop offset="0%" stopColor="#8a6a2e"/>
                  <stop offset="100%" stopColor="#e8c98a"/>
                </linearGradient>
              </defs>
              <line x1="0" y1="100" x2="64" y2="100" stroke="url(#vs-arrow)" strokeWidth="1.4"/>
              <path d="M 60 92 L 78 100 L 60 108 Z" fill="#e8c98a"/>
              <text x="40" y="84" fill="#c9a674" fontSize="9" fontFamily="Geist Mono" textAnchor="middle" letterSpacing="2">REPLATFORM</text>
            </svg>
          </div>

          <div className="lp-vs-side new">
            <div className="lp-vs-tag">/ The Demiurge way</div>
            <div className="lp-vs-h">Deploy. Watch. Compound.</div>
            <ul className="lp-vs-list">
              {newway.map((r, i) => (
                <li key={i}>
                  <span className="lp-vs-lbl">{r.lbl}</span>
                  <span className="lp-vs-v">{r.v}</span>
                </li>
              ))}
            </ul>
            <div className="lp-vs-foot">
              <span className="lp-vs-leak">Avg recovered revenue</span>
              <span className="lp-vs-leak-v gain">+£47,200 / mo</span>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

// ============================================================
// LIVE COMMAND CENTER PREVIEW
// Embedded mini-dashboard recreating the console aesthetic.
// ============================================================

const LiveSparkline = ({ data, color = '#4be8ff' }) => {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = max - min || 1;
  const pts = data.map((v, i) => `${(i / (data.length - 1)) * 100},${100 - ((v - min) / range) * 100}`).join(' ');
  return (
    <svg viewBox="0 0 100 100" preserveAspectRatio="none" style={{width: '100%', height: '100%'}}>
      <defs>
        <linearGradient id={`spk-${color.slice(1)}`} x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor={color} stopOpacity="0.3"/>
          <stop offset="100%" stopColor={color} stopOpacity="0"/>
        </linearGradient>
      </defs>
      <polygon points={`0,100 ${pts} 100,100`} fill={`url(#spk-${color.slice(1)})`}/>
      <polyline points={pts} fill="none" stroke={color} strokeWidth="1.4" vectorEffect="non-scaling-stroke"/>
    </svg>
  );
};

const useTickingHistory = (initial, range = 4) => {
  const [hist, setHist] = React.useState(() => {
    return Array.from({length: 28}, (_, i) => initial + Math.sin(i * 0.4) * range + (Math.random() - 0.5) * range * 0.3);
  });
  React.useEffect(() => {
    const t = setInterval(() => {
      setHist(h => [...h.slice(1), h[h.length-1] + (Math.random() - 0.4) * range * 0.6]);
    }, 1400);
    return () => clearInterval(t);
  }, [range]);
  return hist;
};

const LiveActivityFeed = () => {
  const seeds = React.useMemo(() => [
    { t: '00:02', dot: 'ok',   actor: 'ATLAS',    obj: 'booked', detail: 'discovery call · Acme Dental · Tue 14:30' },
    { t: '00:08', dot: 'cool', actor: 'HERMES',   obj: 'answered', detail: 'inbound · +44 7700 · transferred to Vesta' },
    { t: '00:14', dot: 'ok',   actor: 'CALLIOPE', obj: 'shipped', detail: 'Q2 campaign · 4 variants · IG + LinkedIn' },
    { t: '00:22', dot: 'cool', actor: 'VESTA',    obj: 'scored', detail: 'lead 8c4f12 · ICP fit 0.94 · routed to Atlas' },
    { t: '00:31', dot: 'warn', actor: 'ORION',    obj: 'paused', detail: 'creative · IG-EN-04 · CPM > threshold' },
    { t: '00:38', dot: 'ok',   actor: 'IRIS',     obj: 'resolved', detail: 'ticket #2871 · refund · CSAT pending' },
    { t: '00:44', dot: 'cool', actor: 'ATLAS',    obj: 'reached', detail: 'cadence 3/8 · 142 prospects · 4 replies' }
  ], []);
  const [items, setItems] = React.useState(seeds);
  React.useEffect(() => {
    const t = setInterval(() => {
      setItems(curr => {
        const next = [...curr];
        const head = next.shift();
        next.push({ ...head, t: `00:${String(Math.floor(Math.random() * 60)).padStart(2, '0')}` });
        return next;
      });
    }, 2800);
    return () => clearInterval(t);
  }, []);
  const dotColor = { ok: '#5dffb0', cool: '#8b6bff', warn: '#ffb14b' };
  return (
    <div className="lcc-feed">
      {items.map((it, i) => (
        <div className="lcc-feed-item" key={`${it.actor}-${i}`}>
          <span className="lcc-feed-time">{it.t}</span>
          <span className="lcc-feed-dot" style={{background: dotColor[it.dot], boxShadow: `0 0 6px ${dotColor[it.dot]}`}}></span>
          <span className="lcc-feed-msg">
            <span className="lcc-actor">{it.actor}</span>{' '}
            <span style={{color: '#b8bccf'}}>{it.obj}</span>{' '}
            <span className="lcc-feed-detail">{it.detail}</span>
          </span>
        </div>
      ))}
    </div>
  );
};

const LiveCommandCenter = () => {
  const meetings = useTickingHistory(28, 6);
  const pipeline = useTickingHistory(54, 8);
  const ops = useTickingHistory(72, 4);
  return (
    <section className="lp-section" id="live">
      <div className="lp">
        <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', gap: 48, flexWrap: 'wrap'}}>
          <div style={{maxWidth: 820}}>
            <div className="lp-eyebrow">/ 05 · Command center</div>
            <h2 className="lp-h2" style={{marginTop: 18}}>
              Watch your business<br/>
              <em className="lp-brass">operate itself</em>.
            </h2>
          </div>
          <div style={{display: 'flex', flexDirection: 'column', gap: 14, maxWidth: 380}}>
            <p className="lp-lede" style={{fontSize: 15.5, maxWidth: 380, margin: 0}}>
              Every action across every operator, streamed live to a single console. The whole organism
              under glass, in one view, with the ability to intervene.
            </p>
            <a href="Demiurge Console.html" target="_blank" rel="noopener" className="lp-btn primary" style={{alignSelf: 'flex-start'}}>
              Enter command center
              <svg className="arrow" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2"><path d="M5 12h14M13 6l6 6-6 6"/></svg>
            </a>
          </div>
        </div>

        <div className="lcc-shell">
          <div className="corner tl"></div>
          <div className="corner tr"></div>
          <div className="corner bl"></div>
          <div className="corner br"></div>
          <div className="lcc-coord">[ DMG/CONSOLE · LIVE PREVIEW ]</div>
          <div className="lcc-coord-br">38.7142°N · 122.4194°W</div>

          {/* Top bar */}
          <div className="lcc-top">
            <div className="lcc-top-l">
              <div className="lcc-mark">
                <svg viewBox="0 0 28 28">
                  <defs><radialGradient id="lcc-mark" cx="35%" cy="35%"><stop offset="0%" stopColor="#fff"/><stop offset="50%" stopColor="#8b6bff"/><stop offset="100%" stopColor="#1e1455"/></radialGradient></defs>
                  <circle cx="14" cy="14" r="10" fill="url(#lcc-mark)"/>
                  <ellipse cx="14" cy="14" rx="13" ry="3.5" fill="none" stroke="#4be8ff" strokeWidth="0.8" transform="rotate(-22 14 14)"/>
                </svg>
              </div>
              <div>
                <div className="lcc-brand">Demiurge <em>Console</em></div>
                <div className="lcc-crumbs">/ workspace · acme-dental · live</div>
              </div>
            </div>
            <div className="lcc-top-r">
              <span className="lcc-pill ok">● 6 operators online</span>
              <span className="lcc-pill">14:32 GMT</span>
            </div>
          </div>

          {/* KPI row */}
          <div className="lcc-kpi-row">
            <div className="lcc-kpi">
              <div className="lcc-kpi-l">/ MEETINGS BOOKED</div>
              <div className="lcc-kpi-v">241 <span className="d">+18 today</span></div>
              <div className="lcc-kpi-spk"><LiveSparkline data={meetings} color="#4be8ff"/></div>
            </div>
            <div className="lcc-kpi">
              <div className="lcc-kpi-l">/ PIPELINE INFLUENCED</div>
              <div className="lcc-kpi-v">£1.84M <span className="d">+£42k today</span></div>
              <div className="lcc-kpi-spk"><LiveSparkline data={pipeline} color="#8b6bff"/></div>
            </div>
            <div className="lcc-kpi">
              <div className="lcc-kpi-l">/ OPERATOR THROUGHPUT</div>
              <div className="lcc-kpi-v">14,802 <span className="d">actions / sec</span></div>
              <div className="lcc-kpi-spk"><LiveSparkline data={ops} color="#e8c98a"/></div>
            </div>
            <div className="lcc-kpi">
              <div className="lcc-kpi-l">/ TRIAL → CLIENT</div>
              <div className="lcc-kpi-v">87% <span className="d">90d cohort</span></div>
              <div className="lcc-kpi-bar">
                <div className="lcc-kpi-bar-fill" style={{width: '87%'}}></div>
              </div>
            </div>
          </div>

          <div className="lcc-grid">
            {/* Live feed */}
            <div className="lcc-card">
              <div className="lcc-card-hd">
                <span>OPERATOR · LIVE LOG</span>
                <span className="lcc-mono dim">streaming · 14:32:18Z</span>
              </div>
              <LiveActivityFeed/>
            </div>
            {/* Operators status */}
            <div className="lcc-card">
              <div className="lcc-card-hd">
                <span>WORKFORCE · STATUS</span>
                <span className="lcc-mono dim">6 / 6 online</span>
              </div>
              <div className="lcc-ops">
                {[
                  { n: 'Atlas',   r: 'Lead Generation', q: 142, c: 12, hue: '#4be8ff' },
                  { n: 'Hermes',  r: 'Phone Agent',     q: 0,   c: 84, hue: '#5dffb0' },
                  { n: 'Calliope',r: 'Content',         q: 18,  c: 4,  hue: '#ff7ad9' },
                  { n: 'Vesta',   r: 'Qualification',   q: 312, c: 47, hue: '#8b6bff' },
                  { n: 'Orion',   r: 'Ad Optimisation', q: 0,   c: 8,  hue: '#e8c98a' },
                  { n: 'Iris',    r: 'Support',         q: 24,  c: 6,  hue: '#4be8ff' }
                ].map((op, i) => (
                  <div className="lcc-op" key={i}>
                    <div className="lcc-op-name">
                      <span className="lcc-op-pip" style={{background: op.hue, boxShadow: `0 0 6px ${op.hue}`}}></span>
                      <span className="lcc-op-n">{op.n}</span>
                      <span className="lcc-op-r">{op.r}</span>
                    </div>
                    <div className="lcc-op-bar">
                      <div className="lcc-op-bar-fill" style={{width: `${Math.min(100, (op.c / 100) * 100 + 20)}%`, background: op.hue}}></div>
                    </div>
                    <div className="lcc-op-stat">
                      <span>{op.q} queued</span>
                      <span style={{color: op.hue}}>{op.c} active</span>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
};

window.ProblemSection = ProblemSection;
window.LiveCommandCenter = LiveCommandCenter;
