// SVG-based charts — no external library
// Styled to match brand: navy/teal/green palette

const PALETTE = ['#1b5c8e', '#5baa6f', '#c98a2a', '#3a96c4', '#7d8da0', '#a45fc4', '#c0392b'];

// Multi-line chart
const LineChart = ({ series, height = 240, ySuffix = '', showLegend = true, threshold = null, area = false, yMin = null, yMax = null, smoothed = true }) => {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(600);
  React.useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver((e) => setW(e[0].contentRect.width));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  const padL = 42, padR = 18, padT = 16, padB = 28;
  const innerW = Math.max(50, w - padL - padR);
  const innerH = height - padT - padB;

  // collect all y values
  let allY = [];
  series.forEach(s => s.data.forEach(d => allY.push(d)));
  let yLo = yMin != null ? yMin : Math.min(0, ...allY);
  let yHi = yMax != null ? yMax : Math.max(...allY) * 1.08;
  if (yHi === yLo) yHi = yLo + 1;

  const maxLen = Math.max(...series.map(s => s.data.length));
  const x = (i) => padL + (i / Math.max(1, maxLen - 1)) * innerW;
  const y = (v) => padT + innerH - ((v - yLo) / (yHi - yLo)) * innerH;

  // y ticks
  const ticks = 4;
  const tickVals = [];
  for (let i = 0; i <= ticks; i++) tickVals.push(yLo + (yHi - yLo) * (i / ticks));

  function buildPath(data) {
    if (!data.length) return '';
    if (!smoothed) {
      return data.map((v, i) => (i === 0 ? 'M' : 'L') + x(i) + ',' + y(v)).join(' ');
    }
    // simple smoothing (catmull-rom-ish bezier)
    let d = `M ${x(0)},${y(data[0])}`;
    for (let i = 0; i < data.length - 1; i++) {
      const x0 = x(i), y0 = y(data[i]);
      const x1 = x(i + 1), y1 = y(data[i + 1]);
      const cx = (x0 + x1) / 2;
      d += ` C ${cx},${y0} ${cx},${y1} ${x1},${y1}`;
    }
    return d;
  }

  return (
    <div ref={ref} style={{ width: '100%', height }}>
      <svg width={w} height={height}>
        {/* Y grid */}
        {tickVals.map((v, i) => (
          <g key={i}>
            <line x1={padL} x2={padL + innerW} y1={y(v)} y2={y(v)} stroke="#edf1f5" strokeWidth="1" />
            <text x={padL - 8} y={y(v) + 4} fontSize="10.5" fontFamily="JetBrains Mono, monospace" fill="#7d8da0" textAnchor="end">
              {Math.round(v).toLocaleString()}{ySuffix}
            </text>
          </g>
        ))}
        {/* X axis baseline */}
        <line x1={padL} x2={padL + innerW} y1={padT + innerH} y2={padT + innerH} stroke="#d4dce4" strokeWidth="1" />

        {/* threshold */}
        {threshold != null && (
          <g>
            <line x1={padL} x2={padL + innerW} y1={y(threshold)} y2={y(threshold)} stroke="#c98a2a" strokeWidth="1" strokeDasharray="4 4" />
            <text x={padL + innerW - 4} y={y(threshold) - 4} fontSize="10" fontFamily="JetBrains Mono, monospace" fill="#c98a2a" textAnchor="end">
              warn @ {threshold}{ySuffix}
            </text>
          </g>
        )}

        {/* area fills */}
        {area && series.map((s, idx) => {
          const color = s.color || PALETTE[idx % PALETTE.length];
          const path = buildPath(s.data);
          if (!path) return null;
          const fillPath = path + ` L ${x(s.data.length - 1)},${padT + innerH} L ${x(0)},${padT + innerH} Z`;
          return (
            <path key={'a' + idx} d={fillPath} fill={color} fillOpacity="0.08" />
          );
        })}

        {/* lines */}
        {series.map((s, idx) => {
          const color = s.color || PALETTE[idx % PALETTE.length];
          return (
            <path key={idx} d={buildPath(s.data)} fill="none" stroke={color} strokeWidth="2"
              strokeLinejoin="round" strokeLinecap="round" />
          );
        })}

        {/* end-of-series dots */}
        {series.map((s, idx) => {
          const color = s.color || PALETTE[idx % PALETTE.length];
          if (!s.data.length) return null;
          const last = s.data.length - 1;
          return (
            <circle key={'d' + idx} cx={x(last)} cy={y(s.data[last])} r="3" fill="#fff" stroke={color} strokeWidth="2" />
          );
        })}

        {/* X labels (hour labels) */}
        {[0, 0.25, 0.5, 0.75, 1].map((t, i) => {
          const hr = Math.round(t * 24);
          const lbl = hr === 0 ? '00:00' : hr === 24 ? '24:00' : (hr < 10 ? '0' + hr : hr) + ':00';
          return (
            <text key={i} x={padL + t * innerW} y={padT + innerH + 16} fontSize="10.5" fontFamily="JetBrains Mono, monospace"
              fill="#7d8da0" textAnchor="middle">{lbl}</text>
          );
        })}
      </svg>

      {showLegend && series.length > 1 && (
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', padding: '8px 4px 0' }}>
          {series.map((s, idx) => (
            <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12, color: 'var(--ink-700)' }}>
              <span style={{ width: 12, height: 3, background: s.color || PALETTE[idx % PALETTE.length], borderRadius: 2 }} />
              {s.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// Stacked bar chart (consumption by device per day)
const StackedBarChart = ({ data, labels, series, height = 240, ySuffix = ' kWh', showLegend = true }) => {
  const ref = React.useRef(null);
  const [w, setW] = React.useState(600);
  React.useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver((e) => setW(e[0].contentRect.width));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  const padL = 42, padR = 18, padT = 16, padB = 28;
  const innerW = Math.max(50, w - padL - padR);
  const innerH = height - padT - padB;

  // data is array of arrays: data[seriesIdx][barIdx]
  const totals = labels.map((_, i) => data.reduce((s, d) => s + (d[i] || 0), 0));
  const yMax = Math.max(...totals) * 1.1;

  const x = (i) => padL + (i / labels.length) * innerW + (innerW / labels.length) * 0.15;
  const bw = (innerW / labels.length) * 0.7;
  const y = (v) => padT + innerH - (v / yMax) * innerH;

  const ticks = [0, 0.25, 0.5, 0.75, 1].map(t => yMax * t);

  return (
    <div ref={ref} style={{ width: '100%', height }}>
      <svg width={w} height={height}>
        {ticks.map((v, i) => (
          <g key={i}>
            <line x1={padL} x2={padL + innerW} y1={y(v)} y2={y(v)} stroke="#edf1f5" />
            <text x={padL - 8} y={y(v) + 4} fontSize="10.5" fontFamily="JetBrains Mono, monospace" fill="#7d8da0" textAnchor="end">
              {Math.round(v).toLocaleString()}
            </text>
          </g>
        ))}
        <line x1={padL} x2={padL + innerW} y1={padT + innerH} y2={padT + innerH} stroke="#d4dce4" />

        {labels.map((lbl, i) => {
          let acc = 0;
          return (
            <g key={i}>
              {data.map((sData, si) => {
                const v = sData[i] || 0;
                const h = (v / yMax) * innerH;
                const yPos = padT + innerH - (acc + v) / yMax * innerH;
                acc += v;
                return (
                  <rect key={si} x={x(i)} y={yPos} width={bw} height={h}
                    fill={series[si].color || PALETTE[si % PALETTE.length]}
                    rx="2"
                  />
                );
              })}
              <text x={x(i) + bw / 2} y={padT + innerH + 16} fontSize="10.5" fontFamily="JetBrains Mono, monospace"
                fill="#7d8da0" textAnchor="middle">{lbl}</text>
            </g>
          );
        })}
      </svg>

      {showLegend && (
        <div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', padding: '8px 4px 0' }}>
          {series.map((s, idx) => (
            <div key={idx} style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
              <span style={{ width: 10, height: 10, background: s.color || PALETTE[idx % PALETTE.length], borderRadius: 2 }} />
              {s.label}
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

// Area chart - single series, dense
const AreaChart = ({ data, height = 120, color = '#1b5c8e', ySuffix = ' kW' }) => {
  return <LineChart series={[{ data, color }]} height={height} ySuffix={ySuffix} showLegend={false} area={true} />;
};

// Arc gauge — used for "Sun Power" + "Battery"
const ArcGauge = ({ value, max, label, unit, color = '#5baa6f', size = 180, sub }) => {
  const pct = Math.max(0, Math.min(1, value / max));
  const cx = size / 2, cy = size / 2;
  const r = size / 2 - 18;
  const startAngle = Math.PI * 0.75;
  const endAngle = Math.PI * 2.25;
  const angle = startAngle + (endAngle - startAngle) * pct;
  const x1 = cx + r * Math.cos(startAngle), y1 = cy + r * Math.sin(startAngle);
  const x2 = cx + r * Math.cos(angle), y2 = cy + r * Math.sin(angle);
  const x3 = cx + r * Math.cos(endAngle), y3 = cy + r * Math.sin(endAngle);
  const largeArcFull = (endAngle - startAngle) > Math.PI ? 1 : 0;
  const largeArc = (angle - startAngle) > Math.PI ? 1 : 0;
  return (
    <svg width={size} height={size}>
      <path d={`M ${x1} ${y1} A ${r} ${r} 0 ${largeArcFull} 1 ${x3} ${y3}`}
        fill="none" stroke="#edf1f5" strokeWidth="14" strokeLinecap="round" />
      <path d={`M ${x1} ${y1} A ${r} ${r} 0 ${largeArc} 1 ${x2} ${y2}`}
        fill="none" stroke={color} strokeWidth="14" strokeLinecap="round" />
      <text x={cx} y={cy - 4} textAnchor="middle" fontSize="28" fontFamily="JetBrains Mono, monospace"
        fontWeight="600" fill="#0d2840">
        {typeof value === 'number' ? value.toFixed(value < 10 ? 1 : 0) : value}
      </text>
      {unit && <text x={cx} y={cy + 14} textAnchor="middle" fontSize="11" fill="#5a6c7f" fontWeight="600">{unit}</text>}
      {sub && <text x={cx} y={cy + 30} textAnchor="middle" fontSize="10.5" fill="#7d8da0">{sub}</text>}
    </svg>
  );
};

// Ring (for SOC %)
const RingGauge = ({ value, label, sub, size = 180, color = '#1b5c8e' }) => {
  const pct = Math.max(0, Math.min(100, value)) / 100;
  const cx = size / 2, cy = size / 2;
  const r = size / 2 - 16;
  const circ = 2 * Math.PI * r;
  return (
    <svg width={size} height={size}>
      <circle cx={cx} cy={cy} r={r} fill="none" stroke="#edf1f5" strokeWidth="14" />
      <circle cx={cx} cy={cy} r={r} fill="none" stroke={color} strokeWidth="14"
        strokeDasharray={circ}
        strokeDashoffset={circ * (1 - pct)}
        strokeLinecap="round"
        transform={`rotate(-90 ${cx} ${cy})`} />
      <text x={cx} y={cy - 2} textAnchor="middle" fontSize="32" fontFamily="JetBrains Mono, monospace" fontWeight="600" fill="#0d2840">
        {Math.round(value)}<tspan fontSize="14" fill="#5a6c7f" fontFamily="Manrope">%</tspan>
      </text>
      {sub && <text x={cx} y={cy + 22} textAnchor="middle" fontSize="11" fill="#7d8da0" fontWeight="500">{sub}</text>}
    </svg>
  );
};

// Sparkline (tiny, no axes)
const Sparkline = ({ data, color = '#1b5c8e', height = 36, width = 100 }) => {
  const maxV = Math.max(...data) || 1;
  const minV = Math.min(...data, 0);
  const x = (i) => (i / Math.max(1, data.length - 1)) * width;
  const y = (v) => height - ((v - minV) / (maxV - minV || 1)) * (height - 4) - 2;
  const path = data.map((v, i) => (i === 0 ? 'M' : 'L') + x(i) + ',' + y(v)).join(' ');
  const area = path + ` L ${width} ${height} L 0 ${height} Z`;
  return (
    <svg width={width} height={height} style={{ display: 'block' }}>
      <path d={area} fill={color} fillOpacity="0.12" />
      <path d={path} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" />
    </svg>
  );
};

Object.assign(window, { LineChart, StackedBarChart, AreaChart, ArcGauge, RingGauge, Sparkline, PALETTE });
