import React, { useState, useEffect } from "react";
import {
  Buildings,
  CurrencyDollar,
  TrendUp,
  Users,
  ChartLine,
  Warning,
  CheckCircle,
  Wallet,
  Target,
  Bank,
  ArrowUp,
  ArrowDown,
  ChartBar,
  Lightning,
  Shield,
  ChartPieSlice,
  Receipt,
} from "@phosphor-icons/react";
import {
  AreaChart,
  Area,
  BarChart,
  Bar,
  PieChart,
  Pie,
  Cell,
  LineChart,
  Line,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend,
  ResponsiveContainer,
} from "recharts";
import { useNavigate } from "react-router-dom";
import axios from "axios";

const BRAND = "#5D4037";
const COLORS = [
  "#5D4037",
  "#6D4C41",
  "#A1887F",
  "#C6A862",
  "#10b981",
  "#f59e0b",
  "#8b5cf6",
  "#06b6d4",
  "#f97316",
  "#14b8a6",
];

const fmt = (n) => {
  if (!n && n !== 0) return "—";
  if (n >= 1_000_000_000) return `₦${(n / 1_000_000_000).toFixed(1)}B`;
  if (n >= 1_000_000) return `₦${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `₦${(n / 1_000).toFixed(0)}K`;
  return `₦${Number(n).toLocaleString()}`;
};

const Glass = ({ children, className = "" }) => (
  <div
    className={`rounded-2xl border border-gray-200 bg-white shadow-lg ${className}`}
  >
    {children}
  </div>
);

const KPI = ({ icon: Icon, label, value, sub, color, change }) => (
  <Glass className="p-5">
    <div className="flex items-start justify-between mb-3">
      <div
        className="w-11 h-11 rounded-xl flex items-center justify-center"
        style={{ background: color + "20" }}
      >
        <Icon size={22} weight="duotone" style={{ color }} />
      </div>
      {change !== undefined && (
        <span
          className={`flex items-center gap-1 text-xs font-bold px-2 py-1 rounded-full ${change >= 0 ? "bg-green-100 text-green-700" : "bg-red-100 text-red-600"}`}
        >
          {change >= 0 ? (
            <ArrowUp size={10} weight="bold" />
          ) : (
            <ArrowDown size={10} weight="bold" />
          )}
          {Math.abs(change)}%
        </span>
      )}
    </div>
    <p className="text-2xl font-black text-gray-900 tracking-tight">{value}</p>
    <p className="text-xs font-semibold text-gray-500 mt-1 uppercase tracking-wider">
      {label}
    </p>
    {sub && <p className="text-xs text-gray-400 mt-0.5">{sub}</p>}
  </Glass>
);

const healthColors = {
  excellent: "#10b981",
  good: "#5D4037",
  fair: "#f59e0b",
  poor: "#f97316",
  critical: "#dc2626",
};
const healthBg = {
  excellent: "#dcfce7",
  good: "#EFEBE9",
  fair: "#fef9c3",
  poor: "#ffedd5",
  critical: "#fee2e2",
};

export default function GroupDashboard() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [period, setPeriod] = useState("month");
  const [showAssets, setShowAssets] = useState(false);
  const [assetCompany, setAssetCompany] = useState(null);

  useEffect(() => {
    fetchData();
  }, [period]);

  const fetchData = async () => {
    try {
      setLoading(true);
      setError(null);
      const res = await axios.get(`/api/dashboard/group?period=${period}`);
      setData(res.data);
    } catch (e) {
      console.error(e);
      setError(
        e.response?.data?.message ||
          e.response?.statusText ||
          "Failed to load dashboard data",
      );
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50">
        <div className="text-center">
          <div
            className="w-16 h-16 rounded-full border-4 border-t-transparent mx-auto animate-spin"
            style={{ borderColor: `${BRAND}33`, borderTopColor: BRAND }}
          />
          <p className="mt-4 text-sm text-gray-500 font-medium">
            Loading group data…
          </p>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-gray-50 p-6">
        <div className="bg-white rounded-2xl shadow-xl border border-red-100 p-8 max-w-md text-center">
          <div className="w-16 h-16 rounded-full bg-red-50 flex items-center justify-center mx-auto mb-4">
            <Warning size={32} className="text-red-500" weight="duotone" />
          </div>
          <h2 className="text-xl font-bold text-gray-900 mb-2">
            Dashboard Error
          </h2>
          <p className="text-sm text-gray-500 mb-4">{error}</p>
          <button
            onClick={fetchData}
            className="px-5 py-2.5 rounded-xl text-white font-semibold text-sm shadow-lg hover:shadow-xl transition-all"
            style={{ background: `linear-gradient(135deg,${BRAND},#6D4C41)` }}
          >
            Try Again
          </button>
        </div>
      </div>
    );
  }

  const s = data?.stats || {};
  const companies = data?.companies || [];
  const loans = data?.loanRequests || [];
  const allocations = data?.profitAllocations || [];
  const trend = data?.revenueTrend || [];
  const empDist = data?.empByCompany || [];

  const pieData = companies
    .slice(0, 8)
    .map((c) => ({ name: c.name?.split(" ").pop(), value: c.revenue || 0 }));

  return (
    <div className="min-h-screen p-6 bg-gray-50">
      {/* ── Header ─────────────────────────────────────────── */}
      <div className="mb-7 flex flex-wrap items-center justify-between gap-4">
        <div>
          <h1 className="text-3xl font-black text-gray-900 flex items-center gap-3">
            <div
              className="w-9 h-9 rounded-xl flex items-center justify-center"
              style={{ background: BRAND }}
            >
              <Lightning size={20} weight="fill" className="text-white" />
            </div>
            Sarkin Mota Group — God View
          </h1>
          <p className="text-gray-500 text-sm mt-1 ml-12">
            Group-level analytics across all subsidiaries
          </p>
        </div>
        <select
          value={period}
          onChange={(e) => setPeriod(e.target.value)}
          className="px-4 py-2 rounded-xl bg-white text-gray-700 text-sm border border-gray-200 focus:outline-none focus:border-primary-400 shadow-sm"
        >
          <option value="week" className="text-gray-900">
            This Week
          </option>
          <option value="month" className="text-gray-900">
            This Month
          </option>
          <option value="quarter" className="text-gray-900">
            This Quarter
          </option>
          <option value="year" className="text-gray-900">
            This Year
          </option>
        </select>
      </div>

      {/* ── KPI Row ─────────────────────────────────────────── */}
      <div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-4 mb-6">
        <KPI
          icon={Buildings}
          label="Companies"
          value={s.totalCompanies || 0}
          sub={`${s.subsidiaries || 0} subsidiaries`}
          color={BRAND}
        />
        <KPI
          icon={CurrencyDollar}
          label="Group Revenue"
          value={fmt(s.totalRevenue)}
          change={s.revenueGrowth}
          color="#10b981"
        />
        <KPI
          icon={TrendUp}
          label="Net Profit"
          value={fmt(s.totalProfit)}
          sub={`${s.profitMargin || 0}% margin`}
          color="#8b5cf6"
        />
        <div
          onClick={() => {
            setAssetCompany(null);
            setShowAssets(true);
          }}
          className="cursor-pointer"
        >
          <KPI
            icon={Bank}
            label="Total Assets"
            value={fmt(s.totalAssets)}
            color="#f59e0b"
          />
        </div>
        <KPI
          icon={Wallet}
          label="Group Cash"
          value={fmt(s.totalCash)}
          sub={`${s.pendingLoans || 0} pending loans`}
          color="#06b6d4"
        />
        <KPI
          icon={Users}
          label="Employees"
          value={s.totalEmployees || 0}
          sub="group-wide"
          color="#ec4899"
        />
      </div>

      {/* ── Charts Row 1 ─────────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-3 gap-5 mb-5">
        {/* Revenue Trend */}
        <Glass className="lg:col-span-2 p-5">
          <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
            <ChartLine size={18} weight="duotone" style={{ color: BRAND }} />{" "}
            Group Revenue Trend (6 months)
          </h3>
          <ResponsiveContainer width="100%" height={240}>
            <AreaChart data={trend}>
              <defs>
                <linearGradient id="rGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor={BRAND} stopOpacity={0.2} />
                  <stop offset="95%" stopColor={BRAND} stopOpacity={0} />
                </linearGradient>
                <linearGradient id="pGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#10b981" stopOpacity={0.2} />
                  <stop offset="95%" stopColor="#10b981" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="#EFEBE9" />
              <XAxis
                dataKey="month"
                tick={{ fontSize: 11, fill: "#9ca3af" }}
                axisLine={false}
                tickLine={false}
              />
              <YAxis
                tickFormatter={(v) => `₦${(v / 1000).toFixed(0)}K`}
                tick={{ fontSize: 10, fill: "#9ca3af" }}
                axisLine={false}
                tickLine={false}
              />
              <Tooltip
                formatter={(v) => [fmt(v)]}
                contentStyle={{
                  borderRadius: 12,
                  border: "none",
                  fontSize: 12,
                }}
              />
              <Legend wrapperStyle={{ fontSize: 11 }} />
              <Area
                type="monotone"
                dataKey="revenue"
                name="Revenue"
                stroke={BRAND}
                strokeWidth={2.5}
                fill="url(#rGrad)"
              />
              <Area
                type="monotone"
                dataKey="expenses"
                name="Expenses"
                stroke="#f59e0b"
                strokeWidth={2}
                fill="none"
                strokeDasharray="4 2"
              />
              <Area
                type="monotone"
                dataKey="profit"
                name="Profit"
                stroke="#10b981"
                strokeWidth={2.5}
                fill="url(#pGrad)"
              />
            </AreaChart>
          </ResponsiveContainer>
        </Glass>

        {/* Revenue Pie */}
        <Glass className="p-5">
          <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
            <ChartPieSlice
              size={18}
              weight="duotone"
              style={{ color: "#8b5cf6" }}
            />{" "}
            Revenue Distribution
          </h3>
          <ResponsiveContainer width="100%" height={200}>
            <PieChart>
              <Pie
                data={pieData}
                cx="50%"
                cy="50%"
                innerRadius={50}
                outerRadius={85}
                paddingAngle={3}
                dataKey="value"
              >
                {pieData.map((_, i) => (
                  <Cell key={i} fill={COLORS[i % COLORS.length]} />
                ))}
              </Pie>
              <Tooltip
                formatter={(v) => [fmt(v), "Revenue"]}
                contentStyle={{
                  borderRadius: 10,
                  border: "none",
                  fontSize: 11,
                }}
              />
            </PieChart>
          </ResponsiveContainer>
          <div className="mt-2 space-y-1 max-h-28 overflow-y-auto">
            {pieData.map((d, i) => (
              <div
                key={i}
                className="flex items-center justify-between text-xs"
              >
                <span className="flex items-center gap-1.5">
                  <span
                    className="w-2 h-2 rounded-full"
                    style={{ background: COLORS[i % COLORS.length] }}
                  />
                  {d.name}
                </span>
                <span className="font-semibold text-gray-700">
                  {fmt(d.value)}
                </span>
              </div>
            ))}
          </div>
        </Glass>
      </div>

      {/* ── Charts Row 2 ─────────────────────────────────── */}
      <div className="grid grid-cols-1 lg:grid-cols-2 gap-5 mb-5">
        {/* Employee Distribution */}
        <Glass className="p-5">
          <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
            <Users size={18} weight="duotone" style={{ color: "#ec4899" }} />{" "}
            Headcount by Company
          </h3>
          <ResponsiveContainer width="100%" height={220}>
            <BarChart
              data={empDist}
              layout="vertical"
              margin={{ left: 10, right: 15 }}
            >
              <CartesianGrid
                strokeDasharray="3 3"
                stroke="#EFEBE9"
                horizontal={false}
              />
              <XAxis
                type="number"
                tick={{ fontSize: 10, fill: "#9ca3af" }}
                axisLine={false}
                tickLine={false}
              />
              <YAxis
                dataKey="name"
                type="category"
                tick={{ fontSize: 10, fill: "#6b7280" }}
                width={90}
                axisLine={false}
                tickLine={false}
              />
              <Tooltip
                contentStyle={{
                  borderRadius: 10,
                  border: "none",
                  fontSize: 11,
                }}
              />
              <Bar dataKey="count" name="Employees" radius={[0, 6, 6, 0]}>
                {empDist.map((_, i) => (
                  <Cell key={i} fill={COLORS[i % COLORS.length]} />
                ))}
              </Bar>
            </BarChart>
          </ResponsiveContainer>
        </Glass>

        {/* Loan Requests */}
        <Glass className="p-5">
          <div className="flex items-center justify-between mb-4">
            <h3 className="font-bold text-gray-800 flex items-center gap-2">
              <Receipt
                size={18}
                weight="duotone"
                style={{ color: "#f59e0b" }}
              />{" "}
              Intercompany Loans
            </h3>
            {s.pendingLoans > 0 && (
              <span className="px-2 py-1 rounded-full text-xs font-bold bg-orange-100 text-orange-700">
                {s.pendingLoans} pending
              </span>
            )}
          </div>
          <div className="space-y-2 max-h-60 overflow-y-auto pr-1">
            {loans.length === 0 && (
              <p className="text-sm text-gray-400 text-center py-6">
                No loan records
              </p>
            )}
            {loans.map((l, i) => (
              <div
                key={i}
                className="flex items-center justify-between p-3 rounded-xl border border-gray-100 bg-gray-50 hover:bg-primary-50 transition-all"
              >
                <div className="min-w-0">
                  <p className="text-sm font-bold text-gray-900 truncate">
                    {l.company}
                  </p>
                  <p className="text-xs text-gray-500">
                    {fmt(l.amount)} @ {l.interest_rate}% • {l.term}mo
                  </p>
                  <p className="text-xs text-gray-400 truncate">{l.purpose}</p>
                </div>
                <span
                  className={`ml-3 px-2 py-1 rounded-lg text-xs font-bold flex-shrink-0 ${
                    l.status === "active"
                      ? "bg-green-100 text-green-700"
                      : l.status === "pending"
                        ? "bg-orange-100 text-orange-700"
                        : l.status === "approved"
                          ? "bg-primary-100 text-primary-700"
                          : "bg-gray-100 text-gray-600"
                  }`}
                >
                  {l.status}
                </span>
              </div>
            ))}
          </div>
        </Glass>
      </div>

      {/* ── Company Health Matrix ─────────────────────────── */}
      <Glass className="overflow-hidden">
        <div className="p-5 border-b border-gray-100 flex items-center justify-between">
          <h3 className="font-bold text-gray-800 flex items-center gap-2">
            <Target size={18} weight="duotone" style={{ color: BRAND }} />{" "}
            Company Health Matrix
          </h3>
          <span className="text-xs text-gray-400">
            {companies.length} companies
          </span>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr style={{ background: `${BRAND}08` }}>
                {[
                  "Company",
                  "Revenue",
                  "Profit",
                  "Cash",
                  "Assets",
                  "Employees",
                  "Credit",
                  "Runway",
                  "Health",
                ].map((h) => (
                  <th
                    key={h}
                    className="px-4 py-3 text-left text-xs font-bold text-gray-500 uppercase tracking-wider whitespace-nowrap"
                  >
                    {h}
                  </th>
                ))}
              </tr>
            </thead>
            <tbody className="divide-y divide-gray-50">
              {companies.map((c, i) => {
                const hs = c.healthStatus || "good";
                const hc = healthColors[hs] || BRAND;
                const hb = healthBg[hs] || "#e0e7ff";
                return (
                  <tr
                    key={i}
                    className="hover:bg-primary-50 hover:bg-opacity-30 transition-colors cursor-pointer"
                    onClick={() => navigate(`/companies/${c.id}`)}
                  >
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-2">
                        <div
                          className="w-8 h-8 rounded-lg flex items-center justify-center text-white text-xs font-black flex-shrink-0"
                          style={{
                            background: `linear-gradient(135deg,${BRAND},#A1887F)`,
                          }}
                        >
                          {c.name?.charAt(0)}
                        </div>
                        <div>
                          <p className="font-semibold text-gray-900 text-xs">
                            {c.name}
                          </p>
                          <p className="text-gray-400 text-xs">{c.industry}</p>
                        </div>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-xs font-semibold text-gray-800 whitespace-nowrap">
                      {fmt(c.revenue)}
                    </td>
                    <td className="px-4 py-3 whitespace-nowrap">
                      <span
                        className={`text-xs font-bold ${c.profit >= 0 ? "text-green-600" : "text-red-600"}`}
                      >
                        {fmt(Math.abs(c.profit))}
                      </span>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600 whitespace-nowrap">
                      {fmt(c.cash)}
                    </td>
                    <td
                      className="px-4 py-3 text-xs text-gray-600 whitespace-nowrap cursor-pointer hover:bg-primary-50 rounded-md transition-colors"
                      onClick={() => {
                        setAssetCompany(c);
                        setShowAssets(true);
                      }}
                    >
                      {fmt(c.totalAssets)}
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-700 font-medium">
                      {c.employees}
                    </td>
                    <td className="px-4 py-3">
                      <div className="flex items-center gap-1.5">
                        <div className="w-12 h-1.5 bg-gray-100 rounded-full overflow-hidden">
                          <div
                            className="h-full rounded-full"
                            style={{
                              width: `${Math.min((c.creditScore / 850) * 100, 100)}%`,
                              background: hc,
                            }}
                          />
                        </div>
                        <span className="text-xs font-bold text-gray-700">
                          {c.creditScore}
                        </span>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-xs text-gray-600 whitespace-nowrap">
                      {c.runwayDays}d
                    </td>
                    <td className="px-4 py-3">
                      <span
                        className="px-2 py-1 rounded-lg text-xs font-bold capitalize"
                        style={{ background: hb, color: hc }}
                      >
                        {hs}
                      </span>
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      </Glass>

      {/* ── Profit Allocation ─────────────────────────────────── */}
      {allocations.length > 0 && (
        <Glass className="p-5 mt-5">
          <h3 className="font-bold text-gray-800 mb-4 flex items-center gap-2">
            <TrendUp size={18} weight="duotone" style={{ color: "#10b981" }} />{" "}
            Recent Profit Allocations
            <span className="ml-auto text-xs font-bold px-2 py-1 rounded-full bg-green-100 text-green-700">
              {fmt(allocations.reduce((s, x) => s + (x.amount || 0), 0))} total
            </span>
          </h3>
          <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3">
            {allocations.map((alloc, i) => (
              <div
                key={i}
                className="p-3 rounded-xl bg-gradient-to-br from-green-50 to-primary-50 border border-green-100"
              >
                <p className="text-sm font-bold text-gray-900">
                  {alloc.company}
                </p>
                <p className="text-xs text-gray-500">→ {alloc.destination}</p>
                <p className="text-lg font-black text-green-600 mt-1">
                  {fmt(alloc.amount)}
                </p>
                <div className="flex items-center justify-between mt-1">
                  <span className="text-xs text-gray-400">
                    {alloc.allocation_date}
                  </span>
                  <span className="text-xs font-bold px-2 py-0.5 rounded-full bg-green-100 text-green-700">
                    {alloc.status}
                  </span>
                </div>
              </div>
            ))}
          </div>
        </Glass>
      )}

      {/* Asset Detail Modal */}
      {showAssets && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
          <div className="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-[90vh] overflow-y-auto">
            <div className="bg-gradient-to-r from-primary-600 to-primary-500 text-white px-6 py-4 rounded-t-2xl flex items-center justify-between">
              <div>
                <h2 className="text-xl font-bold">
                  {assetCompany ? assetCompany.name : "Group"} Assets
                </h2>
                <p className="text-primary-100 text-sm">
                  {assetCompany
                    ? assetCompany.industry
                    : "All subsidiary companies"}
                </p>
              </div>
              <button
                onClick={() => setShowAssets(false)}
                className="text-white/80 hover:text-white text-2xl"
              >
                &times;
              </button>
            </div>

            <div className="p-6 space-y-6">
              {(() => {
                const total = assetCompany
                  ? assetCompany.totalAssets
                  : data?.stats?.totalAssets || 0;
                const assets = assetCompany
                  ? assetCompany.assets || []
                  : (data?.companies || []).flatMap((c) =>
                      (c.assets || []).map((a) => ({
                        ...a,
                        name: `${c.name.split(" ")[0]} — ${a.name}`,
                      })),
                    );

                if (assets.length === 0) {
                  return (
                    <div className="py-16 text-center text-gray-400">
                      <Bank
                        size={40}
                        weight="duotone"
                        className="mx-auto mb-3 opacity-30"
                      />
                      <p className="font-semibold text-gray-500">
                        No assets recorded yet
                      </p>
                      <p className="text-sm mt-1">
                        Assets will appear here once added via the Assets
                        module.
                      </p>
                      {total > 0 && (
                        <div className="mt-4 inline-block bg-primary-50 border border-primary-100 rounded-xl px-5 py-3">
                          <p className="text-xs text-gray-500">
                            Balance-sheet total
                          </p>
                          <p className="text-lg font-black text-primary-700">
                            {fmt(total)}
                          </p>
                        </div>
                      )}
                    </div>
                  );
                }

                const sortedAssets = [...assets].sort(
                  (a, b) => b.value - a.value,
                );
                const categories = [...new Set(assets.map((a) => a.category))];

                return (
                  <>
                    {/* Summary KPIs by category */}
                    <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
                      {[
                        {
                          label: "Total Assets",
                          value: fmt(total),
                          bg: "#EFEBE9",
                          c: BRAND,
                        },
                        ...categories.slice(0, 3).map((cat, i) => ({
                          label: cat,
                          value: fmt(
                            assets
                              .filter((a) => a.category === cat)
                              .reduce((s, a) => s + a.value, 0),
                          ),
                          bg: ["#dcfce7", "#fef3c7", "#e0e7ff"][i],
                          c: ["#10b981", "#f59e0b", "#6366f1"][i],
                        })),
                      ].map((k, i) => (
                        <div
                          key={i}
                          className="bg-gray-50 rounded-xl p-4 text-center"
                        >
                          <div className="text-xs text-gray-500 mb-1">
                            {k.label}
                          </div>
                          <div className="text-lg font-bold text-gray-900">
                            {k.value}
                          </div>
                        </div>
                      ))}
                    </div>

                    {/* Asset table */}
                    <div className="border border-gray-100 rounded-xl overflow-hidden">
                      <table className="w-full text-sm">
                        <thead className="bg-gray-50">
                          <tr className="border-b border-gray-100">
                            {[
                              "Asset Name",
                              "Category",
                              "Current Value",
                              "% of Total",
                            ].map((h) => (
                              <th
                                key={h}
                                className="text-left py-3 px-4 text-gray-500 font-semibold text-xs uppercase"
                              >
                                {h}
                              </th>
                            ))}
                          </tr>
                        </thead>
                        <tbody>
                          {sortedAssets.map((a, i) => (
                            <tr
                              key={i}
                              className="border-b border-gray-50 hover:bg-gray-50"
                            >
                              <td className="py-3 px-4 font-medium text-gray-900">
                                {a.name}
                              </td>
                              <td className="py-3 px-4">
                                <span
                                  className="px-2 py-0.5 rounded-md text-xs font-semibold"
                                  style={{
                                    background: "#EFEBE9",
                                    color: BRAND,
                                  }}
                                >
                                  {a.category}
                                </span>
                              </td>
                              <td className="py-3 px-4 font-bold text-gray-900">
                                {fmt(a.value)}
                              </td>
                              <td className="py-3 px-4 text-gray-500 text-xs">
                                {total > 0
                                  ? ((a.value / total) * 100).toFixed(1)
                                  : "0"}
                                %
                              </td>
                            </tr>
                          ))}
                        </tbody>
                      </table>
                    </div>
                  </>
                );
              })()}
            </div>
          </div>
        </div>
      )}
    </div>
  );
}
