/* KpiRow — four KPI blocks */
function Sparkline({ points, color = 'var(--accent)' }) {
  const max = Math.max(...points), min = Math.min(...points);
  const w = 100, h = 26;
  const d = points.map((p, i) => {
    const x = (i / (points.length - 1)) * w;
    const y = h - ((p - min) / (max - min || 1)) * h;
    return `${i === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`;
  }).join(' ');
  return (
    <svg viewBox={`0 0 ${w} ${h}`} preserveAspectRatio="none" className="k-spark">
      <path d={d} fill="none" stroke={color} strokeWidth="1.5"/>
    </svg>
  );
}

function KpiCard({ label, value, unit, delta, deltaDir = 'up', sparkPoints, iconPath }) {
  return (
    <div className="kpi-card">
      <div className="k-icon">
        <svg viewBox="0 0 24 24">{iconPath}</svg>
      </div>
      <div className="k-label">{label}</div>
      <div className="k-num">{value}{unit && <span className="u">{unit}</span>}</div>
      <div className="k-foot">
        <span className={`k-delta ${deltaDir}`}>
          {deltaDir === 'up' ? '▲' : deltaDir === 'down' ? '▼' : '—'} {delta}
        </span>
        {sparkPoints && <Sparkline points={sparkPoints}/>}
      </div>
    </div>
  );
}

function KpiRow() {
  return (
    <div className="kpi-row">
      <KpiCard
        label="Output today" value="2,340" unit="MWh"
        delta="12%" deltaDir="up"
        sparkPoints={[20, 24, 22, 28, 26, 32, 30, 36, 34, 42, 40, 48]}
        iconPath={<><path d="M9.6 4.6A2 2 0 1 1 11 8H2" strokeLinecap="round"/><path d="M12.6 19.4A2 2 0 1 0 14 16H2" strokeLinecap="round"/><path d="M17.5 8a2.5 2.5 0 1 1 2 4H2" strokeLinecap="round"/></>}
      />
      <KpiCard
        label="Availability" value="98.2" unit="%"
        delta="0.6 pts" deltaDir="up"
        sparkPoints={[96, 97, 96.5, 97.2, 97, 97.8, 98, 97.9, 98.1, 98.2, 98.1, 98.2]}
        iconPath={<><path d="M22 12h-4l-3 9L9 3l-3 9H2" strokeLinecap="round" strokeLinejoin="round"/></>}
      />
      <KpiCard
        label="Wind · avg" value="12.4" unit="m/s"
        delta="steady" deltaDir="flat"
        sparkPoints={[12.1, 12.3, 12.2, 12.5, 12.4, 12.3, 12.6, 12.4, 12.5, 12.4, 12.3, 12.4]}
        iconPath={<><path d="M2 12h20" strokeLinecap="round"/><path d="M4 6h14" strokeLinecap="round"/><path d="M4 18h10" strokeLinecap="round"/></>}
      />
      <KpiCard
        label="Active alerts" value="3" unit=""
        delta="1 new" deltaDir="down"
        sparkPoints={[1, 1, 2, 2, 1, 2, 3, 2, 2, 3, 3, 3]}
        iconPath={<><path d="M10.3 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" strokeLinecap="round" strokeLinejoin="round"/><path d="M12 9v4" strokeLinecap="round"/><path d="M12 17h.01" strokeLinecap="round"/></>}
      />
    </div>
  );
}

Object.assign(window, { KpiRow, KpiCard, Sparkline });
