/* global React, Icons */
const { useState: useStateDash, useEffect: useEffectDash, useRef: useRefDash, useMemo } = React;

// ---------- chart helpers ----------
function smoothPath(pts) {
  if (pts.length < 2) return '';
  let d = `M ${pts[0][0]},${pts[0][1]}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[i], p1 = pts[i + 1];
    const cx = (p0[0] + p1[0]) / 2;
    d += ` C ${cx},${p0[1]} ${cx},${p1[1]} ${p1[0]},${p1[1]}`;
  }
  return d;
}
function toPoints(vals, w, h, pad = 4) {
  const min = Math.min(...vals), max = Math.max(...vals);
  const span = max - min || 1;
  return vals.map((v, i) => [
    (i / (vals.length - 1)) * w,
    pad + (1 - (v - min) / span) * (h - pad * 2),
  ]);
}

function Sparkline({ data, color = '#22D3EE', w = 96, h = 30 }) {
  const pts = toPoints(data, w, h, 3);
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="overflow-visible">
      <path d={smoothPath(pts)} fill="none" stroke={color} strokeWidth="1.8" strokeLinecap="round" />
      <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.4" fill={color} />
    </svg>
  );
}

function AreaChart({ series, w = 560, h = 200 }) {
  const id = useMemo(() => 'g' + Math.random().toString(36).slice(2), []);
  const pad = 10;
  const a = toPoints(series.a, w, h - 22, pad);
  const b = toPoints(series.b, w, h - 22, pad);
  const areaD = smoothPath(a) + ` L ${w},${h - 22} L 0,${h - 22} Z`;
  const ticks = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full" preserveAspectRatio="none" style={{ height: 'auto' }}>
      <defs>
        <linearGradient id={id} x1="0" y1="0" x2="0" y2="1">
          <stop offset="0%" stopColor="#8B5CF6" stopOpacity="0.42" />
          <stop offset="100%" stopColor="#8B5CF6" stopOpacity="0" />
        </linearGradient>
      </defs>
      {[0.25, 0.5, 0.75, 1].map((g, i) => (
        <line key={i} x1="0" x2={w} y1={(h - 22) * g} y2={(h - 22) * g} stroke="rgba(255,255,255,0.05)" strokeWidth="1" />
      ))}
      <path d={areaD} fill={`url(#${id})`} />
      <path d={smoothPath(b)} fill="none" stroke="#22D3EE" strokeWidth="1.6" strokeDasharray="3 4" opacity="0.7" />
      <path d={smoothPath(a)} fill="none" stroke="#a78bfa" strokeWidth="2.4" strokeLinecap="round" />
      <circle cx={a[a.length - 1][0]} cy={a[a.length - 1][1]} r="3.5" fill="#fff" />
      <circle cx={a[a.length - 1][0]} cy={a[a.length - 1][1]} r="7" fill="#a78bfa" opacity="0.3" />
      {ticks.map((t, i) => (
        <text key={t} x={(i / 6) * w} y={h - 5} fill="#475569" fontSize="9" fontFamily="Inter"
          textAnchor={i === 0 ? 'start' : i === 6 ? 'end' : 'middle'}>{t}</text>
      ))}
    </svg>
  );
}

function BarMini({ data, color = '#34D399', w = 230, h = 92 }) {
  const max = Math.max(...data);
  const bw = w / data.length;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full" style={{ height: 'auto' }}>
      {data.map((v, i) => {
        const bh = (v / max) * (h - 6);
        return <rect key={i} x={i * bw + bw * 0.18} y={h - bh} width={bw * 0.64} height={bh} rx="2"
          fill={i === data.length - 1 ? color : 'rgba(52,211,153,0.32)'} />;
      })}
    </svg>
  );
}

function Ring({ value = 73, color = '#22D3EE', size = 92 }) {
  const r = size / 2 - 8, c = 2 * Math.PI * r;
  return (
    <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke="rgba(255,255,255,0.07)" strokeWidth="7" />
      <circle cx={size / 2} cy={size / 2} r={r} fill="none" stroke={color} strokeWidth="7" strokeLinecap="round"
        strokeDasharray={c} strokeDashoffset={c * (1 - value / 100)} transform={`rotate(-90 ${size / 2} ${size / 2})`} />
      <text x="50%" y="50%" textAnchor="middle" dy="0.05em" fill="#F8FAFC" fontSize="19" fontFamily="Inter" fontWeight="600">{value}%</text>
      <text x="50%" y="64%" textAnchor="middle" fill="#64748B" fontSize="7.5" fontFamily="Inter">RESOLVED</text>
    </svg>
  );
}

// ---------- feed data ----------
const FEED_SEED = [
  { t: 'now', c: 'mint', txt: 'Agent · auto-reconciled 1,204 transactions', meta: 'no exceptions' },
  { t: '2m', c: 'cyan', txt: 'Throughput spike detected on EU-West', meta: '+18% vs. baseline' },
  { t: '6m', c: 'primary', txt: 'AI summary drafted for weekly report', meta: 'ready to review' },
  { t: '11m', c: 'amber', txt: 'Anomaly flagged · invoice #44821', meta: 'escalated to human' },
  { t: '17m', c: 'mint', txt: 'Re-route applied · shipment MX-7782', meta: 'within policy' },
  { t: '24m', c: 'cyan', txt: 'Model swapped to claude-sonnet for intake', meta: 'latency −22%' },
];
const dotColor = { mint: '#34D399', cyan: '#22D3EE', primary: '#8B5CF6', amber: '#FBBF24' };

// ---------- main dashboard ----------
function Dashboard({ live = false }) {
  const [kpis, setKpis] = useStateDash([
    { label: 'Throughput', value: 24816, fmt: 'n', delta: '+12.4%', up: true, spark: [8, 10, 9, 13, 12, 16, 15, 19, 22, 24], color: '#a78bfa' },
    { label: 'Active agents', value: 12, fmt: 'i', delta: '+2', up: true, spark: [6, 7, 7, 9, 9, 10, 11, 11, 12, 12], color: '#22D3EE' },
    { label: 'Avg latency', value: 312, fmt: 'ms', delta: '−22%', up: true, spark: [9, 8, 8, 7, 7, 6, 6, 5, 5, 4], color: '#34D399' },
    { label: 'Error rate', value: 0.08, fmt: '%', delta: '−0.3pt', up: true, spark: [5, 4, 4, 3, 4, 3, 2, 2, 2, 1], color: '#34D399' },
  ]);
  const [feed, setFeed] = useStateDash(FEED_SEED);
  const [tick, setTick] = useStateDash(0);

  useEffectDash(() => {
    if (!live) return;
    const id = setInterval(() => {
      setKpis(prev => prev.map((k, i) => i === 0
        ? { ...k, value: k.value + Math.floor(Math.random() * 40), spark: [...k.spark.slice(1), k.spark[k.spark.length - 1] + (Math.random() - 0.3) * 3] }
        : k));
      setTick(t => t + 1);
    }, 2600);
    return () => clearInterval(id);
  }, [live]);

  const fmtVal = (k) => {
    if (k.fmt === 'n') return k.value.toLocaleString();
    if (k.fmt === 'ms') return k.value + 'ms';
    if (k.fmt === '%') return k.value + '%';
    return k.value;
  };

  const areaSeries = { a: [12, 15, 13, 18, 16, 22, 20, 26, 24, 30, 28, 34], b: [10, 11, 12, 13, 13, 15, 16, 17, 18, 19, 20, 22] };

  return (
    <div className="w-full h-full rounded-2xl overflow-hidden flex text-[13px]"
      style={{ background: 'linear-gradient(160deg,#0b1020,#0a0e1c)', border: '1px solid rgba(255,255,255,0.08)' }}>
      {/* sidebar */}
      <aside className="hidden sm:flex flex-col items-center gap-1 py-4 px-2.5 border-r border-white/5 bg-white/[0.015]">
        <div className="w-8 h-8 rounded-lg grid place-items-center mb-3" style={{ background: 'linear-gradient(135deg,#6366F1,#8B5CF6)' }}>
          <Icons.Sparkles size={16} className="text-white" />
        </div>
        {['Grid', 'Activity', 'Bot', 'Chart', 'Users', 'Bell'].map((ic, i) => (
          <div key={ic} className={`w-9 h-9 rounded-lg grid place-items-center ${i === 1 ? 'bg-primary/15 text-violet-300' : 'text-body-dim hover:text-body'}`}>
            {React.createElement(Icons[ic], { size: 17 })}
          </div>
        ))}
      </aside>

      {/* main */}
      <div className="flex-1 min-w-0 flex flex-col">
        {/* topbar */}
        <div className="flex items-center gap-3 px-4 sm:px-5 h-12 border-b border-white/5 shrink-0">
          <div className="flex items-center gap-2 min-w-0">
            <span className="font-display font-semibold text-heading truncate">Orion Ops</span>
            <span className="hidden md:inline text-[11px] text-body-dim font-mono">/ control tower</span>
          </div>
          <div className="hidden md:flex items-center gap-2 ml-2 px-2.5 h-7 rounded-lg bg-white/[0.03] border border-white/5 text-body-dim min-w-0 flex-1 max-w-[180px]">
            <Icons.Search size={13} /><span className="text-[11px] truncate">Search metrics…</span>
          </div>
          <div className="ml-auto flex items-center gap-2.5">
            <span className="flex items-center gap-1.5 px-2 h-6 rounded-full bg-mint/10 border border-mint/20 text-mint text-[10px] font-mono">
              <span className="w-1.5 h-1.5 rounded-full bg-mint animate-pulse-dot" />LIVE
            </span>
            <div className="w-7 h-7 rounded-full bg-gradient-to-br from-violet-500 to-cyan-400 grid place-items-center text-white text-[10px] font-semibold">OT</div>
          </div>
        </div>

        {/* body */}
        <div className="flex-1 p-3 sm:p-4 grid gap-3 overflow-hidden" style={{ gridTemplateColumns: 'minmax(0,1.6fr) minmax(0,1fr)' }}>
          {/* left column */}
          <div className="flex flex-col gap-3 min-w-0">
            {/* KPI tiles */}
            <div className="grid grid-cols-2 lg:grid-cols-4 gap-2.5">
              {kpis.map((k) => (
                <div key={k.label} className="rounded-xl p-2.5 bg-white/[0.025] border border-white/5">
                  <div className="text-[10px] text-body-dim font-mono uppercase tracking-wide truncate">{k.label}</div>
                  <div className="mt-1 flex items-end justify-between gap-1">
                    <span className="font-display font-semibold text-heading text-base sm:text-lg tabular-nums">{fmtVal(k)}</span>
                  </div>
                  <div className="mt-1.5 flex items-center justify-between gap-1">
                    <span className={`text-[10px] font-mono ${k.up ? 'text-mint' : 'text-rose-400'}`}>{k.delta}</span>
                    <Sparkline data={k.spark} color={k.color} w={54} h={18} />
                  </div>
                </div>
              ))}
            </div>

            {/* big area chart */}
            <div className="rounded-xl p-3 sm:p-4 bg-white/[0.02] border border-white/5 flex-1 min-h-0 flex flex-col">
              <div className="flex items-center justify-between mb-1">
                <div>
                  <div className="text-heading font-display font-medium text-sm">Throughput</div>
                  <div className="text-[10px] text-body-dim font-mono">events / hour · last 7 days</div>
                </div>
                <div className="flex items-center gap-3 text-[10px] font-mono">
                  <span className="flex items-center gap-1.5 text-violet-300"><span className="w-2.5 h-[3px] rounded bg-violet-400" />actual</span>
                  <span className="flex items-center gap-1.5 text-cyan"><span className="w-2.5 h-[3px] rounded bg-cyan/70" />forecast</span>
                </div>
              </div>
              <div className="flex-1 min-h-0 flex items-end">
                <AreaChart series={areaSeries} />
              </div>
            </div>

            {/* bottom row: bar + ring */}
            <div className="grid grid-cols-2 gap-3">
              <div className="rounded-xl p-3 bg-white/[0.02] border border-white/5">
                <div className="flex items-center justify-between mb-2">
                  <div className="text-[11px] text-body font-medium">Volume by source</div>
                  <Icons.TrendUp size={13} className="text-mint" />
                </div>
                <BarMini data={[5, 8, 6, 9, 7, 11, 9, 13]} />
              </div>
              <div className="rounded-xl p-3 bg-white/[0.02] border border-white/5 flex items-center justify-between">
                <div>
                  <div className="text-[11px] text-body font-medium">Auto-resolved</div>
                  <div className="text-[10px] text-body-dim font-mono mt-0.5">no human touch</div>
                  <div className="mt-2 text-mint font-mono text-[10px]">▲ +6pt week</div>
                </div>
                <Ring value={73} />
              </div>
            </div>
          </div>

          {/* right column */}
          <div className="flex flex-col gap-3 min-w-0">
            {/* AI summary */}
            <div className="rounded-xl p-3.5 grad-border relative bg-gradient-to-b from-violet-500/[0.08] to-transparent border border-white/5">
              <div className="flex items-center gap-2 mb-2">
                <span className="w-6 h-6 rounded-lg grid place-items-center" style={{ background: 'linear-gradient(135deg,#6366F1,#8B5CF6)' }}>
                  <Icons.Sparkles size={13} className="text-white" />
                </span>
                <span className="text-heading font-display font-medium text-sm">AI summary</span>
                <span className="ml-auto text-[9px] font-mono text-body-dim px-1.5 py-0.5 rounded bg-white/5">claude</span>
              </div>
              <p className="text-[12px] leading-relaxed text-body">
                Throughput is up <span className="text-violet-300 font-medium">12.4%</span> week-over-week, driven by EU-West.
                Agents auto-resolved <span className="text-mint font-medium">73%</span> of exceptions; one invoice anomaly was escalated.
                Latency improved after the model swap.
              </p>
              <div className="mt-2.5 flex flex-wrap gap-1.5">
                {['Healthy', '1 to review', 'On forecast'].map((t, i) => (
                  <span key={t} className={`text-[10px] font-mono px-2 py-0.5 rounded-full border ${i === 1 ? 'text-amber-300 border-amber-400/25 bg-amber-400/10' : 'text-body-dim border-white/8 bg-white/[0.03]'}`}>{t}</span>
                ))}
              </div>
            </div>

            {/* live feed */}
            <div className="rounded-xl bg-white/[0.02] border border-white/5 flex-1 min-h-0 flex flex-col overflow-hidden">
              <div className="flex items-center justify-between px-3 py-2.5 border-b border-white/5">
                <span className="text-[11px] text-body font-medium">Live insights</span>
                <Icons.Activity size={13} className="text-cyan" />
              </div>
              <div className="flex-1 min-h-0 overflow-hidden p-2 space-y-1.5">
                {feed.slice(0, 6).map((f, i) => (
                  <div key={f.txt + i} className="flex gap-2.5 px-2 py-1.5 rounded-lg hover:bg-white/[0.025]" style={{ opacity: 1 - i * 0.07 }}>
                    <span className="mt-1.5 w-1.5 h-1.5 rounded-full shrink-0" style={{ background: dotColor[f.c], boxShadow: `0 0 8px ${dotColor[f.c]}` }} />
                    <div className="min-w-0">
                      <div className="text-[11px] text-body leading-snug truncate">{f.txt}</div>
                      <div className="text-[9.5px] text-body-dim font-mono">{f.meta} · {f.t}</div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Dashboard });
