// Command Center — overview dashboard with onboarding, action center, learning, goals
function Dashboard({ onNav, settings }) {
  const liveAgents = AGENTS.filter(a => a.status === 'live').length;
  const totalQueue = AGENTS.reduce((s, a) => s + a.queue, 0);
  const todaySpend = AGENTS.reduce((s, a) => s + a.cost, 0);
  const [showOnboarding, setShowOnboarding] = React.useState(true);

  return (
    <div>
      <TickerStrip/>

      <div className="page-hd">
        <div className="page-hd-l">
          <div className="page-eyebrow">CMD-CTR · DEMIURGE/EXT · SECTOR 7E32 · <span className="pip" style={{ verticalAlign: 'middle', width: 5, height: 5 }}/> LIVE</div>
          <h1 className="page-title">Good afternoon, <em>Reza</em>.</h1>
          <div className="page-sub">8 agents in flight · 41 meetings booked since 00:00 GMT · Atlas converting 41% above target — consider widening its sequence cap.</div>
          <div className="telemetry" style={{ marginTop: 10 }}>
            <span><span className="lbl">UPTIME</span> <span className="ok">99.98%</span></span>
            <span><span className="lbl">P95</span> <span className="cy">312ms</span></span>
            <span><span className="lbl">ERR</span> <span className="ok">0.04%</span></span>
            <span><span className="lbl">QUEUE</span> <span className="val">{totalQueue.toLocaleString()}</span></span>
            <span><span className="lbl">CPU</span> <span className="vi">34%</span></span>
            <span><span className="lbl">x402</span> <span className="ok">£18.42/24H</span></span>
            <span><span className="lbl">ALERTS</span> <span className="warn">2</span></span>
          </div>
        </div>
        <div className="page-hd-r">
          <div className="segmented">
            <button>24H</button>
            <button className="active">7D</button>
            <button>30D</button>
            <button>QTR</button>
          </div>
          <button className="btn" onClick={() => window.toast('Syncing…', 'info', 'Pulling latest from all connected systems')}><Icon.Refresh className="icon"/>Sync</button>
          <button className="btn primary" onClick={() => window.runAction('newAutomation')}><Icon.Plus className="icon"/>New automation</button>
        </div>
      </div>

      {showOnboarding && <GetStartedCard onDismiss={() => setShowOnboarding(false)} onNav={onNav}/>}

      <div style={{ padding: '20px 24px 0', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <KpiBlock label="MEETINGS · 7D" val="241" delta="+34%" stream={fakeStream(1, 14, 18, 12)}/>
        <KpiBlock label="PIPELINE INFLUENCED" val="1.84" unit="$M" delta="+12%" stream={fakeStream(2, 14, 80, 25)}/>
        <KpiBlock label="AGENT SPEND · TODAY" val={todaySpend.toFixed(0)} unit="$" delta="-8%" deltaGood stream={fakeStream(3, 14, 40, 14)}/>
        <KpiBlock label="QUEUE DEPTH" val={totalQueue.toLocaleString()} delta="+148" deltaBad stream={fakeStream(4, 14, 1400, 400)}/>
      </div>

      <div style={{ padding: '14px 24px 0', display: 'grid', gridTemplateColumns: '380px 1fr 1fr', gap: 14 }}>
        <div className="panel glow frame">
          <span className="coord">NW · ORBITAL TELEMETRY · 7E32-α</span>
          <span className="br-bl"></span><span className="br-br"></span>
          <span className="coord-br">PING 4s · 8 NODES</span>
          <div className="panel-hd">
            <h3><span className="tag live" style={{ padding: '1px 6px' }}>ORBIT</span>Operator constellation</h3>
            <span className="panel-meta">{liveAgents}/{AGENTS.length}</span>
          </div>
          <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14 }}>
            <CosmosDial size={260}/>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8, width: '100%' }}>
              <DialStat label="CPU" val="34%" color="var(--cyan)"/>
              <DialStat label="P95" val="312ms" color="var(--violet)"/>
              <DialStat label="ERR" val="0.04%" color="var(--good)"/>
            </div>
          </div>
        </div>

        <div className="panel frame">
          <span className="coord violet">N · OPERATORS · 24H</span>
          <span className="br-bl"></span><span className="br-br"></span>
          <div className="panel-hd">
            <h3>Operators · last 24h</h3>
            <button className="btn ghost sm" onClick={() => onNav('agents')}>View all <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
          </div>
          <div>
            <table className="dem">
              <thead>
                <tr><th>Agent</th><th>State</th><th>Throughput</th><th>Replied</th><th>Booked</th><th>Cost</th></tr>
              </thead>
              <tbody>
                {AGENTS.slice(0, 6).map(a => (
                  <tr key={a.id} onClick={() => onNav('agents', a.id)}>
                    <td>
                      <div className="row" style={{ gap: 8 }}>
                        <span className="mono gradient-text" style={{ fontSize: 11, fontWeight: 600 }}>{a.name.toUpperCase()}</span>
                        <span className="faint mono" style={{ fontSize: 10 }}>{a.role}</span>
                      </div>
                    </td>
                    <td><StatusTag status={a.status}/></td>
                    <td><Sparkline data={fakeStream(a.id.charCodeAt(1), 18, 14, 10)} w={70} h={18} gradient/></td>
                    <td className="num">{a.replied.toLocaleString()}</td>
                    <td className="num" style={{ color: a.booked > 0 ? 'var(--cyan)' : 'var(--text-faint)' }}>{a.booked || '—'}</td>
                    <td className="num">£{a.cost.toFixed(2)}</td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>

        <div className="panel frame">
          <span className="coord">NE · EVENT FEED · LIVE</span>
          <span className="br-bl"></span><span className="br-br"></span>
          <div className="panel-hd">
            <h3><span className="tag live">LIVE</span>Event stream</h3>
            <button className="btn ghost sm">Pause</button>
          </div>
          <div style={{ maxHeight: 488, overflowY: 'auto' }}>
            {FEED.map((f, i) => (
              <div key={i} className="feed-item">
                <span className="feed-time mono">{f.t}</span>
                <span className={`feed-dot ${f.dot}`}/>
                <span className="feed-msg">
                  <span className="actor">{f.actor}</span>{' '}{f.msg}{' '}<span className="obj">{f.obj}</span>
                </span>
                <span className="feed-meta">{f.meta}</span>
              </div>
            ))}
          </div>
        </div>
      </div>

      <div style={{ padding: '14px 24px 0', display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14 }}>
        <div className="panel">
          <div className="panel-hd">
            <h3>Acquisition funnel · 7D</h3>
            <button className="btn ghost sm" onClick={() => onNav('funnels')}>Open funnel <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
          </div>
          <div className="panel-body">
            <div className="funnel-bar">
              {FUNNEL.map((s, i) => {
                const hPct = (s.val / FUNNEL[0].val) * 100;
                return (
                  <div key={s.name} className="funnel-step" title={`£${s.name}: ${s.val.toLocaleString()}`}>
                    <div className="step-bar" style={{
                      height: `£${Math.max(4, hPct)}%`,
                      background: `linear-gradient(180deg, hsl(${190 + i * 12}, 90%, 65%) 0%, hsl(${250 + i * 8}, 85%, 60%) 100%)`,
                      boxShadow: `0 0 20px hsla(${220 + i * 10}, 85%, 60%, 0.4)`,
                    }}/>
                  </div>
                );
              })}
            </div>
            <div style={{ display: 'grid', gridTemplateColumns: `repeat(${FUNNEL.length}, 1fr)`, gap: 4, marginTop: 14 }}>
              {FUNNEL.map(s => (
                <div key={s.name} style={{ display: 'flex', flexDirection: 'column', gap: 2, padding: '0 2px' }}>
                  <div style={{ fontSize: 11, color: 'var(--text)' }}>{s.name}</div>
                  <div className="mono" style={{ fontSize: 12, color: 'var(--cyan)' }}>{s.val >= 1000 ? (s.val / 1000).toFixed(1) + 'k' : s.val}</div>
                  <div className="mono" style={{ fontSize: 10, color: 'var(--text-faint)' }}>{s.pct}%</div>
                </div>
              ))}
            </div>
          </div>
        </div>

        <GoalsCard/>
      </div>

      <div style={{ padding: '14px 24px 0', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14 }}>
        <ActionCenter onNav={onNav}/>
        <div className="panel">
          <div className="panel-hd">
            <h3>Activity heatmap</h3>
            <span className="panel-meta">7d × 24h · GMT</span>
          </div>
          <div className="panel-body">
            <Heatmap rows={7} cols={24}/>
            <div className="row faint mono" style={{ fontSize: 9, marginTop: 10, justifyContent: 'space-between' }}>
              <span>MON</span><span>TUE</span><span>WED</span><span>THU</span><span>FRI</span><span>SAT</span><span>SUN</span>
            </div>
          </div>
        </div>
        <LearningCard/>
      </div>

      <div style={{ padding: '14px 24px 24px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
        <div className="panel">
          <div className="panel-hd">
            <h3>Channel performance · 7D</h3>
            <span className="panel-meta">£16.6k spend → 313 booked</span>
          </div>
          <div className="panel-body">
            <div style={{ display: 'grid', gap: 12 }}>
              {[
                { name: 'Outbound email', spend: 0, booked: 112, color: '#4be8ff', chip: 'email' },
                { name: 'Meta ads', spend: 12480, booked: 188, color: '#ff7ad9', chip: 'paid' },
                { name: 'Google brand', spend: 4120, booked: 64, color: '#8b6bff', chip: 'paid' },
                { name: 'Inbound web', spend: 0, booked: 42, color: '#5dffb0', chip: 'auto' },
                { name: 'SMS', spend: 32, booked: 12, color: '#ffb14b', chip: 'sms' },
              ].map(c => {
                const maxB = 200;
                return (
                  <div key={c.name} style={{ display: 'grid', gridTemplateColumns: '150px 1fr 80px 60px', gap: 14, alignItems: 'center', fontSize: 12 }}>
                    <span className="row">
                      <span className={`channel-chip ${c.chip}`}>{c.chip}</span>
                      {c.name}
                    </span>
                    <div className="bar-track">
                      <div className="bar-fill flat" style={{ width: `£${(c.booked / maxB) * 100}%`, background: c.color, boxShadow: `0 0 8px ${c.color}66` }}/>
                    </div>
                    <span className="mono dim" style={{ textAlign: 'right' }}>£{c.spend.toLocaleString()}</span>
                    <span className="mono tnum" style={{ textAlign: 'right' }}>{c.booked}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        <div className="panel">
          <div className="panel-hd">
            <h3>Operator health</h3>
            <span className="tag live">8 monitored</span>
          </div>
          <div>
            <table className="dem">
              <thead>
                <tr><th>Agent</th><th>Health</th><th>Suggested action</th><th></th></tr>
              </thead>
              <tbody>
                {[
                  { name: 'Atlas',    state: 'healthy',  action: 'Widen daily cap (+200)',                         cta: 'Apply',  go: () => window.toast('Cap widened · Atlas +200/day', 'ok', 'Effective immediately') },
                  { name: 'Nyx',      state: 'degraded', action: 'Clearbit rate-limited · add Apollo fallback',     cta: 'Fix',    go: () => window.runAction('connect', { name: 'Apollo (fallback)' }) },
                  { name: 'Kairos',   state: 'inactive', action: 'No runs in 7d · review playbook',                 cta: 'Review', go: () => onNav('agents') },
                  { name: 'Calliope', state: 'warning',  action: 'Spam score elevated on "Cold #2"',                cta: 'Review', go: () => window.runAction('viewLogs', { source: 'calliope · cold-2' }) },
                ].map((h, i) => {
                  const dotColor = h.state === 'healthy' ? 'var(--good)' : h.state === 'degraded' ? 'var(--danger)' : h.state === 'warning' ? 'var(--warn)' : 'var(--text-faint)';
                  return (
                    <tr key={i}>
                      <td><span className="mono gradient-text" style={{ fontSize: 11, fontWeight: 600 }}>{h.name.toUpperCase()}</span></td>
                      <td>
                        <span className="row" style={{ gap: 6 }}>
                          <span style={{ width: 6, height: 6, borderRadius: '50%', background: dotColor, boxShadow: `0 0 6px ${dotColor}` }}/>
                          <span style={{ textTransform: 'capitalize', fontSize: 12 }}>{h.state}</span>
                        </span>
                      </td>
                      <td className="dim" style={{ fontSize: 12 }}>{h.action}</td>
                      <td><button className="btn sm" data-handled="1" onClick={h.go}>{h.cta}</button></td>
                    </tr>
                  );
                })}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
}

function KpiBlock({ label, val, unit, delta, deltaGood, deltaBad, stream, onClick }) {
  const positive = delta?.startsWith('+');
  const isGood = deltaGood !== undefined ? deltaGood : positive;
  const isBad = deltaBad !== undefined ? deltaBad : !positive;
  // Auto-route by label keyword if no explicit onClick
  const route = onClick || (() => {
    const L = (label || '').toLowerCase();
    if (/meeting|booked|appoint/.test(L))         return window.demiurgeNav?.('calendar');
    if (/queue|inbox|reply/.test(L))              return window.demiurgeNav?.('inbox');
    if (/pipeline|revenue|attrib|cycle|spend|cac|engaged|projection|profit|mrr|usage|active business/.test(L)) return window.demiurgeNav?.('analytics');
    if (/agent|operator/.test(L))                 return window.demiurgeNav?.('agents');
    if (/lead/.test(L))                           return window.demiurgeNav?.('contacts');
    window.toast(`${label}`, 'info', `Current value: ${val}${unit ? ' ' + unit : ''} · ${delta}`);
  });
  return (
    <div className="kpi-block" onClick={route} style={{ cursor: 'pointer' }}>
      <div className="kpi-label">{label}</div>
      <div className="row" style={{ alignItems: 'flex-end', justifyContent: 'space-between', gap: 12 }}>
        <div className="kpi-val">
          {unit === '£' && <span className="unit">$</span>}
          {val}
          {unit && unit !== '£' && <span className="unit"> {unit}</span>}
        </div>
        <Sparkline data={stream} w={120} h={40} gradient/>
      </div>
      <div className="kpi-meta">
        <span className={`delta ${isGood ? 'up' : isBad ? 'dn' : ''}`}>{delta}</span>
        <span className="faint">vs prior 7d</span>
      </div>
    </div>
  );
}

function DialStat({ label, val, color }) {
  return (
    <div style={{
      padding: '8px 10px',
      background: 'rgba(0, 0, 0, 0.25)',
      border: '1px solid var(--border)',
      borderRadius: 6,
      display: 'flex', flexDirection: 'column', gap: 2,
    }}>
      <span className="mono faint" style={{ fontSize: 9, letterSpacing: '0.1em' }}>{label}</span>
      <span className="mono tnum" style={{ fontSize: 13, color }}>{val}</span>
    </div>
  );
}

function GetStartedCard({ onDismiss, onNav }) {
  const steps = [
    { id: 'agent',    t: 'Provision your first operator', sub: 'Pick a template or write a playbook from scratch.', done: true,  icon: 'Bolt',  cta: 'Configure', go: () => window.runAction('spinUpAgent') },
    { id: 'channels', t: 'Connect your channels',         sub: 'Gmail, SendGrid, Twilio, Meta, Google. 30s each.', done: true,  icon: 'Plug',  cta: 'Manage',    go: () => onNav?.('integrations') },
    { id: 'workflow', t: 'Launch your first workflow',    sub: 'Wire a trigger to an agent. Watch it run.',         done: false, icon: 'Flow',  cta: 'Launch',    go: () => window.runAction('deployWorkflow') },
    { id: 'goal',     t: 'Set a pipeline goal',            sub: 'Demiurge will align all agents against your target.', done: false, icon: 'Target', cta: 'Set goal',  go: () => window.toast('Goal builder open', 'info', 'Define KPI target + cadence + cohort') },
  ];
  const completed = steps.filter(s => s.done).length;
  return (
    <div style={{ padding: '14px 24px 0' }}>
      <div className="panel" style={{ background: 'linear-gradient(135deg, rgba(75, 232, 255, 0.04), rgba(139, 107, 255, 0.06), rgba(255, 122, 217, 0.04))', border: '1px solid rgba(139, 107, 255, 0.2)' }}>
        <div className="panel-hd" style={{ borderBottom: '1px solid var(--border)' }}>
          <h3>
            <span className="serif" style={{ fontSize: 18, fontStyle: 'italic' }}>Genesis</span>
            <span className="dim" style={{ fontWeight: 400, marginLeft: 8, fontSize: 12 }}>· Set up your operator stack</span>
          </h3>
          <div className="row" style={{ gap: 14 }}>
            <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)' }}>{completed}/{steps.length} complete</span>
            <div className="bar-track" style={{ width: 120 }}>
              <div className="bar-fill" style={{ width: `£${(completed / steps.length) * 100}%` }}/>
            </div>
            <button className="icon-btn" onClick={onDismiss}><Icon.X/></button>
          </div>
        </div>
        <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12 }}>
          {steps.map((s, i) => {
            const I = Icon[s.icon];
            return (
              <div key={s.id} style={{
                padding: 16,
                background: s.done ? 'rgba(93, 255, 176, 0.05)' : 'rgba(255, 255, 255, 0.025)',
                border: `1px solid ${s.done ? 'rgba(93, 255, 176, 0.2)' : 'var(--border)'}`,
                borderRadius: 'var(--radius)',
                display: 'flex', flexDirection: 'column', gap: 10,
                position: 'relative',
              }}>
                <div className="row" style={{ justifyContent: 'space-between' }}>
                  <div style={{
                    width: 32, height: 32,
                    borderRadius: 8,
                    background: s.done ? 'rgba(93, 255, 176, 0.12)' : 'linear-gradient(135deg, rgba(139, 107, 255, 0.18), rgba(75, 232, 255, 0.10))',
                    border: `1px solid ${s.done ? 'rgba(93, 255, 176, 0.3)' : 'rgba(139, 107, 255, 0.25)'}`,
                    display: 'grid', placeItems: 'center',
                    color: s.done ? 'var(--good)' : 'var(--cyan)',
                  }}>
                    {s.done ? <Icon.Check style={{ width: 16, height: 16 }}/> : <I style={{ width: 16, height: 16 }}/>}
                  </div>
                  <span className="mono faint" style={{ fontSize: 10 }}>0{i+1}</span>
                </div>
                <div>
                  <div style={{ fontSize: 13, color: 'var(--text)', marginBottom: 4 }}>{s.t}</div>
                  <div className="dim" style={{ fontSize: 11, lineHeight: 1.5 }}>{s.sub}</div>
                </div>
                {!s.done && <button className="btn sm" data-handled="1" onClick={s.go} style={{ alignSelf: 'flex-start', marginTop: 'auto' }}>{s.cta} <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>}
                {s.done && <span className="mono" style={{ fontSize: 10, color: 'var(--good)', marginTop: 'auto' }}>✓ Complete</span>}
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function ActionCenter({ onNav }) {
  const actions = [
    { p: 'urgent',      t: 'Nyx · Clearbit rate-limited',         sub: 'Add Apollo as fallback to maintain enrichment throughput.', cta: 'Configure', go: () => window.runAction('reconnect', { name: 'Apollo' }) },
    { p: 'opportunity', t: 'Promote "Founders v3" sequence',      sub: 'A/B winner, +41% replies. Calliope is waiting on you.',     cta: 'Promote',   go: () => window.toast('Promoted to all founders segment', 'ok', 'Calliope rolling out within 2 minutes') },
    { p: 'risk',        t: '"Cold #2" spam score 4.1',             sub: 'Likely to harm demiurge.com domain reputation.',            cta: 'Pause',     go: () => window.toast('Sequence paused', 'warn', 'Calliope · Cold #2 · drafts preserved') },
    { p: 'info',        t: 'May invoice ready',                    sub: '£284 in compute · 11 days early.',                          cta: 'Review',    go: () => window.demiurgeNav?.('settings') },
  ];
  return (
    <div className="panel">
      <div className="panel-hd">
        <h3><Icon.Sparkles style={{ width: 14, height: 14 }} className="gradient-text"/>Actions needed</h3>
        <span className="tag live">{actions.length} pending</span>
      </div>
      <div>
        {actions.map((a, i) => {
          const color = a.p === 'urgent' ? 'var(--danger)' : a.p === 'opportunity' ? 'var(--good)' : a.p === 'risk' ? 'var(--warn)' : 'var(--cyan)';
          return (
            <div key={i} style={{ padding: '12px 18px', borderBottom: i < actions.length - 1 ? '1px solid var(--border)' : 'none' }}>
              <div className="row" style={{ gap: 8, marginBottom: 6 }}>
                <span className="mono" style={{ fontSize: 9, color, letterSpacing: '0.14em', textTransform: 'uppercase' }}>{a.p}</span>
                <span style={{ fontSize: 13 }}>{a.t}</span>
              </div>
              <div className="dim" style={{ fontSize: 11, lineHeight: 1.5, marginBottom: 8 }}>{a.sub}</div>
              <button className="btn sm" data-handled="1" onClick={a.go}>{a.cta}</button>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function LearningCard() {
  return (
    <div className="panel">
      <div className="panel-hd">
        <h3><Icon.Book style={{ width: 14, height: 14, color: 'var(--cyan)' }}/>From Demiurge Labs</h3>
        <span className="mono faint" style={{ fontSize: 10 }}>DAILY</span>
      </div>
      <div style={{ padding: 18 }}>
        <div style={{
          height: 140,
          borderRadius: 'var(--radius)',
          background: 'linear-gradient(135deg, rgba(139, 107, 255, 0.3), rgba(75, 232, 255, 0.18), rgba(255, 122, 217, 0.15))',
          position: 'relative',
          overflow: 'hidden',
          marginBottom: 12,
          display: 'grid', placeItems: 'center',
          cursor: 'pointer',
        }}>
          <div style={{
            width: 48, height: 48,
            borderRadius: '50%',
            background: 'rgba(0, 0, 0, 0.4)',
            backdropFilter: 'blur(20px)',
            border: '1px solid rgba(255, 255, 255, 0.2)',
            display: 'grid', placeItems: 'center',
          }}>
            <Icon.Play style={{ width: 18, height: 18, color: '#fff', marginLeft: 2 }}/>
          </div>
          <div style={{ position: 'absolute', bottom: 10, left: 12, right: 12, display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <span className="tag">EP 04 · 7 MIN</span>
            <span className="mono" style={{ fontSize: 10, color: 'rgba(255,255,255,0.8)' }}>1/5 IN SERIES</span>
          </div>
        </div>
        <div style={{ fontSize: 13, marginBottom: 4 }}>Designing playbooks that don't drift</div>
        <div className="dim" style={{ fontSize: 11, lineHeight: 1.5, marginBottom: 14 }}>How to scope an operator's authority, set decision boundaries, and detect drift before it costs you.</div>
        <div className="divider"/>
        <div style={{ marginTop: 14 }}>
          <div className="mono faint" style={{ fontSize: 9, textTransform: 'uppercase', letterSpacing: '0.12em', marginBottom: 8 }}>Changelog</div>
          {[
            { d: 'May 21', t: 'New: voice agent + dialer pacing controls' },
            { d: 'May 19', t: 'Workflows now support webhook fan-out' },
            { d: 'May 17', t: 'Fixed: Slack notifications double-firing' },
          ].map((c, i) => (
            <div key={i} className="row" style={{ padding: '4px 0', fontSize: 11, gap: 12 }}>
              <span className="mono faint" style={{ minWidth: 50 }}>{c.d}</span>
              <span className="dim">{c.t}</span>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function GoalsCard() {
  const goalMRR = 50000, currentMRR = 32400;
  const goalMeetings = 400, currentMeetings = 241;
  return (
    <div className="panel">
      <div className="panel-hd">
        <h3><Icon.Target style={{ width: 14, height: 14, color: 'var(--violet)' }}/>Q2 Goals</h3>
        <span className="mono" style={{ fontSize: 10, color: 'var(--cyan)' }}>ON PACE</span>
      </div>
      <div className="panel-body" style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
        <div>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
            <span className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em' }}>Pipeline · MRR</span>
            <span className="mono dim" style={{ fontSize: 11 }}>{Math.round((currentMRR / goalMRR) * 100)}%</span>
          </div>
          <div className="row" style={{ gap: 8, marginBottom: 8, alignItems: 'baseline' }}>
            <span className="serif" style={{ fontSize: 28, color: 'var(--text)', fontStyle: 'italic' }}>£{(currentMRR / 1000).toFixed(1)}k</span>
            <span className="mono" style={{ fontSize: 12, color: 'var(--text-faint)' }}>/ ${(goalMRR / 1000)}k</span>
          </div>
          <div className="bar-track" style={{ height: 6 }}>
            <div className="bar-fill" style={{ width: `£${(currentMRR / goalMRR) * 100}%` }}/>
          </div>
          <div className="mono faint" style={{ fontSize: 10, marginTop: 6 }}>+£8.2k this week · ahead of pace by 4d</div>
        </div>
        <div>
          <div className="row" style={{ justifyContent: 'space-between', marginBottom: 8 }}>
            <span className="mono faint" style={{ fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.12em' }}>Meetings booked</span>
            <span className="mono dim" style={{ fontSize: 11 }}>{Math.round((currentMeetings / goalMeetings) * 100)}%</span>
          </div>
          <div className="row" style={{ gap: 8, marginBottom: 8, alignItems: 'baseline' }}>
            <span className="serif" style={{ fontSize: 28, color: 'var(--text)', fontStyle: 'italic' }}>{currentMeetings}</span>
            <span className="mono" style={{ fontSize: 12, color: 'var(--text-faint)' }}>/ {goalMeetings}</span>
          </div>
          <div className="bar-track" style={{ height: 6 }}>
            <div className="bar-fill cool flat" style={{ width: `£${(currentMeetings / goalMeetings) * 100}%` }}/>
          </div>
          <div className="mono faint" style={{ fontSize: 10, marginTop: 6 }}>+41 this week · Atlas leading</div>
        </div>
        <button className="btn ghost sm" data-handled="1" onClick={() => window.toast('Goal builder open', 'info', 'Edit MRR target, meetings cadence, cohort split')} style={{ alignSelf: 'flex-start' }}>Adjust goals <Icon.ChevronR className="icon" style={{ width: 12, height: 12 }}/></button>
      </div>
    </div>
  );
}

window.Dashboard = Dashboard;
window.KpiBlock = KpiBlock;

function TickerStrip() {
  const items = [
    { sym: 'ATLAS', val: '+22', dir: 'up', sub: 'booked·24h' },
    { sym: 'VESTA', val: '+88', dir: 'up', sub: 'qualified·24h' },
    { sym: 'HERMES', val: '+41', dir: 'up', sub: 'calls·24h' },
    { sym: 'CALLIOPE', val: '+312', dir: 'up', sub: 'replies' },
    { sym: 'ORION', val: '−31%', dir: 'dn', sub: 'CPA·30d' },
    { sym: 'NYX', val: 'DEG', dir: 'dn', sub: 'clearbit 429' },
    { sym: 'PIPELINE', val: '£1.84M', dir: 'up', sub: '+12%' },
    { sym: 'x402·24H', val: '£18.42', dir: 'up', sub: '1,408 txns' },
    { sym: 'USDC·BASE', val: '$1.00', dir: 'up', sub: 'peg' },
    { sym: 'ROI', val: '107×', dir: 'up', sub: '30d' },
    { sym: 'CAC', val: '£42', dir: 'up', sub: '−31%' },
    { sym: 'TRIAL→ACT', val: '87.2%', dir: 'up', sub: '+4.1pt' },
    { sym: 'INBOX', val: '3 await', dir: 'dn', sub: 'human' },
    { sym: 'WORKFLOWS', val: '8,182✓', dir: 'up', sub: '218✗' },
    { sym: 'MTD·SPEND', val: '£1,842', dir: 'up', sub: '36%·cap' },
    { sym: 'GMT', val: '14:32:08', dir: 'up', sub: 'SAT 22/05' },
  ];
  return (
    <div className="ticker" style={{
      padding: '8px 0',
      borderBottom: '1px solid var(--border)',
      background: 'rgba(0, 0, 0, 0.3)',
      position: 'relative',
    }}>
      <div className="ticker-track">
        {[...items, ...items].map((it, i) => (
          <span key={i}>
            <span className="tx-sym">{it.sym}</span>
            <span className={it.dir === 'up' ? 'tx-up' : 'tx-dn'}>
              {it.dir === 'up' ? '▲' : '▼'} {it.val}
            </span>
            <span className="tx-arrow">·</span>
            <span className="faint" style={{ fontSize: 10 }}>{it.sub}</span>
          </span>
        ))}
      </div>
      <div style={{ position: 'absolute', left: 0, top: 0, bottom: 0, width: 60, background: 'linear-gradient(90deg, var(--bg-base), transparent)', zIndex: 1, pointerEvents: 'none' }}/>
      <div style={{ position: 'absolute', right: 0, top: 0, bottom: 0, width: 60, background: 'linear-gradient(-90deg, var(--bg-base), transparent)', zIndex: 1, pointerEvents: 'none' }}/>
    </div>
  );
}

window.TickerStrip = TickerStrip;
