/* ============================================================
   ZERO — Chart primitives (pure SVG, no libs). window.Charts
   ============================================================ */
(function () {
  const { useId } = React;

  // ---- Sparkline (tiny line) ----
  function Sparkline({ data, color = 'var(--violet)', w = 96, h = 30, fill = true }) {
    const id = useId();
    const max = Math.max(...data), min = Math.min(...data);
    const rng = max - min || 1;
    const pts = data.map((v, i) => [ (i / (data.length - 1)) * w, h - ((v - min) / rng) * (h - 4) - 2 ]);
    const line = pts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
    const area = line + ` L${w} ${h} L0 ${h} Z`;
    return (
      <svg width={w} height={h} style={{ display: 'block', overflow: 'visible' }}>
        <defs>
          <linearGradient id={'sp' + id} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.28" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
        </defs>
        {fill && <path d={area} fill={`url(#sp${id})`} />}
        <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
        <circle cx={pts[pts.length - 1][0]} cy={pts[pts.length - 1][1]} r="2.6" fill={color} />
      </svg>
    );
  }

  // ---- Area chart (large) with grid + hover dots ----
  function AreaChart({ data, labels, color = 'var(--violet)', color2 = 'var(--teal)', h = 240, prefix = '$', suffix = 'k' }) {
    const id = useId();
    const W = 760, H = h, padL = 8, padB = 26, padT = 12;
    const cw = W - padL, ch = H - padB - padT;
    const max = Math.max(...data) * 1.15, min = 0;
    const rng = max - min || 1;
    const x = (i) => padL + (i / (data.length - 1)) * cw;
    const y = (v) => padT + ch - ((v - min) / rng) * ch;
    const pts = data.map((v, i) => [x(i), y(v)]);
    // smooth path
    let line = `M${pts[0][0]} ${pts[0][1]}`;
    for (let i = 1; i < pts.length; i++) {
      const [px, py] = pts[i - 1], [cx, cy] = pts[i];
      const mx = (px + cx) / 2;
      line += ` C${mx} ${py}, ${mx} ${cy}, ${cx} ${cy}`;
    }
    const area = line + ` L${pts[pts.length - 1][0]} ${padT + ch} L${pts[0][0]} ${padT + ch} Z`;
    const grid = [0, 0.25, 0.5, 0.75, 1].map(f => padT + ch * f);
    return (
      <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} preserveAspectRatio="none" style={{ overflow: 'visible' }}>
        <defs>
          <linearGradient id={'ar' + id} x1="0" y1="0" x2="0" y2="1">
            <stop offset="0%" stopColor={color} stopOpacity="0.32" />
            <stop offset="100%" stopColor={color} stopOpacity="0" />
          </linearGradient>
          <linearGradient id={'st' + id} x1="0" y1="0" x2="1" y2="0">
            <stop offset="0%" stopColor={color} />
            <stop offset="100%" stopColor={color2} />
          </linearGradient>
        </defs>
        {grid.map((gy, i) => <line key={i} x1={padL} y1={gy} x2={W} y2={gy} stroke="var(--line)" strokeWidth="1" />)}
        <path d={area} fill={`url(#ar${id})`} />
        <path d={line} fill="none" stroke={`url(#st${id})`} strokeWidth="2.5" strokeLinecap="round" />
        {pts.map((p, i) => <circle key={i} cx={p[0]} cy={p[1]} r="3" fill="var(--bg-0)" stroke={color} strokeWidth="2" opacity={i === pts.length - 1 ? 1 : 0} />)}
        {labels && labels.map((l, i) => (i % 2 === 0 || i === labels.length - 1) && (
          <text key={i} x={x(i)} y={H - 6} fontSize="10.5" fill="var(--tx-3)" textAnchor="middle" fontFamily="JetBrains Mono">{l}</text>
        ))}
      </svg>
    );
  }

  // ---- Bars ----
  function Bars({ data, color = 'var(--violet)', h = 150, labels }) {
    const max = Math.max(...data) || 1;
    return (
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: h }}>
        {data.map((v, i) => (
          <div key={i} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6, height: '100%', justifyContent: 'flex-end' }}>
            <div style={{ width: '100%', height: `${(v / max) * 100}%`, minHeight: 4,
              background: `linear-gradient(180deg, ${color}, color-mix(in oklab, ${color}, transparent 55%))`,
              borderRadius: '5px 5px 2px 2px', transition: 'height .5s cubic-bezier(.2,.7,.2,1)' }} />
            {labels && <span className="mono" style={{ fontSize: 9.5, color: 'var(--tx-3)' }}>{labels[i]}</span>}
          </div>
        ))}
      </div>
    );
  }

  // ---- Donut ----
  function Donut({ value, max = 100, size = 110, stroke = 11, color = 'var(--violet)', label, sub }) {
    const r = (size - stroke) / 2;
    const c = 2 * Math.PI * r;
    const pct = Math.min(value / max, 1);
    return (
      <div style={{ position: 'relative', width: size, height: size }}>
        <svg width={size} height={size} style={{ transform: 'rotate(-90deg)' }}>
          <circle cx={size/2} cy={size/2} r={r} fill="none" stroke="var(--line)" strokeWidth={stroke} />
          <circle cx={size/2} cy={size/2} r={r} fill="none" stroke={color} strokeWidth={stroke}
            strokeDasharray={c} strokeDashoffset={c * (1 - pct)} strokeLinecap="round"
            style={{ transition: 'stroke-dashoffset .8s cubic-bezier(.2,.7,.2,1)' }} />
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: '-0.03em' }}>{label}</div>
            {sub && <div style={{ fontSize: 10.5, color: 'var(--tx-2)' }}>{sub}</div>}
          </div>
        </div>
      </div>
    );
  }

  // ---- Radial gauge ring (multi) ----
  window.Charts = { Sparkline, AreaChart, Bars, Donut };
})();
