"use client"

import Link from "next/link"
import { useEffect, useMemo, useState } from "react"
import { useLocale, useTranslations } from "next-intl"
import {
  AreaChart, Area, BarChart, Bar, PieChart, Pie, Cell,
  XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer,
} from "recharts"
import {
  Briefcase, Users, UserRound, TrendingUp, TrendingDown,
  AlertTriangle, CheckCircle2, Clock3, ArrowUpRight, ArrowDownRight,
  RefreshCcw, ChevronRight, Inbox, ArrowRight, Wallet,
  BarChart3, Building2, MapPin,
} from "lucide-react"

import { listCases, type Case } from "@/src/lib/api/cases"
import { listCustomers, type Customer } from "@/src/lib/api/customers"
import { listDebtors } from "@/src/lib/api/debtors"
import { fetchMe, type Me } from "@/src/lib/api/me"
import { useCountry } from "@/src/contexts/CountryContext"

// ── Palette navy/teal ACX ──────────────────────────────────────────────────
const C = {
  navy:   "#1a3578",
  navy2:  "#2655b0",
  teal:   "#4dba96",
  teal2:  "#3aa07e",
  amber:  "#f59e0b",
  red:    "#ef4444",
  blue:   "#0ea5e9",
  muted:  "#64748b",
  border: "rgba(15,23,42,.07)",
  bg:     "#f7f8fc",
}

function cx(...c: Array<string | false | null | undefined>) {
  return c.filter(Boolean).join(" ")
}

// ── Tooltip ────────────────────────────────────────────────────────────────
function NiceTooltip({ active, payload, label }: any) {
  if (!active || !payload?.length) return null
  return (
    <div className="rounded-xl border bg-white px-3 py-2 shadow-lg text-xs" style={{ borderColor: C.border }}>
      {label && <div className="mb-1.5 font-semibold text-slate-600">{label}</div>}
      {payload.map((p: any, i: number) => (
        <div key={i} className="flex items-center justify-between gap-5">
          <span className="flex items-center gap-1.5 text-slate-500">
            <span className="h-2 w-2 rounded-full" style={{ background: p.color }} />
            {p.name}
          </span>
          <span className="font-bold text-slate-900">
            {typeof p.value === "number" && p.value > 999
              ? new Intl.NumberFormat("fr-FR").format(p.value)
              : p.value}
          </span>
        </div>
      ))}
    </div>
  )
}

// ── KPI Card ───────────────────────────────────────────────────────────────
function KpiCard({
  icon, label, value, sub, delta, up, tone = "navy", loading,
}: {
  icon: React.ReactNode
  label: string
  value: string
  sub?: string
  delta?: string
  up?: boolean
  tone?: "navy" | "teal" | "amber" | "red" | "blue"
  loading?: boolean
}) {
  const styles = {
    navy:  { bg: `rgba(26,53,120,.10)`,  ring: `rgba(26,53,120,.18)`,  color: C.navy },
    teal:  { bg: `rgba(77,186,150,.12)`, ring: `rgba(77,186,150,.22)`, color: C.teal },
    amber: { bg: `rgba(245,158,11,.12)`, ring: `rgba(245,158,11,.22)`, color: C.amber },
    red:   { bg: `rgba(239,68,68,.10)`,  ring: `rgba(239,68,68,.20)`,  color: C.red },
    blue:  { bg: `rgba(14,165,233,.12)`, ring: `rgba(14,165,233,.22)`, color: C.blue },
  }[tone]

  return (
    <div className="rounded-2xl border bg-white p-4 shadow-sm flex flex-col gap-3" style={{ borderColor: C.border }}>
      <div className="flex items-center justify-between">
        <div className="h-10 w-10 rounded-xl flex items-center justify-center"
          style={{ background: styles.bg, border: `1px solid ${styles.ring}`, color: styles.color }}>
          {icon}
        </div>
        {delta && (
          <span className={cx(
            "inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold",
            up ? "text-emerald-700" : "text-red-600"
          )}
            style={{
              background: up ? "rgba(16,185,129,.10)" : "rgba(239,68,68,.10)",
              border: `1px solid ${up ? "rgba(16,185,129,.18)" : "rgba(239,68,68,.18)"}`,
            }}>
            {up ? <ArrowUpRight className="h-3 w-3" /> : <ArrowDownRight className="h-3 w-3" />}
            {delta}
          </span>
        )}
      </div>
      {loading ? (
        <div className="space-y-1.5">
          <div className="h-7 w-20 animate-pulse rounded-lg bg-slate-100" />
          <div className="h-3 w-28 animate-pulse rounded bg-slate-100" />
        </div>
      ) : (
        <div>
          <div className="text-2xl font-bold text-slate-900 leading-none">{value}</div>
          {sub && <div className="mt-1 text-xs text-slate-400">{sub}</div>}
        </div>
      )}
      <div className="text-[11px] font-semibold uppercase tracking-widest text-slate-400">{label}</div>
    </div>
  )
}

// ── Card wrapper ───────────────────────────────────────────────────────────
function Card({ title, subtitle, right, children }: {
  title: string; subtitle?: string; right?: React.ReactNode; children: React.ReactNode
}) {
  return (
    <div className="rounded-2xl border bg-white shadow-sm overflow-hidden" style={{ borderColor: C.border }}>
      <div className="flex items-start justify-between gap-3 px-5 pt-4 pb-3 border-b" style={{ borderColor: C.border }}>
        <div>
          <div className="text-sm font-semibold text-slate-900">{title}</div>
          {subtitle && <div className="text-xs text-slate-400 mt-0.5">{subtitle}</div>}
        </div>
        {right}
      </div>
      <div className="p-4">{children}</div>
    </div>
  )
}

// ── Status badge ───────────────────────────────────────────────────────────
const STATUS_BG: Record<string, { bg: string; color: string }> = {
  open:        { bg: "rgba(14,165,233,.12)",   color: C.blue },
  in_progress: { bg: "rgba(77,186,150,.12)",   color: C.teal },
  on_hold:     { bg: "rgba(245,158,11,.12)",   color: C.amber },
  closed:      { bg: "rgba(15,23,42,.07)",     color: "#475569" },
}

function StatusBadge({ status, label }: { status: string; label: string }) {
  const s = STATUS_BG[status] ?? { bg: "rgba(15,23,42,.07)", color: "#475569" }
  return (
    <span className="rounded-full px-2.5 py-0.5 text-[11px] font-semibold whitespace-nowrap"
      style={{ background: s.bg, color: s.color }}>
      {label}
    </span>
  )
}

const PRIORITY_COLOR: Record<string, string> = {
  low: "#94a3b8", medium: C.blue, high: C.amber, urgent: C.red,
}

// ── Trend chart (opened vs closed by month) ────────────────────────────────
function TrendChart({ cases, labels }: { cases: Case[]; labels: { empty: string; opened: string; closed: string } }) {
  const data = useMemo(() => {
    const months: Record<string, { month: string; opened: number; closed: number }> = {}
    cases.forEach((c) => {
      const d = new Date(c.opened_at)
      const key = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}`
      const label = d.toLocaleDateString("fr-FR", { month: "short", year: "2-digit" })
      if (!months[key]) months[key] = { month: label, opened: 0, closed: 0 }
      months[key].opened++
      if (c.status === "closed") months[key].closed++
    })
    return Object.entries(months)
      .sort(([a], [b]) => a.localeCompare(b))
      .slice(-8)
      .map(([, v]) => v)
  }, [cases])

  if (data.length === 0) return (
    <div className="flex h-[220px] items-center justify-center text-sm text-slate-400">{labels.empty}</div>
  )

  return (
    <div className="h-[220px]">
      <ResponsiveContainer width="100%" height="100%">
        <AreaChart data={data} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
          <defs>
            <linearGradient id="gOpened" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={C.navy} stopOpacity={0.18} />
              <stop offset="95%" stopColor={C.navy} stopOpacity={0} />
            </linearGradient>
            <linearGradient id="gClosed" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%" stopColor={C.teal} stopOpacity={0.18} />
              <stop offset="95%" stopColor={C.teal} stopOpacity={0} />
            </linearGradient>
          </defs>
          <CartesianGrid strokeDasharray="3 6" vertical={false} stroke="rgba(15,23,42,.06)" />
          <XAxis dataKey="month" tickLine={false} axisLine={false} tick={{ fill: C.muted, fontSize: 11 }} />
          <YAxis tickLine={false} axisLine={false} tick={{ fill: C.muted, fontSize: 11 }} allowDecimals={false} />
          <Tooltip content={<NiceTooltip />} cursor={{ stroke: `${C.navy}20` }} />
          <Area type="monotone" dataKey="opened" name={labels.opened} stroke={C.navy} strokeWidth={2.5} fill="url(#gOpened)" dot={false} activeDot={{ r: 4, fill: C.navy }} />
          <Area type="monotone" dataKey="closed" name={labels.closed} stroke={C.teal} strokeWidth={2.5} fill="url(#gClosed)" dot={false} activeDot={{ r: 4, fill: C.teal }} />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  )
}

// ── Status donut ───────────────────────────────────────────────────────────
function StatusDonut({ cases, labels }: { cases: Case[]; labels: { open: string; in_progress: string; on_hold: string; closed: string; total: string } }) {
  const data = useMemo(() => {
    const counts: Record<string, number> = { open: 0, in_progress: 0, on_hold: 0, closed: 0 }
    cases.forEach((c) => { if (c.status in counts) counts[c.status]++ })
    return [
      { name: labels.open,        value: counts.open,        color: C.blue },
      { name: labels.in_progress, value: counts.in_progress, color: C.teal },
      { name: labels.on_hold,     value: counts.on_hold,     color: C.amber },
      { name: labels.closed,      value: counts.closed,      color: "#1e293b" },
    ].filter((d) => d.value > 0)
  }, [cases, labels])

  const total = data.reduce((s, d) => s + d.value, 0)

  return (
    <div className="grid grid-cols-2 gap-4 items-center">
      <div className="h-[180px]">
        <ResponsiveContainer width="100%" height="100%">
          <PieChart>
            <Pie dataKey="value" nameKey="name" data={data}
              innerRadius={50} outerRadius={76} paddingAngle={3}
              cornerRadius={6} startAngle={90} endAngle={-270}>
              {data.map((d) => <Cell key={d.name} fill={d.color} />)}
            </Pie>
            <Tooltip content={<NiceTooltip />} />
          </PieChart>
        </ResponsiveContainer>
      </div>
      <div className="space-y-2">
        <div className="text-base font-bold text-slate-900">{labels.total.replace("{total}", String(total))}</div>
        {data.map((d) => (
          <div key={d.name} className="flex items-center justify-between text-sm">
            <span className="flex items-center gap-2 text-slate-600">
              <span className="h-2.5 w-2.5 rounded-full shrink-0" style={{ background: d.color }} />
              {d.name}
            </span>
            <span className="font-bold text-slate-900">{d.value}</span>
          </div>
        ))}
      </div>
    </div>
  )
}

// ── Priority bar chart ─────────────────────────────────────────────────────
function PriorityChart({ cases, labels }: { cases: Case[]; labels: { low: string; medium: string; high: string; urgent: string; cases: string } }) {
  const data = useMemo(() => {
    const counts: Record<string, number> = { low: 0, medium: 0, high: 0, urgent: 0 }
    cases.filter((c) => c.status !== "closed").forEach((c) => { if (c.priority in counts) counts[c.priority]++ })
    return [
      { name: labels.low,    value: counts.low,    color: "#94a3b8" },
      { name: labels.medium, value: counts.medium, color: C.blue },
      { name: labels.high,   value: counts.high,   color: C.amber },
      { name: labels.urgent, value: counts.urgent, color: C.red },
    ]
  }, [cases, labels])

  return (
    <div className="h-[180px]">
      <ResponsiveContainer width="100%" height="100%">
        <BarChart data={data} barCategoryGap={20} margin={{ top: 8, right: 8, left: -20, bottom: 0 }}>
          <CartesianGrid strokeDasharray="3 6" vertical={false} stroke="rgba(15,23,42,.06)" />
          <XAxis dataKey="name" tickLine={false} axisLine={false} tick={{ fill: C.muted, fontSize: 11 }} />
          <YAxis tickLine={false} axisLine={false} tick={{ fill: C.muted, fontSize: 11 }} allowDecimals={false} />
          <Tooltip content={<NiceTooltip />} cursor={{ fill: "rgba(15,23,42,.04)" }} />
          <Bar name={labels.cases} dataKey="value" radius={[8, 8, 4, 4]} maxBarSize={44}>
            {data.map((d) => <Cell key={d.name} fill={d.color} />)}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  )
}

// ── Recent cases ───────────────────────────────────────────────────────────
function RecentCases({ cases, locale, labels, statusLabels }: {
  cases: Case[]; locale: string
  labels: { empty: string; reference: string; debtor: string; portfolio: string; balance: string; status: string; priority: string; dueDate: string }
  statusLabels: Record<string, string>
}) {
  const recent = useMemo(() =>
    [...cases]
      .sort((a, b) => new Date(b.opened_at).getTime() - new Date(a.opened_at).getTime())
      .slice(0, 7),
    [cases]
  )

  if (recent.length === 0) return (
    <div className="flex flex-col items-center gap-2 py-10 text-slate-400">
      <Inbox className="h-8 w-8 opacity-40" />
      <p className="text-sm">{labels.empty}</p>
    </div>
  )

  return (
    <div className="overflow-x-auto -mx-4">
      <table className="w-full text-sm min-w-[600px]">
        <thead>
          <tr className="border-b" style={{ borderColor: C.border }}>
            {[labels.reference, labels.debtor, labels.portfolio, labels.balance, labels.status, labels.priority, labels.dueDate].map((h) => (
              <th key={h} className="px-4 pb-2.5 text-left text-[10px] font-bold uppercase tracking-widest text-slate-400">{h}</th>
            ))}
          </tr>
        </thead>
        <tbody>
          {recent.map((c, i) => {
            const bal = Number(c.balance_amount) || 0
            const due = c.due_date ? new Date(c.due_date) : null
            const overdue = due && due < new Date() && c.status !== "closed"
            return (
              <tr key={c.id}
                className={cx("border-b transition-colors hover:bg-slate-50/70", i === recent.length - 1 && "border-0")}
                style={{ borderColor: C.border }}>
                <td className="px-4 py-3">
                  <Link href={`/${locale}/cases/${c.id}`}
                    className="font-mono text-xs font-bold transition hover:underline"
                    style={{ color: C.navy }}>
                    {c.reference}
                  </Link>
                </td>
                <td className="px-4 py-3 max-w-[140px]">
                  <span className="truncate block text-xs text-slate-700">{c.debtor?.full_name ?? "—"}</span>
                </td>
                <td className="px-4 py-3 text-xs text-slate-500">{c.portfolio?.name ?? "—"}</td>
                <td className="px-4 py-3 text-xs font-semibold text-slate-900 whitespace-nowrap">
                  {new Intl.NumberFormat("fr-FR").format(bal)}&nbsp;{c.currency ?? "XAF"}
                </td>
                <td className="px-4 py-3"><StatusBadge status={c.status} label={statusLabels[c.status] ?? c.status} /></td>
                <td className="px-4 py-3">
                  <span className="h-2.5 w-2.5 rounded-full inline-block"
                    style={{ background: PRIORITY_COLOR[c.priority] ?? C.muted }} />
                </td>
                <td className="px-4 py-3 text-xs whitespace-nowrap"
                  style={{ color: overdue ? C.red : C.muted }}>
                  {due ? due.toLocaleDateString("fr-FR") : "—"}
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </div>
  )
}

// ── Recovery gauge ─────────────────────────────────────────────────────────
function RecoveryGauge({ cases, labels }: { cases: Case[]; labels: { goal: string; portfolio: string; recovered: string } }) {
  const { rate, collected, total } = useMemo(() => {
    let sumTotal = 0, sumCollected = 0
    cases.forEach((c) => {
      const orig = Number(c.original_amount) || 0
      const bal  = Number(c.balance_amount) || 0
      if (orig > 0) { sumTotal += orig; sumCollected += (orig - bal) }
    })
    const r = sumTotal > 0 ? Math.round((sumCollected / sumTotal) * 100) : 0
    return { rate: r, collected: sumCollected, total: sumTotal }
  }, [cases])

  const v = Math.max(0, Math.min(100, rate))
  const color = v >= 70 ? C.teal : v >= 40 ? C.amber : C.red
  const gaugeData = [
    { name: "done", value: v, color },
    { name: "rest", value: 100 - v, color: "rgba(15,23,42,.07)" },
  ]
  const fmt = (n: number) => new Intl.NumberFormat("fr-FR", { notation: "compact", maximumFractionDigits: 1 }).format(n)

  return (
    <div className="flex flex-col items-center">
      <div className="relative h-[170px] w-full max-w-[260px]">
        <ResponsiveContainer width="100%" height="100%">
          <PieChart>
            <Pie dataKey="value" data={gaugeData}
              startAngle={180} endAngle={0}
              innerRadius={62} outerRadius={86}
              paddingAngle={0} cornerRadius={10}>
              {gaugeData.map((d) => <Cell key={d.name} fill={d.color} />)}
            </Pie>
          </PieChart>
        </ResponsiveContainer>
        <div className="absolute inset-0 flex flex-col items-center justify-center pt-14">
          <div className="text-3xl font-bold text-slate-900">{v}%</div>
          <div className="text-[11px] text-slate-400 mt-0.5">{labels.goal}</div>
        </div>
      </div>
      {total > 0 && (
        <div className="mt-1 flex gap-6 text-center text-xs text-slate-500">
          <div>
            <div className="font-bold text-slate-900 text-sm">{fmt(total)}</div>
            <div>{labels.portfolio}</div>
          </div>
          <div>
            <div className="font-bold text-sm" style={{ color }}>{fmt(collected)}</div>
            <div>{labels.recovered}</div>
          </div>
        </div>
      )}
    </div>
  )
}

// ── Main ───────────────────────────────────────────────────────────────────
export default function DashboardPage() {
  const locale = useLocale()
  const t = useTranslations("dashboard")

  const { selectedCountry } = useCountry()

  const [me,        setMe]       = useState<Me | null>(null)
  const [cases,     setCases]    = useState<Case[]>([])
  const [customers, setCustomers]= useState<Customer[]>([])
  const [debtorCnt, setDebtorCnt]= useState<number>(0)
  const [loading,   setLoading]  = useState(true)
  const [refreshing,setRefreshing]=useState(false)
  const [currency,  setCurrency] = useState<string>("ALL")

  async function load(countryCode?: string) {
    setRefreshing(true)
    try {
      const [meData, casesData, customersData, debtorsData] = await Promise.all([
        fetchMe(),
        listCases({ country: countryCode }),
        listCustomers(),
        listDebtors({ country: countryCode }),
      ])
      setMe(meData)
      setCases(casesData)
      setCustomers(customersData)
      setDebtorCnt(debtorsData.length)
    } catch {
      // silencieux — données partielles affichées
    } finally {
      setLoading(false)
      setRefreshing(false)
    }
  }

  useEffect(() => { load(selectedCountry?.country_code) }, [selectedCountry?.country_code]) // eslint-disable-line

  // ── Devises distinctes présentes dans les dossiers ───────────────────────
  const availableCurrencies = useMemo(() => {
    const seen = new Set<string>()
    cases.forEach((c) => { if (c.currency) seen.add(c.currency) })
    return Array.from(seen).sort()
  }, [cases])

  // ── Dossiers filtrés par devise sélectionnée ─────────────────────────────
  const filteredCases = useMemo(() =>
    currency === "ALL" ? cases : cases.filter((c) => (c.currency ?? "XAF") === currency),
    [cases, currency]
  )

  // ── KPIs calculés ────────────────────────────────────────────────────────
  const kpi = useMemo(() => {
    const now   = new Date()
    const total   = filteredCases.length
    const open    = filteredCases.filter((c) => c.status === "open").length
    const inprog  = filteredCases.filter((c) => c.status === "in_progress").length
    const overdue = filteredCases.filter((c) => c.status !== "closed" && c.due_date && new Date(c.due_date) < now).length
    let sumOrig = 0, sumBal = 0
    filteredCases.forEach((c) => { sumOrig += Number(c.original_amount) || 0; sumBal += Number(c.balance_amount) || 0 })
    const recovered = sumOrig - sumBal
    const rate = sumOrig > 0 ? Math.round((recovered / sumOrig) * 100) : 0
    const fmt = (n: number) => new Intl.NumberFormat("fr-FR", { notation: "compact", maximumFractionDigits: 1 }).format(n)
    return { total, open, inprog, overdue, recovered, rate, fmt, customers: customers.length, debtors: debtorCnt }
  }, [filteredCases, customers, debtorCnt])

  const tenantName = me?.active_tenant?.name ?? "—"
  const firstName  = me?.first_name || me?.username || "—"
  const hour = new Date().getHours()
  const greeting = hour < 12 ? t("greeting.morning") : hour < 18 ? t("greeting.afternoon") : t("greeting.evening")

  return (
    <div className="w-full space-y-5">

      {/* ── Header ────────────────────────────────────────────────────────── */}
      <div
        className="rounded-2xl p-5 text-white relative overflow-hidden"
        style={{ background: `linear-gradient(135deg, ${C.navy} 0%, ${C.navy2} 60%, #3272c8 100%)` }}
      >
        <div className="pointer-events-none absolute inset-0">
          <div className="absolute -top-16 -right-16 h-56 w-56 rounded-full opacity-[0.10]"
            style={{ background: `radial-gradient(circle, ${C.teal}, transparent 70%)` }} />
          <div className="absolute -bottom-10 -left-10 h-40 w-40 rounded-full opacity-[0.07]"
            style={{ background: "radial-gradient(circle, #fff, transparent 70%)" }} />
          <svg className="absolute inset-0 h-full w-full opacity-[0.04]" xmlns="http://www.w3.org/2000/svg">
            <defs><pattern id="dd" x="0" y="0" width="24" height="24" patternUnits="userSpaceOnUse">
              <circle cx="2" cy="2" r="1.4" fill="white" />
            </pattern></defs>
            <rect width="100%" height="100%" fill="url(#dd)" />
          </svg>
        </div>

        <div className="relative flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
          <div>
            <p className="text-sm text-white/65">{greeting}, <span className="font-semibold text-white">{firstName}</span></p>
            <h1 className="mt-1 text-2xl font-bold leading-tight flex items-center gap-2">
              <Building2 className="h-5 w-5 opacity-70" />
              {tenantName}
            </h1>
            <p className="mt-1.5 text-sm text-white/55">{t("header.subtitle")}</p>
            {selectedCountry && (
              <div className="mt-2 inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-semibold"
                style={{ background: "rgba(255,255,255,0.15)", color: "rgba(255,255,255,0.9)" }}>
                <MapPin className="h-3 w-3" />
                {selectedCountry.country_name}
              </div>
            )}
          </div>

          <div className="flex items-center gap-2 shrink-0 flex-wrap">
            {/* ── Sélecteur de devise ── */}
            {availableCurrencies.length > 0 && (
              <div className="flex rounded-xl overflow-hidden text-xs" style={{ background: "rgba(255,255,255,0.12)" }}>
                <button
                  onClick={() => setCurrency("ALL")}
                  className="px-3 py-1.5 font-semibold transition"
                  style={currency === "ALL" ? { background: "rgba(255,255,255,0.25)", color: "#fff" } : { color: "rgba(255,255,255,0.65)" }}
                >
                  {t("currency.all")}
                </button>
                {availableCurrencies.map((cur) => (
                  <button key={cur}
                    onClick={() => setCurrency(cur)}
                    className="px-3 py-1.5 font-semibold transition"
                    style={currency === cur ? { background: "rgba(255,255,255,0.25)", color: "#fff" } : { color: "rgba(255,255,255,0.65)" }}
                  >
                    {cur}
                  </button>
                ))}
              </div>
            )}
            <button type="button" onClick={() => load(selectedCountry?.country_code)} disabled={refreshing}
              className="flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium text-white/75 transition hover:bg-white/10 disabled:opacity-50">
              <RefreshCcw className={cx("h-4 w-4", refreshing && "animate-spin")} />
              {t("header.refresh")}
            </button>
            <Link href={`/${locale}/cases`}
              className="flex items-center gap-2 rounded-xl px-4 py-2 text-sm font-semibold text-white transition"
              style={{ background: "rgba(255,255,255,0.15)", backdropFilter: "blur(4px)" }}>
              {t("header.viewCases")} <ArrowRight className="h-4 w-4" />
            </Link>
          </div>
        </div>
      </div>

      {/* ── KPIs ──────────────────────────────────────────────────────────── */}
      <div className="grid grid-cols-2 sm:grid-cols-3 xl:grid-cols-7 gap-3">
        <KpiCard icon={<Briefcase className="h-5 w-5" />}     label={t("kpi.total")}        value={`${kpi.total}`}   sub={t("kpi.sub.allStatuses")}  tone="navy"  loading={loading} />
        <KpiCard icon={<Clock3 className="h-5 w-5" />}        label={t("kpi.open")}         value={`${kpi.open}`}    sub={t("kpi.sub.toProcess")}    tone="blue"  loading={loading} />
        <KpiCard icon={<TrendingUp className="h-5 w-5" />}    label={t("kpi.inProgress")}   value={`${kpi.inprog}`}  sub={t("kpi.sub.inProcessing")} tone="teal"  loading={loading} />
        <KpiCard icon={<AlertTriangle className="h-5 w-5" />} label={t("kpi.overdue")}      value={`${kpi.overdue}`} sub={t("kpi.sub.overdue")}      tone="red"   loading={loading} />
        <KpiCard icon={<Users className="h-5 w-5" />}         label={t("kpi.customers")}    value={`${kpi.customers}`} sub={t("kpi.sub.active")}     tone="navy"  loading={loading} />
        <KpiCard icon={<UserRound className="h-5 w-5" />}     label={t("kpi.debtors")}      value={`${kpi.debtors}`} sub={t("kpi.sub.referenced")}   tone="teal"  loading={loading} />
        <KpiCard icon={<Wallet className="h-5 w-5" />}        label={t("kpi.recoveryRate")} value={`${kpi.rate}%`}   sub={`${kpi.fmt(kpi.recovered)} ${currency === "ALL" ? t("currency.mixed") : currency}`} tone={kpi.rate >= 70 ? "teal" : kpi.rate >= 40 ? "amber" : "red"} loading={loading} />
      </div>

      {/* ── Raccourcis ────────────────────────────────────────────────────── */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { href: `/${locale}/cases`,         icon: Briefcase,   label: t("shortcuts.cases"),      color: C.navy,  badge: kpi.overdue > 0 ? String(kpi.overdue) : undefined },
          { href: `/${locale}/customers`,     icon: Building2,   label: t("shortcuts.customers"),  color: C.teal },
          { href: `/${locale}/portfolio`,     icon: BarChart3,   label: t("shortcuts.portfolios"), color: C.blue },
          { href: `/${locale}/treasury`,      icon: Wallet,      label: t("shortcuts.treasury"),   color: C.amber },
        ].map(({ href, icon: Icon, label, color, badge }) => (
          <Link key={label} href={href}
            className="flex items-center gap-3 rounded-2xl border bg-white p-3.5 text-sm font-medium text-slate-700 shadow-sm transition hover:shadow-md hover:bg-slate-50/80"
            style={{ borderColor: C.border }}>
            <div className="h-9 w-9 rounded-xl flex items-center justify-center shrink-0"
              style={{ background: `${color}15`, color }}>
              <Icon className="h-4 w-4" />
            </div>
            <span className="flex-1 truncate">{label}</span>
            {badge && (
              <span className="rounded-full px-1.5 py-0.5 text-[11px] font-bold text-white"
                style={{ background: C.red }}>{badge}</span>
            )}
            <ChevronRight className="h-4 w-4 text-slate-300 shrink-0" />
          </Link>
        ))}
      </div>

      {/* ── Charts row 1 : Trend + Status ─────────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">
        <div className="lg:col-span-2">
          <Card title={t("charts.trends.title")} subtitle={t("charts.trends.subtitle")}
            right={
              <div className="flex items-center gap-3 text-[11px] text-slate-400">
                <span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-full" style={{ background: C.navy }} />{t("charts.trends.opened")}</span>
                <span className="flex items-center gap-1.5"><span className="h-2.5 w-2.5 rounded-full" style={{ background: C.teal }} />{t("charts.trends.closed")}</span>
              </div>
            }>
            <TrendChart cases={filteredCases} labels={{ empty: t("empty.data"), opened: t("charts.trends.opened"), closed: t("charts.trends.closed") }} />
          </Card>
        </div>
        <div className="lg:col-span-1">
          <Card title={t("charts.status.title")} subtitle={t("charts.status.subtitle")}>
            <StatusDonut cases={filteredCases} labels={{ open: t("status.open"), in_progress: t("status.in_progress"), on_hold: t("status.on_hold"), closed: t("status.closed"), total: t("charts.status.total") }} />
          </Card>
        </div>
      </div>

      {/* ── Charts row 2 : Gauge + Priority + Recent ──────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-4">
        <div className="lg:col-span-1">
          <Card title={t("charts.gauge.title")} subtitle={t("charts.gauge.subtitle")}>
            <RecoveryGauge cases={filteredCases} labels={{ goal: t("charts.gauge.goal"), portfolio: t("charts.gauge.portfolio"), recovered: t("charts.gauge.recovered") }} />
          </Card>
        </div>
        <div className="lg:col-span-1">
          <Card title={t("charts.priority.title")} subtitle={t("charts.priority.subtitle")}>
            <PriorityChart cases={filteredCases} labels={{ low: t("priority.low"), medium: t("priority.medium"), high: t("priority.high"), urgent: t("priority.urgent"), cases: t("charts.priority.cases") }} />
          </Card>
        </div>
        <div className="lg:col-span-2">
          <Card title={t("charts.recent.title")} subtitle={t("charts.recent.subtitle")}
            right={
              <Link href={`/${locale}/cases`}
                className="flex items-center gap-1 text-xs font-medium transition"
                style={{ color: C.teal }}>
                {t("charts.recent.viewAll")} <ChevronRight className="h-3.5 w-3.5" />
              </Link>
            }>
            <RecentCases cases={filteredCases} locale={locale}
              labels={{ empty: t("charts.recent.empty"), reference: t("table.reference"), debtor: t("table.debtor"), portfolio: t("table.portfolio"), balance: t("table.balance"), status: t("table.status"), priority: t("table.priority"), dueDate: t("table.dueDate") }}
              statusLabels={{ open: t("status.open"), in_progress: t("status.in_progress"), on_hold: t("status.on_hold"), closed: t("status.closed") }}
            />
          </Card>
        </div>
      </div>

    </div>
  )
}
