"use client"

/**
 * Détail d'un portefeuille — Outil d'aide à la décision
 * Statistiques de recouvrement globales + dossiers individuels
 */

import { useEffect, useMemo, useState } from "react"
import { useParams } from "next/navigation"
import { useLocale, useTranslations } from "next-intl"
import Link from "next/link"
import {
  ArrowLeft, RefreshCw, Layers, TrendingUp, AlertTriangle,
  ShieldCheck, Coins, UserRound, FolderOpen, ChevronRight,
  Clock, CheckCircle2, Circle, Loader2, BarChart3, ArrowUpRight,
  Target, XCircle,
} from "lucide-react"
import { listCases, type Case } from "@/src/lib/api/cases"
import { listPortfolios, type Portfolio } from "@/src/lib/api/portfolios"

// ── Palette ──────────────────────────────────────────────────────────────────
const NAVY  = "#1a3578"
const NAVY2 = "#2655b0"
const TEAL  = "#4dba96"

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

// ── Formatters ───────────────────────────────────────────────────────────────
function fmtMoney(v?: string | number | null, currency?: string | null) {
  const num = parseFloat(String(v ?? 0))
  if (isNaN(num) || num === 0) return "—"
  return new Intl.NumberFormat("fr-FR", { maximumFractionDigits: 0 }).format(num) +
    (currency ? ` ${currency}` : "")
}

function fmtPct(num: number, denom: number): string {
  if (!denom) return "0%"
  return `${Math.round((num / denom) * 100)}%`
}

function fmtDate(d?: string | null) {
  if (!d) return "—"
  return new Date(d).toLocaleDateString("fr-FR", { day: "2-digit", month: "short", year: "numeric" })
}

function numOf(v?: string | number | null): number {
  const n = parseFloat(String(v ?? 0))
  return isNaN(n) ? 0 : n
}

// ── Status / Priority badges ─────────────────────────────────────────────────
const STATUS_CFG: Record<string, { color: string; bg: string; border: string; icon: React.ElementType }> = {
  open:        { color: "#2655b0", bg: "rgba(38,85,176,.08)",  border: "rgba(38,85,176,.2)",  icon: Circle },
  in_progress: { color: TEAL,     bg: "rgba(77,186,150,.1)", border: "rgba(77,186,150,.25)", icon: Clock },
  on_hold:     { color: "#f59e0b", bg: "rgba(245,158,11,.08)", border: "rgba(245,158,11,.2)", icon: AlertTriangle },
  closed:      { color: "#64748b", bg: "rgba(100,116,139,.08)", border: "rgba(100,116,139,.2)", icon: CheckCircle2 },
}

const PRIO_CFG: Record<string, { color: string; bg: string }> = {
  low:    { color: "#64748b", bg: "rgba(100,116,139,.08)" },
  medium: { color: "#2655b0", bg: "rgba(38,85,176,.08)"  },
  high:   { color: "#f97316", bg: "rgba(249,115,22,.08)" },
  urgent: { color: "#dc2626", bg: "rgba(220,38,38,.08)"  },
}

function StatusBadge({ status, label }: { status: string; label: string }) {
  const cfg = STATUS_CFG[status] ?? STATUS_CFG.open
  const Icon = cfg.icon
  return (
    <span className="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] font-semibold border"
      style={{ color: cfg.color, background: cfg.bg, borderColor: cfg.border }}>
      <Icon className="h-3 w-3" />
      {label}
    </span>
  )
}

function PrioBadge({ prio, label }: { prio: string; label: string }) {
  const cfg = PRIO_CFG[prio] ?? PRIO_CFG.medium
  return (
    <span className="inline-flex items-center rounded-full px-2 py-0.5 text-[10px] font-semibold"
      style={{ color: cfg.color, background: cfg.bg }}>
      {label}
    </span>
  )
}

// ── Recovery bar ─────────────────────────────────────────────────────────────
function RecoveryBar({ pct, color = TEAL }: { pct: number; color?: string }) {
  const safe = Math.min(100, Math.max(0, Math.round(pct)))
  const barColor = safe >= 80 ? "#10b981" : safe >= 50 ? TEAL : safe >= 30 ? "#f59e0b" : "#ef4444"
  return (
    <div className="flex items-center gap-2">
      <div className="flex-1 h-2 bg-slate-100 rounded-full overflow-hidden">
        <div className="h-full rounded-full transition-all" style={{ width: `${safe}%`, background: barColor }} />
      </div>
      <span className="text-xs font-bold tabular-nums" style={{ color: barColor, minWidth: 36 }}>
        {safe}%
      </span>
    </div>
  )
}

// ── Decision alert chip ───────────────────────────────────────────────────────
function Alert({ type, msg }: { type: "warning" | "danger" | "ok"; msg: string }) {
  const cfg = {
    warning: { bg: "rgba(245,158,11,.08)", border: "rgba(245,158,11,.25)", color: "#b45309" },
    danger:  { bg: "rgba(220,38,38,.08)",  border: "rgba(220,38,38,.25)",  color: "#dc2626" },
    ok:      { bg: "rgba(16,185,129,.08)", border: "rgba(16,185,129,.25)", color: "#059669" },
  }[type]
  return (
    <div className="rounded-xl border px-3 py-2 text-xs font-medium"
      style={{ background: cfg.bg, borderColor: cfg.border, color: cfg.color }}>
      {msg}
    </div>
  )
}

// ── Page ─────────────────────────────────────────────────────────────────────
export default function PortfolioDetailPage() {
  const locale  = useLocale()
  const t       = useTranslations("portfolios.detail")
  const params  = useParams<{ id: string }>()
  const portId  = Number(params?.id)

  const [portfolio, setPortfolio] = useState<Portfolio | null>(null)
  const [cases, setCases]         = useState<Case[]>([])
  const [loading, setLoading]     = useState(true)
  const [error, setError]         = useState<string | null>(null)

  // Filters on cases
  const [qCase, setQCase]           = useState("")
  const [fStatus, setFStatus]       = useState("")
  const [fAssignee, setFAssignee]   = useState("")
  const [sortBy, setSortBy]         = useState<"pct_asc" | "pct_desc" | "amount_desc" | "date">("pct_asc")

  async function load() {
    setLoading(true); setError(null)
    try {
      const [portList, caseList] = await Promise.all([
        listPortfolios(),
        listCases({ portfolio: portId }),
      ])
      const p = portList.find(x => x.id === portId) ?? null
      setPortfolio(p)
      setCases(caseList)
    } catch (e: any) {
      setError(e?.message ?? "Erreur de chargement")
    } finally {
      setLoading(false)
    }
  }

  useEffect(() => { if (portId && !isNaN(portId)) load() }, [portId])

  // ── Analytics ────────────────────────────────────────────────────────────
  const analytics = useMemo(() => {
    const total         = cases.length
    const open          = cases.filter(c => c.status === "open").length
    const inProgress    = cases.filter(c => c.status === "in_progress").length
    const onHold        = cases.filter(c => c.status === "on_hold").length
    const closed        = cases.filter(c => c.status === "closed").length
    const urgent        = cases.filter(c => c.priority === "urgent").length
    const highPrio      = cases.filter(c => c.priority === "high").length
    const unassigned    = cases.filter(c => !c.assigned_to_username).length

    const totalDue      = cases.reduce((s, c) => s + numOf(c.original_amount), 0)
    const totalBalance  = cases.reduce((s, c) => s + numOf(c.balance_amount), 0)
    const totalCollected = totalDue - totalBalance
    const recoveryPct   = totalDue ? (totalCollected / totalDue) * 100 : 0

    // Assignee breakdown
    const byAssignee: Record<string, { name: string; count: number; due: number; balance: number }> = {}
    for (const c of cases) {
      const key = c.assigned_to_username ?? "__none__"
      if (!byAssignee[key]) byAssignee[key] = { name: c.assigned_to_username ?? t("table.unassigned"), count: 0, due: 0, balance: 0 }
      byAssignee[key].count++
      byAssignee[key].due     += numOf(c.original_amount)
      byAssignee[key].balance += numOf(c.balance_amount)
    }

    const assignees = Object.values(byAssignee).sort((a, b) => b.due - a.due)

    // Decision signals
    const alerts: { type: "warning" | "danger" | "ok"; msg: string }[] = []
    const pct = Math.round(recoveryPct)
    if (recoveryPct < 30 && total > 0)      alerts.push({ type: "danger",  msg: t("analytics.alert_critical", { pct }) })
    else if (recoveryPct < 60 && total > 0) alerts.push({ type: "warning", msg: t("analytics.alert_warning",  { pct }) })
    else if (total > 0)                     alerts.push({ type: "ok",      msg: t("analytics.alert_ok",       { pct }) })
    if (unassigned > 0) alerts.push({ type: "warning", msg: unassigned > 1 ? t("analytics.alert_unassigned_many", { count: unassigned }) : t("analytics.alert_unassigned_one", { count: unassigned }) })
    if (urgent > 0)     alerts.push({ type: "danger",  msg: urgent > 1      ? t("analytics.alert_urgent_many",    { count: urgent })      : t("analytics.alert_urgent_one",    { count: urgent }) })
    if (onHold > 2)     alerts.push({ type: "warning", msg: t("analytics.alert_on_hold", { count: onHold }) })

    const currency = portfolio?.default_currency

    return { total, open, inProgress, onHold, closed, urgent, highPrio, unassigned,
             totalDue, totalBalance, totalCollected, recoveryPct, assignees, alerts, currency }
  }, [cases, portfolio])

  // ── Filtered + sorted cases ──────────────────────────────────────────────
  const displayedCases = useMemo(() => {
    let list = [...cases]
    if (qCase.trim()) {
      const q = qCase.toLowerCase()
      list = list.filter(c =>
        [c.reference, c.title, c.debtor?.full_name, c.assigned_to_username]
          .filter(Boolean).join(" ").toLowerCase().includes(q)
      )
    }
    if (fStatus) list = list.filter(c => c.status === fStatus)
    if (fAssignee) list = list.filter(c => (c.assigned_to_username ?? "__none__") === fAssignee)

    list.sort((a, b) => {
      const aDue = numOf(a.original_amount), abal = numOf(a.balance_amount)
      const bDue = numOf(b.original_amount), bbal = numOf(b.balance_amount)
      const aPct = aDue ? ((aDue - abal) / aDue) * 100 : 0
      const bPct = bDue ? ((bDue - bbal) / bDue) * 100 : 0
      if (sortBy === "pct_asc")    return aPct - bPct
      if (sortBy === "pct_desc")   return bPct - aPct
      if (sortBy === "amount_desc") return bDue - aDue
      return new Date(b.opened_at).getTime() - new Date(a.opened_at).getTime()
    })
    return list
  }, [cases, qCase, fStatus, fAssignee, sortBy])

  const assigneeList = useMemo(() =>
    [...new Set(cases.map(c => c.assigned_to_username).filter(Boolean))] as string[],
    [cases])

  if (loading) return (
    <div className="flex items-center justify-center h-64 text-slate-400">
      <Loader2 className="h-6 w-6 animate-spin mr-2" />{t("loading")}
    </div>
  )

  if (error) return (
    <div className="rounded-2xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">{error}</div>
  )

  const curr = analytics.currency

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

      {/* ── Header ──────────────────────────────────────────────────────────── */}
      <div className="relative overflow-hidden rounded-2xl px-6 py-5 text-white"
        style={{ background: `linear-gradient(135deg, ${NAVY} 0%, ${NAVY2} 100%)` }}>
        <div className="pointer-events-none absolute -top-10 -right-10 h-40 w-40 rounded-full opacity-[0.07]"
          style={{ background: `radial-gradient(circle, ${TEAL}, transparent 70%)` }} />
        <div className="relative">
          <div className="flex items-center gap-3 mb-3">
            <Link href={`/${locale}/portfolio`}
              className="inline-flex items-center gap-1.5 rounded-xl border border-white/20 bg-white/10 px-3 py-1.5 text-xs hover:bg-white/20 transition">
              <ArrowLeft className="h-3.5 w-3.5" />
              {t("breadcrumb")}
            </Link>
            <ChevronRight className="h-3.5 w-3.5 text-white/40" />
            <span className="text-sm text-white/70">{portfolio?.code ?? `#${portId}`}</span>
          </div>

          <div className="flex items-end justify-between gap-4 flex-wrap">
            <div>
              <h1 className="text-2xl font-bold">{portfolio?.name ?? "Portefeuille"}</h1>
              <div className="flex items-center gap-3 mt-1 flex-wrap">
                {portfolio?.category && <span className="text-sm text-white/60">{portfolio.category}</span>}
                {portfolio?.default_currency && (
                  <span className="text-xs bg-white/10 rounded-full px-2 py-0.5">{portfolio.default_currency}</span>
                )}
                <span className={cx(
                  "text-xs rounded-full px-2 py-0.5 font-semibold",
                  portfolio?.is_active ? "bg-emerald-400/20 text-emerald-200" : "bg-slate-400/20 text-slate-300"
                )}>
                  {portfolio?.is_active ? t("active") : t("inactive")}
                </span>
                {portfolio?.owner_username && (
                  <span className="text-xs text-white/50">{t("owner_prefix")} @{portfolio.owner_username}</span>
                )}
              </div>
            </div>
            <button onClick={load}
              className="rounded-xl border border-white/20 p-2 hover:bg-white/10 transition">
              <RefreshCw className="h-4 w-4" />
            </button>
          </div>
        </div>
      </div>

      {/* ── Decision signals ────────────────────────────────────────────────── */}
      {analytics.alerts.length > 0 && (
        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2">
          {analytics.alerts.map((a, i) => <Alert key={i} type={a.type} msg={a.msg} />)}
        </div>
      )}

      {/* ── Global KPIs ─────────────────────────────────────────────────────── */}
      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        {[
          { label: t("kpi.total"),      value: analytics.total,                            icon: Layers,        color: NAVY,     bg: "rgba(26,53,120,.08)" },
          { label: t("kpi.active"),     value: analytics.inProgress + analytics.open,      icon: Clock,         color: TEAL,     bg: "rgba(77,186,150,.10)" },
          { label: t("kpi.urgent"),     value: analytics.urgent,                           icon: AlertTriangle, color: "#f97316", bg: "rgba(249,115,22,.08)" },
          { label: t("kpi.unassigned"), value: analytics.unassigned,                       icon: UserRound,     color: "#e11d48", bg: "rgba(225,29,72,.08)" },
        ].map(({ label, value, icon: Icon, color, bg }) => (
          <div key={label} className="rounded-2xl border border-slate-200 bg-white p-4 flex items-center gap-3 shadow-sm">
            <div className="rounded-xl p-2.5 shrink-0" style={{ background: bg }}>
              <Icon className="h-4 w-4" style={{ color }} />
            </div>
            <div>
              <div className="text-2xl font-bold text-slate-900 leading-none">{value}</div>
              <div className="text-[11px] font-medium text-slate-400 uppercase tracking-wide mt-0.5">{label}</div>
            </div>
          </div>
        ))}
      </div>

      {/* ── Recovery analytics row ─────────────────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-4">

        {/* Global recovery gauge */}
        <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="text-sm font-semibold text-slate-700">{t("analytics.recovery_gauge")}</div>
            <Target className="h-4 w-4 text-slate-300" />
          </div>

          {/* Big circle-like indicator */}
          <div className="flex flex-col items-center py-2">
            <div className="relative h-28 w-28 mb-3">
              <svg viewBox="0 0 100 100" className="h-full w-full -rotate-90">
                <circle cx="50" cy="50" r="42" fill="none" stroke="#f1f5f9" strokeWidth="10" />
                <circle cx="50" cy="50" r="42" fill="none"
                  stroke={analytics.recoveryPct >= 80 ? "#10b981" : analytics.recoveryPct >= 50 ? TEAL : analytics.recoveryPct >= 30 ? "#f59e0b" : "#ef4444"}
                  strokeWidth="10"
                  strokeDasharray={`${2 * Math.PI * 42}`}
                  strokeDashoffset={`${2 * Math.PI * 42 * (1 - Math.min(analytics.recoveryPct, 100) / 100)}`}
                  strokeLinecap="round"
                  style={{ transition: "stroke-dashoffset 1s ease" }}
                />
              </svg>
              <div className="absolute inset-0 flex flex-col items-center justify-center">
                <span className="text-2xl font-bold text-slate-900">{Math.round(analytics.recoveryPct)}%</span>
                <span className="text-[10px] text-slate-400">{t("analytics.recovered_label")}</span>
              </div>
            </div>
          </div>

          <div className="space-y-2 text-xs">
            <div className="flex justify-between text-slate-500">
              <span>{t("analytics.total_due")}</span>
              <span className="font-semibold text-slate-700">{fmtMoney(analytics.totalDue, curr)}</span>
            </div>
            <div className="flex justify-between text-slate-500">
              <span>{t("analytics.recovered")}</span>
              <span className="font-semibold text-emerald-600">{fmtMoney(analytics.totalCollected, curr)}</span>
            </div>
            <div className="flex justify-between text-slate-500">
              <span>{t("analytics.balance")}</span>
              <span className="font-semibold text-red-500">{fmtMoney(analytics.totalBalance, curr)}</span>
            </div>
          </div>
        </div>

        {/* Status breakdown */}
        <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="text-sm font-semibold text-slate-700">{t("analytics.status_breakdown")}</div>
            <BarChart3 className="h-4 w-4 text-slate-300" />
          </div>
          <div className="space-y-3">
            {[
              { label: t("analytics.status_open"),        count: analytics.open,       color: NAVY2 },
              { label: t("analytics.status_in_progress"), count: analytics.inProgress, color: TEAL },
              { label: t("analytics.status_on_hold"),     count: analytics.onHold,     color: "#f59e0b" },
              { label: t("analytics.status_closed"),      count: analytics.closed,     color: "#94a3b8" },
            ].map(({ label, count, color }) => (
              <div key={label}>
                <div className="flex items-center justify-between text-xs mb-1">
                  <span className="text-slate-600">{label}</span>
                  <span className="font-semibold text-slate-800">{count} ({fmtPct(count, analytics.total)})</span>
                </div>
                <div className="h-2 bg-slate-100 rounded-full overflow-hidden">
                  <div className="h-full rounded-full" style={{
                    width: analytics.total ? `${(count / analytics.total) * 100}%` : "0%",
                    background: color
                  }} />
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* Assignee performance */}
        <div className="rounded-2xl border border-slate-200 bg-white p-5 shadow-sm">
          <div className="flex items-center justify-between mb-4">
            <div className="text-sm font-semibold text-slate-700">{t("analytics.agent_perf")}</div>
            <UserRound className="h-4 w-4 text-slate-300" />
          </div>
          <div className="space-y-2.5 max-h-52 overflow-y-auto pr-1">
            {analytics.assignees.length === 0 ? (
              <p className="text-xs text-slate-400 text-center py-4">{t("analytics.no_agents")}</p>
            ) : analytics.assignees.map(ag => {
              const collected = ag.due - ag.balance
              const pct = ag.due ? (collected / ag.due) * 100 : 0
              return (
                <div key={ag.name} className="space-y-1">
                  <div className="flex items-center justify-between text-xs">
                    <div className="flex items-center gap-1.5 min-w-0">
                      <div className="h-5 w-5 rounded-full bg-slate-200 flex items-center justify-center text-[9px] font-bold text-slate-500 shrink-0">
                        {ag.name.charAt(0).toUpperCase()}
                      </div>
                      <span className="text-slate-600 truncate">{ag.name}</span>
                    </div>
                    <span className="text-slate-400 shrink-0 ml-2">{ag.count > 1 ? t("analytics.case_count_plural", { count: ag.count }) : t("analytics.case_count", { count: ag.count })}</span>
                  </div>
                  <RecoveryBar pct={pct} />
                </div>
              )
            })}
          </div>
        </div>
      </div>

      {/* ── Cases table ─────────────────────────────────────────────────────── */}
      <div className="rounded-2xl border border-slate-200 bg-white shadow-sm overflow-hidden">

        {/* Table toolbar */}
        <div className="flex items-center gap-3 px-4 py-3 border-b border-slate-100 flex-wrap">
          <div className="flex-1 min-w-[200px] flex items-center gap-2 rounded-xl border border-slate-200 bg-slate-50 px-3 py-1.5">
            <FolderOpen className="h-3.5 w-3.5 text-slate-400 shrink-0" />
            <input
              className="flex-1 bg-transparent outline-none text-sm"
              placeholder={t("table.search_placeholder")}
              value={qCase}
              onChange={e => setQCase(e.target.value)}
            />
          </div>

          <select className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-xs"
            value={fStatus} onChange={e => setFStatus(e.target.value)}>
            <option value="">{t("table.all_statuses")}</option>
            <option value="open">{t("status.open")}</option>
            <option value="in_progress">{t("status.in_progress")}</option>
            <option value="on_hold">{t("status.on_hold")}</option>
            <option value="closed">{t("status.closed")}</option>
          </select>

          <select className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-xs"
            value={fAssignee} onChange={e => setFAssignee(e.target.value)}>
            <option value="">{t("table.all_agents")}</option>
            <option value="__none__">{t("table.unassigned")}</option>
            {assigneeList.map(a => <option key={a} value={a}>@{a}</option>)}
          </select>

          <select className="rounded-xl border border-slate-200 bg-white px-3 py-1.5 text-xs"
            value={sortBy} onChange={e => setSortBy(e.target.value as any)}>
            <option value="pct_asc">{t("table.sort_pct_asc")}</option>
            <option value="pct_desc">{t("table.sort_pct_desc")}</option>
            <option value="amount_desc">{t("table.sort_amount_desc")}</option>
            <option value="date">{t("table.sort_date")}</option>
          </select>

          <span className="text-xs text-slate-400 shrink-0">{displayedCases.length > 1 ? t("table.case_count_plural", { count: displayedCases.length }) : t("table.case_count", { count: displayedCases.length })}</span>
        </div>

        {/* Table */}
        {displayedCases.length === 0 ? (
          <div className="flex flex-col items-center gap-3 py-16 text-slate-400">
            <FolderOpen className="h-10 w-10 opacity-30" />
            <p className="text-sm">{t("table.empty")}</p>
          </div>
        ) : (
          <div className="overflow-x-auto">
            <table className="w-full text-sm">
              <thead>
                <tr className="border-b border-slate-100 text-left">
                  {[t("table.col_case"), t("table.col_status"), t("table.col_priority"), t("table.col_owner"), t("table.col_due"), t("table.col_collected"), t("table.col_recovery"), t("table.col_due_date"), ""].map(h => (
                    <th key={h} className="px-4 py-3 text-[11px] font-semibold text-slate-400 uppercase tracking-wide whitespace-nowrap">{h}</th>
                  ))}
                </tr>
              </thead>
              <tbody className="divide-y divide-slate-50">
                {displayedCases.map(c => {
                  const due       = numOf(c.original_amount)
                  const balance   = numOf(c.balance_amount)
                  const collected = due - balance
                  const pct       = due ? (collected / due) * 100 : 0

                  return (
                    <tr key={c.id} className="hover:bg-slate-50/60 transition group">
                      {/* Case name */}
                      <td className="px-4 py-3.5 max-w-[220px]">
                        <div className="font-semibold text-slate-800 truncate">{c.reference}</div>
                        <div className="text-xs text-slate-400 truncate mt-0.5">
                          {c.debtor?.full_name ?? "—"}
                        </div>
                        {c.title && c.title !== c.reference && (
                          <div className="text-[11px] text-slate-300 truncate">{c.title}</div>
                        )}
                      </td>

                      {/* Status */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        <StatusBadge status={c.status} label={t(`status.${c.status}` as any) as string} />
                      </td>

                      {/* Priority */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        <PrioBadge prio={c.priority} label={t(`priority.${c.priority}` as any) as string} />
                      </td>

                      {/* Assignee */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        {c.assigned_to_username ? (
                          <div className="flex items-center gap-1.5">
                            <div className="h-6 w-6 rounded-full bg-slate-200 flex items-center justify-center text-[10px] font-bold text-slate-500">
                              {c.assigned_to_username.charAt(0).toUpperCase()}
                            </div>
                            <span className="text-xs text-slate-600">@{c.assigned_to_username}</span>
                          </div>
                        ) : (
                          <span className="text-xs text-red-400 italic">{t("table.unassigned_cell")}</span>
                        )}
                      </td>

                      {/* Amount due */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        <span className="text-sm font-semibold text-slate-700">
                          {fmtMoney(due, c.currency ?? curr)}
                        </span>
                      </td>

                      {/* Collected */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        <span className={cx(
                          "text-sm font-semibold",
                          collected > 0 ? "text-emerald-600" : "text-slate-300"
                        )}>
                          {collected > 0 ? fmtMoney(collected, c.currency ?? curr) : "—"}
                        </span>
                      </td>

                      {/* Recovery bar */}
                      <td className="px-4 py-3.5 min-w-[140px]">
                        <RecoveryBar pct={pct} />
                      </td>

                      {/* Due date */}
                      <td className="px-4 py-3.5 whitespace-nowrap">
                        {c.due_date ? (
                          <span className={cx(
                            "text-xs",
                            new Date(c.due_date) < new Date() && c.status !== "closed"
                              ? "text-red-500 font-semibold"
                              : "text-slate-400"
                          )}>
                            {fmtDate(c.due_date)}
                            {new Date(c.due_date) < new Date() && c.status !== "closed" && (
                              <span className="ml-1 text-[10px] bg-red-50 text-red-500 border border-red-100 rounded-full px-1.5 py-0.5">{t("table.overdue_badge")}</span>
                            )}
                          </span>
                        ) : (
                          <span className="text-slate-300 text-xs">—</span>
                        )}
                      </td>

                      {/* Open case link */}
                      <td className="px-4 py-3.5">
                        <Link href={`/${locale}/cases/${c.id}`}
                          className="opacity-0 group-hover:opacity-100 transition h-7 w-7 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 flex items-center justify-center"
                          title={t("table.open_case")}>
                          <ArrowUpRight className="h-3.5 w-3.5 text-slate-500" />
                        </Link>
                      </td>
                    </tr>
                  )
                })}
              </tbody>
            </table>
          </div>
        )}
      </div>

    </div>
  )
}
