/* ============================================================
   Lightweight SVG charts (no external lib)
   DonutBreakdown, LineChart, BalloonCurve, EquityBar, CompareBars
   ============================================================ */

// distinct chart colors derived from accent family
const CHART_COLORS = [
  "var(--accent-strong)", "var(--accent)", "var(--pos)", "var(--warn)",
  "oklch(0.62 0.1 280)", "oklch(0.66 0.1 330)", "oklch(0.6 0.09 180)", "var(--ink-3)",
];

function DonutBreakdown({ data, total, centerLabel, centerValue, size = 188 }) {
  const r = size / 2 - 14, cx = size / 2, cy = size / 2, C = 2 * Math.PI * r;
  let acc = 0;
  const sum = total ?? data.reduce((s, d) => s + d.v, 0);
  return (
    <div style={{ display: "flex", gap: 18, alignItems: "center", flexWrap: "wrap" }}>
      <svg width={size} height={size} style={{ flexShrink: 0 }}>
        <circle cx={cx} cy={cy} r={r} fill="none" stroke="var(--surface-3)" strokeWidth="16" />
        {data.map((d, i) => {
          const frac = sum ? d.v / sum : 0;
          const dash = `${frac * C} ${C}`;
          const off = -acc * C;
          acc += frac;
          return (
            <circle key={i} cx={cx} cy={cy} r={r} fill="none"
              stroke={d.color || CHART_COLORS[i % CHART_COLORS.length]} strokeWidth="16"
              strokeDasharray={dash} strokeDashoffset={off}
              transform={`rotate(-90 ${cx} ${cy})`} strokeLinecap="butt">
              <title>{d.k}</title>
            </circle>
          );
        })}
        <text x={cx} y={cy - 4} textAnchor="middle" fontFamily="var(--font-display)" fontWeight="700"
          fontSize="22" fill="var(--ink)" style={{ fontVariantNumeric: "tabular-nums" }}>{centerValue}</text>
        <text x={cx} y={cy + 16} textAnchor="middle" fontSize="11" fill="var(--ink-3)" fontWeight="600">{centerLabel}</text>
      </svg>
      <div style={{ display: "flex", flexDirection: "column", gap: 7, flex: 1, minWidth: 150 }}>
        {data.map((d, i) => (
          <div key={i} style={{ display: "flex", alignItems: "center", gap: 9, fontSize: 12.5 }}>
            <span style={{ width: 10, height: 10, borderRadius: 3, background: d.color || CHART_COLORS[i % CHART_COLORS.length], flexShrink: 0 }} />
            <span style={{ color: "var(--ink-2)", flex: 1 }}>{d.k}</span>
            <span style={{ fontWeight: 600, fontVariantNumeric: "tabular-nums" }}>{d.label}</span>
          </div>
        ))}
      </div>
    </div>
  );
}

function LineChart({ series, height = 200, yFmt = (v) => v, xLabels, marker }) {
  // series: [{points:[{x,y}], color, fill}]
  const W = 560, H = height, padL = 52, padR = 14, padT = 14, padB = 26;
  const allY = series.flatMap(s => s.points.map(p => p.y));
  const allX = series.flatMap(s => s.points.map(p => p.x));
  const minY = 0, maxY = Math.max(...allY) * 1.08 || 1;
  const minX = Math.min(...allX), maxX = Math.max(...allX) || 1;
  const sx = (x) => padL + ((x - minX) / (maxX - minX || 1)) * (W - padL - padR);
  const sy = (y) => H - padB - ((y - minY) / (maxY - minY || 1)) * (H - padT - padB);
  const ticks = 4;
  return (
    <svg viewBox={`0 0 ${W} ${H}`} width="100%" height={H} style={{ overflow: "visible" }}>
      {Array.from({ length: ticks + 1 }).map((_, i) => {
        const y = minY + (maxY - minY) * (i / ticks);
        return (
          <g key={i}>
            <line x1={padL} x2={W - padR} y1={sy(y)} y2={sy(y)} stroke="var(--border)" strokeWidth="1" />
            <text x={padL - 8} y={sy(y) + 3} textAnchor="end" fontSize="10" fill="var(--ink-3)" className="mono">{yFmt(y)}</text>
          </g>
        );
      })}
      {series.map((s, si) => {
        const path = s.points.map((p, i) => `${i ? "L" : "M"}${sx(p.x)},${sy(p.y)}`).join(" ");
        const area = path + ` L${sx(s.points[s.points.length - 1].x)},${sy(0)} L${sx(s.points[0].x)},${sy(0)} Z`;
        return (
          <g key={si}>
            {s.fill && <path d={area} fill={s.color} opacity="0.1" />}
            <path d={path} fill="none" stroke={s.color} strokeWidth="2.5" strokeLinejoin="round" strokeLinecap="round" />
          </g>
        );
      })}
      {marker != null && (
        <g>
          <line x1={sx(marker.x)} x2={sx(marker.x)} y1={padT} y2={H - padB} stroke="var(--accent)" strokeWidth="1.5" strokeDasharray="4 4" />
          <circle cx={sx(marker.x)} cy={sy(marker.y)} r="5" fill="var(--accent-strong)" stroke="var(--surface)" strokeWidth="2.5" />
        </g>
      )}
      {xLabels && xLabels.map((l, i) => (
        <text key={i} x={sx(l.x)} y={H - 8} textAnchor="middle" fontSize="10" fill="var(--ink-3)" className="mono">{l.label}</text>
      ))}
    </svg>
  );
}

function CompareBars({ items, fmt, height = 220 }) {
  // items: [{label, value, color, sublabel}]
  const max = Math.max(...items.map(i => i.value)) || 1;
  return (
    <div style={{ display: "flex", gap: 18, alignItems: "flex-end", height, padding: "0 4px" }}>
      {items.map((it, i) => {
        const h = (it.value / max) * (height - 48);
        return (
          <div key={i} style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", gap: 8, height: "100%", justifyContent: "flex-end" }}>
            <div style={{ fontWeight: 700, fontSize: 13.5, fontVariantNumeric: "tabular-nums" }}>{fmt(it.value)}</div>
            <div style={{ width: "100%", maxWidth: 84, height: Math.max(4, h), background: it.color || "var(--accent)", borderRadius: "8px 8px 0 0", transition: "height .35s cubic-bezier(.2,.8,.2,1)" }} />
            <div style={{ fontSize: 12, fontWeight: 600, color: "var(--ink-2)", textAlign: "center" }}>{it.label}</div>
            {it.sublabel && <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>{it.sublabel}</div>}
          </div>
        );
      })}
    </div>
  );
}

function EquityBar({ marketValue, settlement }) {
  const equity = marketValue - settlement;
  const positive = equity >= 0;
  const scale = Math.max(marketValue, settlement) || 1;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      <Bar label="Vehicle value" value={marketValue} scale={scale} color="var(--accent)" fmt={fmt.gbp} />
      <Bar label="Settlement owed" value={settlement} scale={scale} color="var(--ink-3)" fmt={fmt.gbp} />
      <div style={{ height: 1, background: "var(--border)", margin: "2px 0" }} />
      <Bar label={positive ? "Positive equity" : "Negative equity"} value={Math.abs(equity)} scale={scale}
        color={positive ? "var(--pos)" : "var(--neg)"} fmt={fmt.gbp} bold />
    </div>
  );
}
function Bar({ label, value, scale, color, fmt, bold }) {
  return (
    <div>
      <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12.5, marginBottom: 5, fontWeight: bold ? 700 : 500, color: bold ? color : "var(--ink-2)" }}>
        <span>{label}</span><span style={{ fontVariantNumeric: "tabular-nums" }}>{fmt(value)}</span>
      </div>
      <div style={{ height: 12, background: "var(--surface-3)", borderRadius: 999, overflow: "hidden" }}>
        <div style={{ width: `${Math.min(100, (value / scale) * 100)}%`, height: "100%", background: color, borderRadius: 999, transition: "width .4s cubic-bezier(.2,.8,.2,1)" }} />
      </div>
    </div>
  );
}

Object.assign(window, { DonutBreakdown, LineChart, CompareBars, EquityBar });
