// Lightweight, hand-drawn SVG charts — no external libs.
// All charts: stroke 1.5, monochrome by default, accent on hover.

const { useState, useMemo, useRef, useEffect } = React;

// ---------- Line chart with optional area fill ----------
function LineChart({ series, labels, height = 220, accent = "#EA580C", yFormat = (v) => v }) {
  const [hover, setHover] = useState(null);
  const ref = useRef(null);
  const w = 720;
  const h = height;
  const padL = 44, padR = 12, padT = 16, padB = 28;
  const innerW = w - padL - padR;
  const innerH = h - padT - padB;

  const all = series.flatMap(s => s.values);
  const minV = Math.min(...all);
  const maxV = Math.max(...all);
  const yMin = Math.floor(minV * 0.9);
  const yMax = Math.ceil(maxV * 1.05);
  const range = yMax - yMin || 1;

  const x = (i) => padL + (i / (labels.length - 1)) * innerW;
  const y = (v) => padT + innerH - ((v - yMin) / range) * innerH;

  // y ticks
  const ticks = 4;
  const tickValues = Array.from({ length: ticks + 1 }, (_, i) => yMin + (range * i) / ticks);

  function onMove(e) {
    const rect = ref.current.getBoundingClientRect();
    const px = ((e.clientX - rect.left) / rect.width) * w;
    const idx = Math.round(((px - padL) / innerW) * (labels.length - 1));
    if (idx >= 0 && idx < labels.length) setHover(idx);
  }

  return (
    <div className="chart-wrap">
      <svg ref={ref} viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="chart-svg"
           onMouseMove={onMove} onMouseLeave={() => setHover(null)}>
        {/* Y grid */}
        {tickValues.map((tv, i) => (
          <g key={i}>
            <line x1={padL} x2={w - padR} y1={y(tv)} y2={y(tv)} stroke="#EEEAE3" strokeWidth="1" />
            <text x={padL - 8} y={y(tv) + 4} textAnchor="end" className="chart-axis-text">{yFormat(Math.round(tv))}</text>
          </g>
        ))}
        {/* X labels */}
        {labels.map((l, i) => (
          <text key={i} x={x(i)} y={h - 8} textAnchor="middle" className="chart-axis-text">{l}</text>
        ))}
        {/* Series */}
        {series.map((s, si) => {
          const path = s.values.map((v, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(v)}`).join(" ");
          const area = `${path} L ${x(s.values.length - 1)} ${padT + innerH} L ${x(0)} ${padT + innerH} Z`;
          const color = s.color || accent;
          return (
            <g key={si}>
              {s.fill && <path d={area} fill={color} opacity="0.06" />}
              <path d={path} fill="none" stroke={color} strokeWidth="1.75" strokeLinejoin="round" strokeLinecap="round" />
              {s.values.map((v, i) => (
                <circle key={i} cx={x(i)} cy={y(v)} r={hover === i ? 4 : 0} fill={color} />
              ))}
            </g>
          );
        })}
        {/* Hover line */}
        {hover !== null && (
          <line x1={x(hover)} x2={x(hover)} y1={padT} y2={padT + innerH} stroke="#D6D2CB" strokeWidth="1" strokeDasharray="2 3" />
        )}
      </svg>
      {hover !== null && (
        <div className="chart-tooltip" style={{ left: `${(x(hover) / w) * 100}%` }}>
          <div className="tt-label">{labels[hover]}</div>
          {series.map((s, i) => (
            <div key={i} className="tt-row">
              <span className="tt-dot" style={{ background: s.color || accent }} />
              <span className="tt-name">{s.name}</span>
              <span className="tt-val">{yFormat(s.values[hover])}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ---------- Donut chart ----------
function DonutChart({ data, size = 200, thickness = 22 }) {
  const total = data.reduce((s, d) => s + d.value, 0);
  const cx = size / 2;
  const cy = size / 2;
  const r = size / 2 - thickness / 2 - 2;
  let acc = 0;
  const slices = data.map((d) => {
    const start = (acc / total) * Math.PI * 2 - Math.PI / 2;
    acc += d.value;
    const end = (acc / total) * Math.PI * 2 - Math.PI / 2;
    const large = end - start > Math.PI ? 1 : 0;
    const x1 = cx + Math.cos(start) * r;
    const y1 = cy + Math.sin(start) * r;
    const x2 = cx + Math.cos(end) * r;
    const y2 = cy + Math.sin(end) * r;
    return { path: `M ${x1} ${y1} A ${r} ${r} 0 ${large} 1 ${x2} ${y2}`, color: d.color, label: d.label, value: d.value };
  });
  return (
    <svg viewBox={`0 0 ${size} ${size}`} width={size} height={size}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#F0ECE5" strokeWidth={thickness} />
      {slices.map((s, i) => (
        <path key={i} d={s.path} fill="none" stroke={s.color} strokeWidth={thickness} strokeLinecap="butt" />
      ))}
      <text x={cx} y={cy - 6} textAnchor="middle" className="donut-center-num">{Math.round(total).toLocaleString()}</text>
      <text x={cx} y={cy + 14} textAnchor="middle" className="donut-center-label">THB</text>
    </svg>
  );
}

// ---------- Bar chart (grouped) ----------
function BarChart({ groups, series, height = 220, yFormat = (v) => v }) {
  const w = 720, h = height;
  const padL = 44, padR = 12, padT = 16, padB = 28;
  const innerW = w - padL - padR, innerH = h - padT - padB;
  const all = series.flatMap(s => s.values);
  const maxV = Math.max(...all);
  const yMax = Math.ceil(maxV * 1.1);
  const groupW = innerW / groups.length;
  const barW = Math.min(18, (groupW - 12) / series.length);
  const y = (v) => padT + innerH - (v / yMax) * innerH;

  const ticks = 4;
  const tickValues = Array.from({ length: ticks + 1 }, (_, i) => (yMax * i) / ticks);

  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="chart-svg">
      {tickValues.map((tv, i) => (
        <g key={i}>
          <line x1={padL} x2={w - padR} y1={y(tv)} y2={y(tv)} stroke="#EEEAE3" strokeWidth="1" />
          <text x={padL - 8} y={y(tv) + 4} textAnchor="end" className="chart-axis-text">{yFormat(Math.round(tv))}</text>
        </g>
      ))}
      {groups.map((g, gi) => {
        const gx = padL + gi * groupW + groupW / 2;
        return (
          <g key={gi}>
            <text x={gx} y={h - 8} textAnchor="middle" className="chart-axis-text">{g}</text>
            {series.map((s, si) => {
              const v = s.values[gi];
              const totalBars = series.length;
              const offset = (si - (totalBars - 1) / 2) * (barW + 3);
              const bx = gx + offset - barW / 2;
              const by = y(v);
              return <rect key={si} x={bx} y={by} width={barW} height={padT + innerH - by} fill={s.color} rx="2" />;
            })}
          </g>
        );
      })}
    </svg>
  );
}

// ---------- Sparkline (KPI cards) ----------
function Spark({ values, color = "#EA580C", height = 36, width = 120 }) {
  const minV = Math.min(...values);
  const maxV = Math.max(...values);
  const range = maxV - minV || 1;
  const x = (i) => (i / (values.length - 1)) * width;
  const y = (v) => height - ((v - minV) / range) * (height - 4) - 2;
  const path = values.map((v, i) => `${i === 0 ? "M" : "L"} ${x(i)} ${y(v)}`).join(" ");
  const area = `${path} L ${width} ${height} L 0 ${height} Z`;
  return (
    <svg viewBox={`0 0 ${width} ${height}`} width={width} height={height} preserveAspectRatio="none">
      <path d={area} fill={color} opacity="0.08" />
      <path d={path} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />
    </svg>
  );
}

window.LineChart = LineChart;
window.DonutChart = DonutChart;
window.BarChart = BarChart;
window.Spark = Spark;
