/* global React */
const { useState: useStateC, useMemo: useMemoC } = React;

const LineChart = ({ series, height = 180, color = 'var(--info)', fill = true, formatY = (v) => v }) => {
  if (!series || series.length === 0) return <div className="empty">No data</div>;
  const w = 600, h = height;
  const pad = { l: 40, r: 12, t: 8, b: 22 };
  const innerW = w - pad.l - pad.r;
  const innerH = h - pad.t - pad.b;
  const max = Math.max(...series, 1);
  const range = max || 1;
  const step = innerW / (series.length - 1);
  const pts = series.map((v, i) => `${(pad.l + i * step).toFixed(1)},${(pad.t + innerH - (v / range) * innerH).toFixed(1)}`);
  const pathD = 'M ' + pts.join(' L ');
  const fillD = pathD + ` L ${pad.l + innerW},${pad.t + innerH} L ${pad.l},${pad.t + innerH} Z`;
  const yTicks = [0, 0.25, 0.5, 0.75, 1].map(p => max * p);
  return (
    <svg viewBox={`0 0 ${w} ${h}`} width="100%" height={h} preserveAspectRatio="none">
      {yTicks.map((tv, i) => {
        const y = pad.t + innerH - (tv / range) * innerH;
        return (
          <g key={i}>
            <line x1={pad.l} y1={y} x2={pad.l + innerW} y2={y} stroke="var(--border)" strokeWidth="1" strokeDasharray="2 3"/>
            <text x={pad.l - 6} y={y + 3} fontSize="10" fontFamily="Geist Mono" fill="var(--muted-foreground)" textAnchor="end">{formatY(tv)}</text>
          </g>
        );
      })}
      {fill && <path d={fillD} fill={color} opacity="0.18"/>}
      <path d={pathD} fill="none" stroke={color} strokeWidth="1.5" strokeLinejoin="round"/>
      {[0, Math.floor(series.length/2), series.length-1].map(i => (
        <text key={i} x={pad.l + i * step} y={h - 6} fontSize="10" fontFamily="Geist Mono" fill="var(--muted-foreground)" textAnchor="middle">
          {-(series.length - 1 - i)}m
        </text>
      ))}
    </svg>
  );
};

const DonutChart = ({ data, size = 140 }) => {
  const total = data.reduce((s, d) => s + d.value, 0) || 1;
  const r = size/2 - 8, c = size/2, stroke = 16;
  let acc = 0;
  return (
    <div className="donut-wrap">
      <svg className="donut-svg" width={size} height={size} viewBox={`0 0 ${size} ${size}`}>
        <circle cx={c} cy={c} r={r} fill="none" stroke="var(--muted)" strokeWidth={stroke}/>
        {data.map((d, i) => {
          const pct = d.value / total;
          const dash = pct * 2 * Math.PI * r;
          const offset = -acc * 2 * Math.PI * r;
          acc += pct;
          return <circle key={i} cx={c} cy={c} r={r} fill="none" stroke={d.color} strokeWidth={stroke}
            strokeDasharray={`${dash} ${2 * Math.PI * r - dash}`} strokeDashoffset={offset}
            transform={`rotate(-90 ${c} ${c})`}/>;
        })}
        <text x={c} y={c-2} textAnchor="middle" fontSize="20" fontFamily="Geist Mono" fontWeight="600" fill="var(--foreground)">{window.fmtNum(total)}</text>
        <text x={c} y={c+14} textAnchor="middle" fontSize="10" fontFamily="Geist Mono" fill="var(--muted-foreground)">total</text>
      </svg>
      <div className="donut-legend">
        {data.map((d, i) => (
          <div key={i} className="item">
            <span className="sw" style={{ background: d.color }}></span>
            <span className="lb">{d.label}</span>
            <span className="v">{window.fmtNum(d.value)} <span style={{ opacity: 0.6 }}>({((d.value/total)*100).toFixed(1)}%)</span></span>
          </div>
        ))}
      </div>
    </div>
  );
};

const Histogram = ({ data }) => {
  const max = Math.max(...data.map(d => d.count), 1);
  return (
    <div className="histogram">
      {data.map((d, i) => (
        <div key={i} className="histo-bar" title={`${d.label}: ${d.count}`}>
          <div className="v">{window.fmtNum(d.count)}</div>
          <div className="bar" style={{ height: ((d.count/max)*100) + '%' }}></div>
          <div className="lbl">{d.label}</div>
        </div>
      ))}
    </div>
  );
};

const Heatmap = ({ data }) => {
  const days = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
  const max = Math.max(...data.flat(), 1);
  return (
    <div>
      <div className="heatmap" style={{ marginBottom: 4 }}>
        <div></div>
        {Array.from({ length: 24 }, (_, h) => <div key={h} className="lbl-c">{h % 3 === 0 ? h : ''}</div>)}
      </div>
      {data.map((row, d) => (
        <div key={d} className="heatmap" style={{ marginBottom: 2 }}>
          <div className="lbl-r">{days[d]}</div>
          {row.map((v, h) => {
            const intensity = v / max;
            const color = intensity < 0.05 ? 'var(--muted)' : `oklch(${0.45 + intensity * 0.35} ${0.05 + intensity * 0.14} 184)`;
            return <div key={h} className="cell" style={{ background: color }} title={`${days[d]} ${h}:00 — ${v}`}></div>;
          })}
        </div>
      ))}
    </div>
  );
};

window.LineChart = LineChart;
window.DonutChart = DonutChart;
window.Histogram = Histogram;
window.Heatmap = Heatmap;
