// charts.jsx — lightweight SVG chart primitives (no external lib)
const { useState: useStateC } = React;

/* ---------- Area / line chart ---------- */
function AreaChart({ data, color = "var(--accent)", height = 160, suffix = "", labels }) {
  const w = 560, h = height, padL = 34, padB = 22, padT = 12, padR = 8;
  const min = Math.min(...data), max = Math.max(...data);
  const lo = Math.floor(min - (max - min) * 0.25);
  const hi = Math.ceil(max + (max - min) * 0.15);
  const rng = hi - lo || 1;
  const iw = w - padL - padR, ih = h - padB - padT;
  const x = i => padL + (i / (data.length - 1)) * iw;
  const y = v => padT + ih - ((v - lo) / rng) * ih;
  const line = data.map((v, i) => (i ? "L" : "M") + x(i).toFixed(1) + " " + y(v).toFixed(1)).join(" ");
  const area = line + ` L ${x(data.length - 1)} ${padT + ih} L ${padL} ${padT + ih} Z`;
  const gid = "ac" + Math.random().toString(36).slice(2, 7);
  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${w} ${h}`} className="w-full" style={{ height }} preserveAspectRatio="none">
      <defs><linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
        <stop offset="0%" stopColor={color} stopOpacity="0.22" /><stop offset="100%" stopColor={color} stopOpacity="0" />
      </linearGradient></defs>
      {Array.from({ length: ticks + 1 }).map((_, i) => {
        const gv = lo + (rng * i) / ticks; const gy = y(gv);
        return (<g key={i}>
          <line x1={padL} y1={gy} x2={w - padR} y2={gy} stroke="#f1f1f3" strokeWidth="1" />
          <text x={padL - 6} y={gy + 3} textAnchor="end" fontSize="9" fill="#a1a1aa">{Math.round(gv)}{suffix}</text>
        </g>);
      })}
      <path d={area} fill={`url(#${gid})`} />
      <path d={line} fill="none" stroke={color} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx={x(data.length - 1)} cy={y(data[data.length - 1])} r="3.5" fill={color} stroke="#fff" strokeWidth="1.5" />
      {labels && labels.map((l, i) => <text key={i} x={x(i * (data.length - 1))} y={h - 6} textAnchor={i === 0 ? "start" : "end"} fontSize="9" fill="#a1a1aa">{l}</text>)}
    </svg>
  );
}

/* ---------- Donut ---------- */
function Donut({ data, size = 168, thickness = 26 }) {
  const total = data.reduce((a, d) => a + d.value, 0);
  const r = (size - thickness) / 2, cx = size / 2, cy = size / 2, C = 2 * Math.PI * r;
  let off = 0;
  const [hover, setHover] = useStateC(null);
  return (
    <div className="flex items-center gap-5 flex-wrap">
      <div className="relative shrink-0" style={{ width: size, height: size }}>
        <svg width={size} height={size} className="-rotate-90">
          <circle cx={cx} cy={cy} r={r} fill="none" stroke="#f1f1f3" strokeWidth={thickness} />
          {data.map((d, i) => {
            const frac = d.value / total, len = frac * C;
            const el = (
              <circle key={i} cx={cx} cy={cy} r={r} fill="none" stroke={d.color}
                strokeWidth={hover === i ? thickness + 3 : thickness} strokeDasharray={`${len} ${C - len}`} strokeDashoffset={-off}
                onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
                style={{ transition: "stroke-width .15s", cursor: "default" }} />
            );
            off += len; return el;
          })}
        </svg>
        <div className="absolute inset-0 flex flex-col items-center justify-center">
          <span className="text-[22px] font-semibold text-zinc-900 leading-none">{(hover != null ? data[hover] : data[0]).value + "%"}</span>
          <span className="text-[10.5px] text-zinc-400 mt-1 max-w-[84px] text-center leading-tight">{hover != null ? data[hover].label : data[0].label}</span>
        </div>
      </div>
      <div className="flex-1 min-w-[160px] space-y-1.5">
        {data.map((d, i) => (
          <div key={i} className="flex items-center gap-2 text-[12.5px]" onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
            <span className="w-2.5 h-2.5 rounded-sm shrink-0" style={{ background: d.color }} />
            <span className="text-zinc-600 flex-1 truncate">{d.label}</span>
            <span className="text-zinc-800 font-medium tabular-nums">{d.value}%</span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ---------- Horizontal bars (with optional dual metric) ---------- */
function HBars({ rows, maxValue, format = v => v, color = "var(--accent)", colorFor }) {
  const max = maxValue || Math.max(...rows.map(r => r.value));
  return (
    <div className="space-y-3">
      {rows.map((r, i) => (
        <div key={i}>
          <div className="flex items-center justify-between mb-1">
            <span className="text-[12.5px] text-zinc-600">{r.label}</span>
            <span className="text-[12.5px] font-medium text-zinc-800 tabular-nums">{format(r.value)}</span>
          </div>
          <div className="h-2 rounded-full bg-zinc-100 overflow-hidden">
            <div className="h-full rounded-full transition-all" style={{ width: (r.value / max) * 100 + "%", background: colorFor ? colorFor(r) : color }} />
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---------- Radial gauge ---------- */
function Gauge({ value, size = 150, label, color }) {
  const r = (size - 18) / 2, cx = size / 2, cy = size / 2, C = Math.PI * r; // semicircle
  const c = color || (value >= 90 ? "#16a34a" : value >= 75 ? "#d97706" : "#dc2626");
  const len = (value / 100) * C;
  return (
    <div className="flex flex-col items-center">
      <svg width={size} height={size / 2 + 16} viewBox={`0 0 ${size} ${size / 2 + 16}`}>
        <path d={`M ${9} ${cy} A ${r} ${r} 0 0 1 ${size - 9} ${cy}`} fill="none" stroke="#f1f1f3" strokeWidth="12" strokeLinecap="round" />
        <path d={`M ${9} ${cy} A ${r} ${r} 0 0 1 ${size - 9} ${cy}`} fill="none" stroke={c} strokeWidth="12" strokeLinecap="round" strokeDasharray={`${len} ${C}`} />
      </svg>
      <div className="-mt-7 flex flex-col items-center">
        <span className="text-[26px] font-semibold text-zinc-900 leading-none">{value}%</span>
        {label && <span className="text-[11.5px] text-zinc-400 mt-1">{label}</span>}
      </div>
    </div>
  );
}

/* ---------- Confidence ring (small) ---------- */
function ConfRing({ value, size = 40 }) {
  const r = (size - 6) / 2, cx = size / 2, cy = size / 2, C = 2 * Math.PI * r;
  const c = confColor(value), len = (value / 100) * C;
  return (
    <div className="relative shrink-0" style={{ width: size, height: size }}>
      <svg width={size} height={size} className="-rotate-90">
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="#f1f1f3" strokeWidth="3.5" />
        <circle cx={cx} cy={cy} r={r} fill="none" stroke={c} strokeWidth="3.5" strokeLinecap="round" strokeDasharray={`${len} ${C}`} />
      </svg>
      <span className="absolute inset-0 flex items-center justify-center text-[11px] font-semibold tabular-nums" style={{ color: c }}>{value}</span>
    </div>
  );
}

Object.assign(window, { AreaChart, Donut, HBars, Gauge, ConfRing });
