/* KPI cards — supports two styles via `cardStyle` tweak:
   - 'number'  : big number forward, tiny sparkline at corner
   - 'chart'   : number + larger gradient area sparkline filling lower 60%
*/

function KpiSparkline({ data, color = 'pos', filled = true, w = 120, h = 32 }) {
  const min = Math.min(...data);
  const max = Math.max(...data);
  const r = Math.max(1, max - min);
  const stepX = w / (data.length - 1);
  const pts = data.map((v, i) => [i * stepX, h - 2 - ((v - min) / r) * (h - 4)]);
  const line = pts.map((p, i) => (i === 0 ? 'M' : 'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  const area = line + ` L ${w} ${h} L 0 ${h} Z`;
  const stroke = color === 'pos' ? 'var(--cb-pos)' :
                 color === 'warn' ? 'var(--cb-warn)' :
                 color === 'neg' ? 'var(--cb-neg)' : 'var(--cb-fg-2)';
  const grad = `cb-grad-${color}`;
  return (
    <svg width={w} height={h} viewBox={`0 0 ${w} ${h}`} className="cb-spark">
      {filled && (
        <>
          <defs>
            <linearGradient id={grad} x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor={stroke} stopOpacity=".28" />
              <stop offset="100%" stopColor={stroke} stopOpacity="0" />
            </linearGradient>
          </defs>
          <path d={area} fill={`url(#${grad})`} />
        </>
      )}
      <path d={line} fill="none" stroke={stroke} strokeWidth="1.6"
            strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  );
}

function Delta({ value, label }) {
  const up = value >= 0;
  return (
    <span className="cb-delta" data-dir={up ? 'up' : 'down'}>
      {up ? <IconArrowUR size={12} /> : <IconArrowDR size={12} />}
      <b>{(up ? '+' : '−') + Math.abs(value).toFixed(1) + '%'}</b>
      {label && <span>{label}</span>}
    </span>
  );
}

function KpiCard({ kpi, cardStyle }) {
  const isChart = cardStyle === 'chart';
  return (
    <article className="cb-kpi" data-style={cardStyle}>
      <header className="cb-kpi-head">
        <div>
          <div className="cb-kpi-label">{kpi.label}</div>
          <div className="cb-kpi-sub">{kpi.sub}</div>
        </div>
        {!isChart && (
          <KpiSparkline data={kpi.spark} color={kpi.color} w={72} h={26} filled={false} />
        )}
      </header>

      <div className="cb-kpi-value-row">
        <div className="cb-kpi-value">{CB.fmtMoney(kpi.value)}</div>
        <Delta value={kpi.delta} label={kpi.deltaLabel} />
      </div>

      {kpi.secondary && (
        <div className="cb-kpi-sec">
          <span>{kpi.secondary.label}</span>
          <b>{kpi.secondary.value}</b>
        </div>
      )}

      {isChart && (
        <div className="cb-kpi-chart">
          <KpiSparkline data={kpi.spark} color={kpi.color} w={300} h={60} filled={true} />
        </div>
      )}
    </article>
  );
}

function KpiRow({ cardStyle }) {
  return (
    <section className="cb-kpi-row">
      {CB.kpis.map((k) => <KpiCard key={k.id} kpi={k} cardStyle={cardStyle} />)}
    </section>
  );
}

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