// SimpleCharts.jsx — lightweight SVG-based Area and Pie charts.
// No external dependency — pure React + SVG, reads DS tokens.

const PIE_COLORS = ["#f4a261", "#2a9d8f", "#e9c46a", "#7ec8c8", "#e76f51", "#a8dadc"];

// ── SVG Area Chart ────────────────────────────────────────────────────────
function AreaLineChart({ data, series, width = 520, height = 240 }) {
  const pad = { top: 12, right: 8, bottom: 28, left: 52 };
  const w = width - pad.left - pad.right;
  const h = height - pad.top - pad.bottom;

  if (!data || data.length < 2) return null;

  const allVals = series.flatMap(s => data.map(d => d[s.key] || 0)).filter(v => v != null);
  const maxV = Math.max(...allVals) * 1.05 || 1;
  const minAge = data[0].age;
  const maxAge = data[data.length - 1].age;
  const ageSpan = maxAge - minAge || 1;

  const px = (age) => ((age - minAge) / ageSpan) * w;
  const py = (v) => h - ((v || 0) / maxV) * h;

  // Y axis ticks
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(r => ({ v: maxV * r, y: h - r * h }));
  const fmtK = (v) => v >= 1e6 ? `${(v/1e6).toFixed(1)}M` : v >= 1000 ? `${(v/1000).toFixed(0)}K` : `${Math.round(v)}`;

  // X axis ticks every 10 years
  const ages = [];
  for (let a = Math.ceil(minAge / 10) * 10; a <= maxAge; a += 10) ages.push(a);

  const [tooltip, setTooltip] = React.useState(null);

  return (
    <svg width="100%" viewBox={`0 0 ${width} ${height}`} style={{ overflow: "visible" }}
      onMouseLeave={() => setTooltip(null)}>
      <g transform={`translate(${pad.left},${pad.top})`}>
        {/* Grid lines */}
        {yTicks.map((t, i) => (
          <g key={i}>
            <line x1={0} y1={t.y} x2={w} y2={t.y} stroke="rgba(128,100,70,0.15)" strokeDasharray="3 3" />
            <text x={-6} y={t.y + 4} textAnchor="end" fontSize={10} style={{ fill: "var(--text-muted)" }}>{fmtK(t.v)}</text>
          </g>
        ))}
        {ages.map((a, i) => {
          const x = px(a);
          return (
            <g key={i}>
              <text x={x} y={h + 16} textAnchor="middle" fontSize={10} style={{ fill: "var(--text-muted)" }}>{a}</text>
            </g>
          );
        })}

        {/* Area + lines */}
        {series.map((s) => {
          const pts = data.map(d => [px(d.age), py(d[s.key] || 0)]);
          const pathD = pts.map((p, i) => `${i === 0 ? "M" : "L"}${p[0].toFixed(1)},${p[1].toFixed(1)}`).join(" ");
          const areaD = `${pathD} L${pts[pts.length-1][0].toFixed(1)},${h} L${pts[0][0].toFixed(1)},${h} Z`;
          return (
            <g key={s.key}>
              <defs>
                <linearGradient id={`ag-${s.key}`} x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={s.color} stopOpacity={0.18} />
                  <stop offset="95%" stopColor={s.color} stopOpacity={0} />
                </linearGradient>
              </defs>
              <path d={areaD} fill={`url(#ag-${s.key})`} />
              <path d={pathD} fill="none" stroke={s.color} strokeWidth={s.width || 2} strokeDasharray={s.dash || "none"} />
            </g>
          );
        })}

        {/* Hover overlay */}
        <rect x={0} y={0} width={w} height={h} fill="transparent"
          onMouseMove={(e) => {
            const rect = e.currentTarget.closest("svg").getBoundingClientRect();
            const mx = e.clientX - rect.left - pad.left;
            const idx = Math.round((mx / w) * (data.length - 1));
            const d = data[Math.max(0, Math.min(data.length - 1, idx))];
            setTooltip({ d, x: px(d.age), y: 20 });
          }}
        />
        {tooltip && (
          <g>
            <line x1={tooltip.x} y1={0} x2={tooltip.x} y2={h} stroke="rgba(192,114,42,0.25)" strokeWidth={1.5} />
            <rect x={Math.min(tooltip.x + 6, w - 130)} y={0} width={120} height={series.length * 18 + 28} rx={6} style={{ fill: "var(--surface-card)", stroke: "var(--border-default)" }} strokeWidth={1.5} />
            <text x={Math.min(tooltip.x + 12, w - 124)} y={16} fontSize={11} fontWeight="600" style={{ fill: "var(--color-primary)" }}>อายุ {tooltip.d.age} ปี</text>
            {series.map((s, i) => (
              <text key={s.key} x={Math.min(tooltip.x + 12, w - 124)} y={30 + i * 18} fontSize={10} fill={s.color}>
                {s.label}: {tooltip.d[s.key] != null ? `฿${window.fmtTH(tooltip.d[s.key])}` : "—"}
              </text>
            ))}
          </g>
        )}
      </g>
    </svg>
  );
}

// ── SVG Pie Chart ─────────────────────────────────────────────────────────
function PieChart({ data, size = 200 }) {
  const cx = size / 2, cy = size / 2;
  const r = size * 0.38, ir = r * 0.5;
  const total = data.reduce((s, d) => s + d.value, 0) || 1;

  const Legend = ({ slices }) => (
    <div style={{ display: "flex", flexDirection: "column", gap: 7, flex: 1, minWidth: 0 }}>
      {slices.map((s, i) => (
        <div key={i} style={{ display: "flex", alignItems: "center", gap: 7, fontSize: 12 }}>
          <div style={{ width: 10, height: 10, borderRadius: "50%", background: s.color, flexShrink: 0 }}></div>
          <span style={{ color: "var(--text-body)", flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{s.name}</span>
          <span style={{ fontWeight: 400, color: "var(--text-brand)", fontFamily: "Mitr, sans-serif" }}>฿{window.fmtTH(s.value)}</span>
        </div>
      ))}
    </div>
  );

  // Single-slice: SVG arc degenerates when start === end — draw a plain donut circle instead
  if (data.length === 1) {
    const color = PIE_COLORS[0];
    const slices = [{ ...data[0], color, pct: "100" }];
    return (
      <div style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
        <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flexShrink: 0 }}>
          <circle cx={cx} cy={cy} r={r} fill={color} />
          <circle cx={cx} cy={cy} r={ir} style={{ fill: "var(--surface-inset)" }} />
          <text x={cx} y={cy - 6} textAnchor="middle" fontSize={13} fontWeight="700" style={{ fill: "var(--text-heading)" }}>100%</text>
          <text x={cx} y={cy + 10} textAnchor="middle" fontSize={9} style={{ fill: "var(--text-muted)" }}>{data[0].name}</text>
        </svg>
        <Legend slices={slices} />
      </div>
    );
  }

  let angle = -Math.PI / 2;
  const slices = data.map((d, i) => {
    const sweep = Math.min((d.value / total) * Math.PI * 2, Math.PI * 2 - 0.001);
    const a1 = angle, a2 = angle + sweep;
    angle = a2;
    const midA = (a1 + a2) / 2;
    const lx = cx + (r * 0.72) * Math.cos(midA);
    const ly = cy + (r * 0.72) * Math.sin(midA);
    const x1 = cx + r * Math.cos(a1), y1 = cy + r * Math.sin(a1);
    const x2 = cx + r * Math.cos(a2), y2 = cy + r * Math.sin(a2);
    const ix1 = cx + ir * Math.cos(a1), iy1 = cy + ir * Math.sin(a1);
    const ix2 = cx + ir * Math.cos(a2), iy2 = cy + ir * Math.sin(a2);
    const large = sweep > Math.PI ? 1 : 0;
    const path = `M${ix1},${iy1} L${x1},${y1} A${r},${r} 0 ${large} 1 ${x2},${y2} L${ix2},${iy2} A${ir},${ir} 0 ${large} 0 ${ix1},${iy1} Z`;
    return { ...d, path, pct: (d.value / total * 100).toFixed(0), lx, ly, color: PIE_COLORS[i % PIE_COLORS.length] };
  });

  return (
    <div style={{ display: "flex", gap: 16, alignItems: "center", flexWrap: "wrap" }}>
      <svg width={size} height={size} viewBox={`0 0 ${size} ${size}`} style={{ flexShrink: 0 }}>
        {slices.map((s, i) => (
          <path key={i} d={s.path} fill={s.color} stroke="var(--surface-card)" strokeWidth={2} />
        ))}
        {slices.map((s, i) => (
          Number(s.pct) > 8
            ? <text key={i} x={s.lx} y={s.ly} textAnchor="middle" dominantBaseline="middle"
                fontSize={10} fill="white" fontWeight="700">{s.pct}%</text>
            : null
        ))}
      </svg>
      <Legend slices={slices} />
    </div>
  );
}

window.AreaLineChart = AreaLineChart;
window.SimplePieChart = PieChart;
