// HeroKpiBand — bandeau 4 cards KPI XL avec sparkline SVG inline + delta sémantique
// Stack : React 18 CDN + Babel in-browser. NO import/export.
// Exposé via window.HeroKpiBand.
//
// API :
//   <HeroKpiBand items={[
//     {
//       label: "Cap rate moyen",
//       value: "5.8 %",                        // string déjà formatée
//       subValue: "réalisé YTD : 45 000 $",   // optionnel — petite ligne sous la valeur principale
//       sparkline: [4.9,5.1,5.3,5.4,5.6,5.7,5.8], // 7 valeurs numériques
//       sparklineIsMock: true,                  // optionnel — affiche un title indiquant l'origine de la série
//       delta: { value: "+0.4 pt", sign: "pos" },   // sign: 'pos'|'neg'|'neutral'
//       href: "#/..."                           // optionnel — rend la card cliquable
//     },
//     // ... 3 autres
//   ]} />

// ── Sparkline SVG ─────────────────────────────────────────────────────────────
// viewBox 0 0 60 24, stroke var(--accent), fill none
// Petit cercle plein sur le dernier point (radius 1.6).
// Si tous les points sont égaux → ligne horizontale à y=12.

function SparklineSVG({ data, isMock }) {
  if (!data || data.length === 0) return null;

  const W = 60;
  const H = 24;
  const n = data.length;
  const mn = Math.min(...data);
  const mx = Math.max(...data);
  const range = mx - mn;

  // Calcul des coordonnées
  const pts = data.map((v, i) => {
    const x = i * (W / (n - 1 || 1));
    const y = range === 0 ? 12 : H - ((v - mn) / range) * H;
    return [x, y];
  });

  // Path "M x0,y0 L x1,y1 ..."
  const d = pts.map(([x, y], i) => `${i === 0 ? 'M' : 'L'} ${x.toFixed(1)},${y.toFixed(1)}`).join(' ');

  const [lastX, lastY] = pts[pts.length - 1];

  return (
    <svg
      width={W}
      height={H}
      viewBox={`0 0 ${W} ${H}`}
      aria-hidden="true"
      className="hero-kpi-sparkline"
      style={{ overflow: 'visible', opacity: isMock ? 0.55 : 1 }}
      data-mock={isMock ? 'true' : 'false'}
    >
      {isMock && (
        <title>Série bootstrap (pas encore 7 jours d'historique réel)</title>
      )}
      <path
        d={d}
        stroke="var(--accent)"
        strokeWidth="1.5"
        fill="none"
        strokeLinecap="round"
        strokeLinejoin="round"
      />
      <circle
        cx={lastX.toFixed(1)}
        cy={lastY.toFixed(1)}
        r="1.6"
        fill="var(--accent)"
      />
    </svg>
  );
}

// ── Card individuelle ─────────────────────────────────────────────────────────

function HeroKpiCard({ label, value, subValue, sparkline, sparklineIsMock, delta, href }) {
  const clickable = !!href;

  const inner = (
    <>
      <span className="hero-kpi-label">{label}</span>

      <div className="hero-kpi-row">
        <span className="hero-kpi-value">{value}</span>
        {sparkline && sparkline.length > 0 && (
          <SparklineSVG data={sparkline} isMock={!!sparklineIsMock} />
        )}
      </div>

      {subValue && (
        <span className="hero-kpi-subvalue">{subValue}</span>
      )}

      {delta ? (
        <span className="hero-kpi-delta" data-sign={delta.sign || 'neutral'}>
          {delta.sign === 'pos' ? '▲' : delta.sign === 'neg' ? '▼' : ''}
          {' '}{delta.value}
        </span>
      ) : (
        <span className="hero-kpi-delta-empty" aria-hidden="true" />
      )}
    </>
  );

  if (clickable) {
    return (
      <a
        href={href}
        className="hero-kpi-card"
        data-clickable="true"
        aria-label={`${label} : ${value}`}
      >
        {inner}
      </a>
    );
  }

  return (
    <div className="hero-kpi-card" data-clickable="false">
      {inner}
    </div>
  );
}

// ── Composant principal ───────────────────────────────────────────────────────

function HeroKpiBand({ items }) {
  if (!items || items.length === 0) return null;

  return (
    <div className="hero-kpi-band" role="region" aria-label="KPIs principaux">
      {items.map((item, i) => (
        <HeroKpiCard
          key={i}
          label={item.label}
          value={item.value}
          subValue={item.subValue}
          sparkline={item.sparkline}
          sparklineIsMock={item.sparklineIsMock}
          delta={item.delta}
          href={item.href}
        />
      ))}
    </div>
  );
}

// Exposition globale
window.HeroKpiBand = HeroKpiBand;
