'use client'
// src/components/home/KpiRow.tsx
// Input: aucun — KPI globaux depuis computeGlobalKpis()
// Output: 4 cards KPI avec Stat + SparkLine, animation stagger entrée
// Rationale: lecture immédiate du statut global (US1)

import { useMemo } from 'react'
import { motion } from 'framer-motion'
import { Activity, Cpu, TriangleAlert, Users } from 'lucide-react'
import { Card } from '@/components/ui/Card'
import { Stat } from '@/components/ui/Stat'
import { SparkLine } from '@/components/charts/SparkLine'
import { computeGlobalKpis } from '@/lib/mock'
import type { Kpi } from '@/types'

const EASE_OUT = [0.16, 1, 0.3, 1]

const KPI_ICONS = [Activity, Cpu, TriangleAlert, Users]

const KPI_COLORS = ['#3DB8E8', '#34D399', '#F87171', '#818CF8']

// Sparkline mock cohérent par KPI
function makeSparkline(seed: number, points = 14): number[] {
  const out: number[] = []
  let v = 50 + seed * 10
  for (let i = 0; i < points; i++) {
    v += (Math.sin(i * 0.9 + seed) * 8 + (Math.random() - 0.5) * 6)
    out.push(Math.max(5, v))
  }
  return out
}

interface KpiCardProps {
  kpi: Kpi
  index: number
}

function KpiCard({ kpi, index }: KpiCardProps) {
  const Icon = KPI_ICONS[index] ?? Activity
  const color = KPI_COLORS[index] ?? '#3DB8E8'
  // Sparkline déterministe basé sur la valeur
  const sparkPoints = useMemo(() => makeSparkline(index + kpi.value * 0.01), [index, kpi.value])

  return (
    <motion.div
      initial={{ opacity: 0, y: 10 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.35, delay: index * 0.06, ease: EASE_OUT }}
    >
      <Card padding="md" className="flex flex-col gap-3 h-full">
        {/* Header label + icône */}
        <div className="flex items-center justify-between">
          <span className="text-label text-text-muted uppercase tracking-[0.05em]">
            {kpi.label}
          </span>
          <span
            className="p-1.5 rounded-md"
            style={{ background: `${color}18` }}
          >
            <Icon size={14} strokeWidth={1.5} style={{ color }} />
          </span>
        </div>

        {/* Valeur principale */}
        <Stat
          label=""
          value={kpi.value}
          unit={kpi.unit}
          delta={kpi.delta}
          trend={kpi.trend}
          className="gap-0.5"
        />

        {/* SparkLine */}
        <div className="mt-1">
          <SparkLine
            points={sparkPoints}
            width={160}
            height={28}
            color={color}
          />
        </div>
      </Card>
    </motion.div>
  )
}

export function KpiRow() {
  const kpis = useMemo(() => computeGlobalKpis(), [])
  // On affiche les 4 premiers KPI
  const displayed = kpis.slice(0, 4)

  return (
    <div className="grid grid-cols-4 gap-4">
      {displayed.map((kpi, i) => (
        <KpiCard key={kpi.label} kpi={kpi} index={i} />
      ))}
    </div>
  )
}
