// Anologe — animated hero dashboard

const dashRoot = document.getElementById('hero-dashboard');

function useTick(intervalMs = 1400) {
  const [n, setN] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setN((x) => x + 1), intervalMs);
    return () => clearInterval(id);
  }, [intervalMs]);
  return n;
}

function Sparkline({ data, height = 36, color, accent }) {
  const max = Math.max(...data);
  const min = Math.min(...data);
  const range = Math.max(1, max - min);
  const w = 120;
  const h = height;
  const pts = data.map((v, i) => {
    const x = (i / (data.length - 1)) * w;
    const y = h - ((v - min) / range) * (h - 4) - 2;
    return [x, y];
  });
  const path = pts.map(([x, y], i) => (i === 0 ? `M${x},${y}` : `L${x},${y}`)).join(' ');
  const area = `${path} L${w},${h} L0,${h} Z`;
  const last = pts[pts.length - 1];
  return (
    <svg viewBox={`0 0 ${w} ${h}`} style={{ width: '100%', height: h, overflow: 'visible' }}>
      <path d={area} fill={accent || 'rgba(216,234,44,0.18)'} />
      <path d={path} fill="none" stroke={color || 'var(--ink)'} strokeWidth="1.4" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx={last[0]} cy={last[1]} r="2.4" fill="var(--ink)" />
      <circle cx={last[0]} cy={last[1]} r="5.5" fill="var(--ink)" opacity="0.12" />
    </svg>
  );
}

function MetricRow({ label, value, delta, series, suffix }) {
  return (
    <div className="dash-row">
      <div className="dash-label">
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--mute)', letterSpacing: '0.06em', textTransform: 'uppercase', whiteSpace: 'nowrap' }}>{label}</div>
        <div style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, letterSpacing: '-0.025em', marginTop: 2 }}>
          {value}{suffix ? <span style={{ color: 'var(--mute)', fontSize: 14, marginLeft: 2 }}>{suffix}</span> : null}
        </div>
        <div className="mono" style={{ fontSize: 10.5, color: delta >= 0 ? 'var(--good)' : '#b81d1d', marginTop: 2 }}>
          {delta >= 0 ? '▲' : '▼'} {Math.abs(delta).toFixed(1)}% · 24h
        </div>
      </div>
      <div className="dash-spark">
        <Sparkline data={series} />
      </div>
    </div>
  );
}

function genSeries(base, vol, n = 24) {
  const out = [];
  let v = base;
  for (let i = 0; i < n; i++) {
    v += (Math.random() - 0.45) * vol;
    out.push(Math.max(0, v));
  }
  return out;
}

function StatusDot({ ok }) {
  return <span style={{ display: 'inline-block', width: 7, height: 7, borderRadius: 7, background: ok ? 'var(--good)' : 'var(--warn)', boxShadow: `0 0 0 3px ${ok ? 'rgba(31,138,91,0.18)' : 'rgba(200,122,0,0.18)'}` }} />;
}

function ActivityFeed() {
  const events = [
    { t: '14:02:11', kind: 'AGENT', text: 'support.l0  ·  ticket #48201 resolved · 12.4s' },
    { t: '14:02:07', kind: 'FLOW', text: 'lead.enrich  ·  acme.co · ICP score 92' },
    { t: '14:01:54', kind: 'SYNC', text: 'warehouse → crm  ·  3,418 rows · ok' },
    { t: '14:01:38', kind: 'AGENT', text: 'billing.recon  ·  Stripe ↔ Metronome · 0 drift' },
    { t: '14:01:22', kind: 'FLOW', text: 'routing.rr  ·  EMEA queue · 4 assigned' },
    { t: '14:01:04', kind: 'EVAL', text: 'support.draft  ·  pass 247/250' },
  ];
  const [idx, setIdx] = React.useState(0);
  React.useEffect(() => {
    const id = setInterval(() => setIdx((i) => (i + 1) % events.length), 2200);
    return () => clearInterval(id);
  }, []);

  const kindColor = { AGENT: 'var(--ink)', FLOW: '#3b82f6', SYNC: 'var(--mute)', EVAL: 'var(--good)' };

  return (
    <div className="dash-feed">
      {events.map((e, i) => {
        const dist = (i - idx + events.length) % events.length;
        return (
          <div key={i} className="feed-row" style={{ opacity: 1 - dist * 0.16 }}>
            <span className="mono" style={{ color: 'var(--mute-1)' }}>{e.t}</span>
            <span className="mono feed-kind" style={{ color: kindColor[e.kind] || 'var(--ink)' }}>{e.kind}</span>
            <span className="feed-text">{e.text}</span>
          </div>
        );
      })}
    </div>
  );
}

function HeroDashboard() {
  const tick = useTick(2600);

  const series = React.useMemo(() => ({
    leads: genSeries(42, 8),
    runs: genSeries(60, 12),
    sla: genSeries(95, 2.4),
    cost: genSeries(48, 6),
  }), [tick]);

  return (
    <div className="dashboard card">
      <div className="dash-head">
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span className="tag live"><span className="d"></span>Live</span>
          <span className="mono" style={{ fontSize: 11, color: 'var(--mute)', letterSpacing: '0.04em' }}>ops.anologe.co / overview</span>
        </div>
        <div className="mono" style={{ fontSize: 11, color: 'var(--mute-1)', display: 'flex', gap: 10 }}>
          <span>14:02 BST</span>
          <span>·</span>
          <span>v 2026.04.18</span>
        </div>
      </div>

      <div className="dash-tabs">
        <span className="dash-tab active">Overview</span>
        <span className="dash-tab">Revenue</span>
        <span className="dash-tab">Support</span>
        <span className="dash-tab">Workflows</span>
        <span className="dash-tab">Agents</span>
      </div>

      <div className="dash-metrics">
        <MetricRow label="Leads / hr" value={Math.round(38 + Math.sin(tick) * 4 + Math.random() * 3)} delta={+12.4} series={series.leads} />
        <MetricRow label="Runs / hr" value={(2.4 + Math.random() * 0.3).toFixed(1)} suffix="k" delta={+6.8} series={series.runs} />
        <MetricRow label="SLA · support" value={(96 + Math.random() * 1.6).toFixed(1)} suffix="%" delta={+1.4} series={series.sla} />
        <MetricRow label="Cost / 1k runs" value={'$' + (1.18 + Math.random() * 0.08).toFixed(2)} delta={-3.2} series={series.cost} />
      </div>

      <div className="dash-systems">
        <div className="systems-head mono">SYSTEMS · 10 / 10 GREEN</div>
        <div className="systems-grid">
          {['Revenue Ops', 'Workflows', 'CRM', 'Support', 'Billing', 'Knowledge', 'Attribution', 'Agents', 'Routing', 'Reporting'].map((s, i) => (
            <div key={s} className="sys">
              <StatusDot ok={true} />
              <span>{s}</span>
              <span className="mono" style={{ marginLeft: 'auto', color: 'var(--mute-1)', fontSize: 10 }}>{(99 + Math.random() * 0.99).toFixed(2)}%</span>
            </div>
          ))}
        </div>
      </div>

      <div className="dash-foot">
        <div className="mono" style={{ fontSize: 10.5, color: 'var(--mute)', letterSpacing: '0.06em', textTransform: 'uppercase', marginBottom: 8 }}>Activity</div>
        <ActivityFeed />
      </div>

      <style>{`
        .dashboard { padding: 16px; background: var(--bg-card); position: relative; }
        .dash-head { display: flex; justify-content: space-between; align-items: center; padding-bottom: 12px; border-bottom: 1px solid var(--line); }
        .dash-tabs { display: flex; gap: 0; margin: 0 -16px; padding: 0 16px; border-bottom: 1px solid var(--line); overflow: hidden; }
        .dash-tab { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.04em; text-transform: uppercase; color: var(--mute); padding: 12px 14px; cursor: default; position: relative; }
        .dash-tab.active { color: var(--ink); }
        .dash-tab.active::after { content: ''; position: absolute; left: 14px; right: 14px; bottom: -1px; height: 1.5px; background: var(--ink); }
        .dash-metrics { display: grid; grid-template-columns: 1fr 1fr; gap: 1px; background: var(--line); margin: 0 -16px; padding: 1px 0; }
        .dash-row { display: flex; justify-content: space-between; align-items: center; padding: 14px 16px; background: var(--bg-card); gap: 14px; }
        .dash-spark { width: 120px; flex-shrink: 0; }
        .dash-systems { padding-top: 16px; border-top: 1px solid var(--line); margin: 0 -16px; padding: 14px 16px 4px; }
        .systems-head { font-size: 10.5px; color: var(--mute); letter-spacing: 0.06em; margin-bottom: 10px; }
        .systems-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 18px; }
        .sys { display: flex; align-items: center; gap: 8px; font-size: 12.5px; padding: 4px 0; }
        .dash-foot { margin: 0 -16px -16px; padding: 14px 16px; border-top: 1px solid var(--line); background: #fcfcf9; }
        .dash-feed { display: flex; flex-direction: column; gap: 6px; font-size: 11.5px; }
        .feed-row { display: grid; grid-template-columns: 64px 56px 1fr; gap: 10px; align-items: center; transition: opacity 600ms; }
        .feed-kind { font-size: 10px; padding: 1.5px 5px; border: 1px solid var(--line); border-radius: 3px; text-align: center; letter-spacing: 0.05em; }
        .feed-text { font-family: var(--font-mono); color: var(--ink-1); letter-spacing: 0.01em; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
      `}</style>
    </div>
  );
}

if (dashRoot) {
  ReactDOM.createRoot(dashRoot).render(<HeroDashboard />);
}
