// "use client";

// import React, { useState, useEffect, useMemo } from "react";
// import { useVoiceSummary, DateGroup, SourceDayRow } from "@/hooks/voicecall/useVoiceSummary";
// import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
// import { Input } from "@/components/ui/input";
// import { Button } from "@/components/ui/button";
// import Image from "next/image";
// import {
//     Search, BarChart3, ChevronDown, ChevronRight, Calendar,
//     ArrowUpDown, ArrowUp, ArrowDown, Loader2, AlertCircle,
// } from "lucide-react";
// import {
//     Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement,
//     PointElement, ArcElement, Title, Tooltip, Legend, Filler,
// } from "chart.js";
// import { Bar, Line, Doughnut } from "react-chartjs-2";

// ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, ArcElement, Title, Tooltip, Legend, Filler);

// // ─── Company color map ────────────────────────────────────────────────────────

// const COMPANY_COLORS: Record<string, string> = {
//     KTAHV: "#059669", "Villa Raag": "#d97706", KAPPL: "#be185d",
// };
// const CC_FALLBACK = ["#2563eb", "#7c3aed", "#0891b2", "#b45309", "#4338ca"];

// function companyColor(name: string): string {
//     if (COMPANY_COLORS[name]) return COMPANY_COLORS[name];
//     let hash = 0;
//     for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
//     COMPANY_COLORS[name] = CC_FALLBACK[Math.abs(hash) % CC_FALLBACK.length];
//     return COMPANY_COLORS[name];
// }

// // ─── Helpers ──────────────────────────────────────────────────────────────────

// const fmtPct = (n: number, d: number) => d > 0 ? ((n / d) * 100).toFixed(1) : "0.0";
// const normalize = (val?: string) => val?.trim().toLowerCase().replace(/\s+/g, "_") || "";
// const ZERO_SUM = {
//     sent: 0, sentHigh: 0, sentMedium: 0, sentLow: 0,
//     responses: 0, respHigh: 0, respMedium: 0, respLow: 0,
//     qualified: 0, qualHigh: 0, qualMedium: 0, qualLow: 0,
//     dead: 0, deadHigh: 0, deadMedium: 0, deadLow: 0,
// };

// function sumGroup(rows: Partial<SourceDayRow>[] = []) {
//     return rows.reduce((a, c) => ({
//         sent: (a.sent ?? 0) + (c.sent ?? 0),
//         sentHigh: (a.sentHigh ?? 0) + (c.sentHigh ?? 0),
//         sentMedium: (a.sentMedium ?? 0) + (c.sentMedium ?? 0),
//         sentLow: (a.sentLow ?? 0) + (c.sentLow ?? 0),
//         responses: (a.responses ?? 0) + (c.responses ?? 0),
//         respHigh: (a.respHigh ?? 0) + (c.respHigh ?? 0),
//         respMedium: (a.respMedium ?? 0) + (c.respMedium ?? 0),
//         respLow: (a.respLow ?? 0) + (c.respLow ?? 0),
//         qualified: (a.qualified ?? 0) + (c.qualified ?? 0),
//         qualHigh: (a.qualHigh ?? 0) + (c.qualHigh ?? 0),
//         qualMedium: (a.qualMedium ?? 0) + (c.qualMedium ?? 0),
//         qualLow: (a.qualLow ?? 0) + (c.qualLow ?? 0),
//         dead: (a.dead ?? 0) + (c.dead ?? 0),
//         deadHigh: (a.deadHigh ?? 0) + (c.deadHigh ?? 0),
//         deadMedium: (a.deadMedium ?? 0) + (c.deadMedium ?? 0),
//         deadLow: (a.deadLow ?? 0) + (c.deadLow ?? 0),
//     }), { ...ZERO_SUM });
// }

// function filterByDateRange(groups: DateGroup[], range: string, custom: { start: string; end: string }): DateGroup[] {
//     if (range === "all") return groups;
//     const now = new Date();
//     const today = now.toISOString().slice(0, 10);
//     let from = "", to = today;

//     if (range === "today") { from = today; }
//     else if (range === "yesterday") {
//         const d = new Date(now); d.setDate(d.getDate() - 1);
//         from = to = d.toISOString().slice(0, 10);
//     } else if (range === "this_week") {
//         const d = new Date(now); d.setDate(d.getDate() - d.getDay());
//         from = d.toISOString().slice(0, 10);
//     } else if (range === "last_week") {
//         const end = new Date(now); end.setDate(end.getDate() - end.getDay() - 1);
//         const start = new Date(end); start.setDate(start.getDate() - 6);
//         from = start.toISOString().slice(0, 10); to = end.toISOString().slice(0, 10);
//     } else if (range === "this_month") {
//         from = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}-01`;
//     } else if (range === "last_month") {
//         const d = new Date(now.getFullYear(), now.getMonth() - 1, 1);
//         from = d.toISOString().slice(0, 10);
//         const e = new Date(now.getFullYear(), now.getMonth(), 0);
//         to = e.toISOString().slice(0, 10);
//     } else if (range === "this_year") {
//         from = `${now.getFullYear()}-01-01`;
//     } else if (range === "last_year") {
//         from = `${now.getFullYear() - 1}-01-01`; to = `${now.getFullYear() - 1}-12-31`;
//     } else if (range === "custom") {
//         from = custom.start; to = custom.end || today;
//     }

//     return groups.filter(g => g.date >= from && g.date <= to);
// }

// // ─── Icons ────────────────────────────────────────────────────────────────────

// const S = 12;
// const icons = {
//     chart: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
//     table: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" strokeWidth="2" /><path d="M3 9h18M3 15h18M9 3v18" strokeWidth="2" strokeLinecap="round" /></svg>,
//     trend: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
//     dashboard: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><rect x="3" y="3" width="7" height="7" rx="1" strokeWidth="2" /><rect x="14" y="3" width="7" height="7" rx="1" strokeWidth="2" /><rect x="3" y="14" width="7" height="7" rx="1" strokeWidth="2" /><rect x="14" y="14" width="7" height="7" rx="1" strokeWidth="2" /></svg>,
//     check: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><polyline points="20 6 9 17 4 12" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
// };

// // ─── Chart helpers ────────────────────────────────────────────────────────────

// const chartFont = { family: "'Inter', sans-serif" };
// const commonBarOpts: any = {
//     responsive: true, maintainAspectRatio: false,
//     plugins: { legend: { display: false }, tooltip: { titleFont: { ...chartFont, size: 11 }, bodyFont: { ...chartFont, size: 11 } } },
//     scales: {
//         x: { ticks: { font: chartFont, color: "#64748b" }, grid: { display: false }, border: { display: false } },
//         y: { ticks: { font: chartFont, color: "#64748b" }, grid: { color: "#f1f5f9" }, border: { display: false } },
//     },
//     barPercentage: 0.75, categoryPercentage: 0.7,
// };

// function ChartLegend({ items }: { items: { color: string; label: string; round?: boolean }[] }) {
//     return (
//         <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginTop: 10 }}>
//             {items.map(l => (
//                 <div key={l.label} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, color: "#64748b" }}>
//                     <div style={{ width: 8, height: 8, borderRadius: l.round ? "50%" : 2, background: l.color, flexShrink: 0 }} />{l.label}
//                 </div>
//             ))}
//         </div>
//     );
// }

// function ChartCard({ title, subtitle, iconBg, iconColor, icon, legend, children }: {
//     title: string; subtitle: string; iconBg: string; iconColor: string; icon: React.ReactNode;
//     legend?: { color: string; label: string; round?: boolean }[]; children: React.ReactNode;
// }) {
//     return (
//         <div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
//             <div className="flex items-start gap-3 px-4 py-3 border-b border-slate-100">
//                 <div style={{ width: 24, height: 24, borderRadius: 6, background: iconBg, color: iconColor, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{icon}</div>
//                 <div>
//                     <div className="text-[12.5px] font-bold text-slate-800">{title}</div>
//                     <div className="text-[11px] text-slate-400 mt-0.5">{subtitle}</div>
//                 </div>
//             </div>
//             <div className="p-4">{children}{legend && <ChartLegend items={legend} />}</div>
//         </div>
//     );
// }

// // ─── Table constants ──────────────────────────────────────────────────────────

// const HDR_BG = "#1e3a5f";
// const HDR_BG2 = "#162d4a";
// const CELL = {
//     H: { bg: "#f0fdf4", count: "#166534", pct: "#15803d" },
//     M: { bg: "#fefce8", count: "#92400e", pct: "#a16207" },
//     L: { bg: "#fef2f2", count: "#991b1b", pct: "#b91c1c" },
// };

// // ─── % Formula (Table columns) ────────────────────────────────────────────────
// //
// //   Sent      → sent      / grand.sent       (is date/source ka share of total sent)
// //   Responses → responses / grand.responses  (✅ FIX: is date/source ka share of total responses)
// //   Qualified → qualified / responses        (call outcome — % of responses that qualified)
// //   Dead      → dead      / responses        (call outcome — % of responses that went dead)
// //
// // Source sub-rows same formula:
// //   Sent      → s.sent      / t.sent         (source share of day's sent)
// //   Responses → s.responses / t.responses    (✅ FIX: source share of day's responses)
// //   Qualified → s.qualified / s.responses
// //   Dead      → s.dead      / s.responses

// const GROUPS = [
//     {
//         key: "sent", label: "Leads Sent",
//         hdrBg: "#ebfffd", hdrText: "#013b37",
//         getTotal: (t: ReturnType<typeof sumGroup>) => t.sent,
//         getH: (t: ReturnType<typeof sumGroup>) => t.sentHigh,
//         getM: (t: ReturnType<typeof sumGroup>) => t.sentMedium,
//         getL: (t: ReturnType<typeof sumGroup>) => t.sentLow,
//         // sent / grand.sent
//         getDenominator: (_t: ReturnType<typeof sumGroup>, grand: ReturnType<typeof sumGroup>) => grand.sent,
//     },
//     {
//         key: "resp", label: "Responses Received",
//         hdrBg: "#fef3c7", hdrText: "#92400e",
//         getTotal: (t: ReturnType<typeof sumGroup>) => t.responses,
//         getH: (t: ReturnType<typeof sumGroup>) => t.respHigh,
//         getM: (t: ReturnType<typeof sumGroup>) => t.respMedium,
//         getL: (t: ReturnType<typeof sumGroup>) => t.respLow,
//         // ✅ FIX: responses / grand.responses (was t.sent before — wrong)
//         getDenominator: (_t: ReturnType<typeof sumGroup>, grand: ReturnType<typeof sumGroup>) => grand.responses,
//     },
//     {
//         key: "qual", label: "Qualified",
//         hdrBg: "#dcfce7", hdrText: "#166534",
//         getTotal: (t: ReturnType<typeof sumGroup>) => t.qualified,
//         getH: (t: ReturnType<typeof sumGroup>) => t.qualHigh,
//         getM: (t: ReturnType<typeof sumGroup>) => t.qualMedium,
//         getL: (t: ReturnType<typeof sumGroup>) => t.qualLow,
//         // qualified / responses
//         getDenominator: (t: ReturnType<typeof sumGroup>, _grand: ReturnType<typeof sumGroup>) => t.responses,
//     },
//     {
//         key: "dead", label: "Dead / Non-Qual",
//         hdrBg: "#ffe4e6", hdrText: "#9f1239",
//         getTotal: (t: ReturnType<typeof sumGroup>) => t.dead,
//         getH: (t: ReturnType<typeof sumGroup>) => t.deadHigh,
//         getM: (t: ReturnType<typeof sumGroup>) => t.deadMedium,
//         getL: (t: ReturnType<typeof sumGroup>) => t.deadLow,
//         // dead / responses
//         getDenominator: (t: ReturnType<typeof sumGroup>, _grand: ReturnType<typeof sumGroup>) => t.responses,
//     },
// ] as const;

// // ─── GroupCells ───────────────────────────────────────────────────────────────

// function GroupCells({ total, H, M, L, denominator = 0, isDateRow = false, isGrand = false, onCellClick }:
//     { total: number; H: number; M: number; L: number; denominator?: number; isDateRow?: boolean; isGrand?: boolean; onCellClick?: (intent: string) => void }) {

//     if (isGrand) {
//         return (
//             <>
//                 <td className="px-3 py-2.5 text-center whitespace-nowrap border-l border-white/10">
//                     <span style={{ fontSize: 14, fontWeight: 800, color: "#f1f5f9" }}>{total}</span>
//                 </td>
//                 <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100">
//                     <span className="text-[11px] text-slate-500">{denominator > 0 ? `${fmtPct(total, denominator)}%` : "0%"}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(22,101,52,0.25)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
//                     <span style={{ fontSize: 12, fontWeight: 700, color: "#86efac" }}>{H}</span>
//                 </td>
//                 <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.H.bg }}>
//                     <span style={{ fontSize: 11, color: CELL.H.pct }}>{fmtPct(H, total)}%</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(120,53,15,0.25)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
//                     <span style={{ fontSize: 12, fontWeight: 700, color: "#fde68a" }}>{M}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(120,53,15,0.15)" }}>
//                     <span style={{ fontSize: 11, color: "#fcd34d" }}>{fmtPct(M, total)}%</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(127,29,29,0.25)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
//                     <span style={{ fontSize: 12, fontWeight: 700, color: "#fca5a5" }}>{L}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(127,29,29,0.15)" }}>
//                     <span style={{ fontSize: 11, color: "#f87171" }}>{fmtPct(L, total)}%</span>
//                 </td>
//             </>
//         );
//     }

//     if (isDateRow) {
//         return (
//             <>
//                 <td className="px-3 py-2.5 text-center whitespace-nowrap border-l-2 border-slate-300">
//                     <span className="text-sm font-bold text-slate-800">{total}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap">
//                     <span className="text-[11px] font-semibold text-slate-500">{denominator > 0 ? `${fmtPct(total, denominator)}%` : "0%"}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.H.bg, borderLeft: "1px solid #bbf7d0" }}>
//                     <span style={{ fontSize: 12, fontWeight: 700, color: CELL.H.count }}>{H}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.H.bg }}>
//                     <span style={{ fontSize: 11, color: CELL.H.pct }}>{fmtPct(H, total)}%</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.M.bg, borderLeft: "1px solid #fde68a" }}>
//                     <span style={{ fontSize: 12, fontWeight: 700, color: CELL.M.count }}>{M}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.M.bg }}>
//                     <span style={{ fontSize: 11, color: CELL.M.pct }}>{fmtPct(M, total)}%</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.L.bg, borderLeft: "1px solid #fca5a5" }}>
//                     <span style={{ fontSize: 12, fontWeight: 700, color: CELL.L.count }}>{L}</span>
//                 </td>
//                 <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.L.bg }}>
//                     <span style={{ fontSize: 11, color: CELL.L.pct }}>{fmtPct(L, total)}%</span>
//                 </td>
//             </>
//         );
//     }

//     // Source expanded row
//     const cs = (count: number) => onCellClick && count > 0
//         ? { cursor: "pointer" as const, textDecoration: "underline" as const }
//         : {};
//     return (
//         <>
//             <td className="px-3 py-2 text-center whitespace-nowrap border-l-2 border-slate-200 border-b border-slate-100" onClick={() => total > 0 && onCellClick?.("ALL")} style={cs(total)}>
//                 <span className="text-[13px] font-semibold text-slate-800" style={cs(total)}>{total}</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100">
//                 <span className="text-[11px] text-slate-500">{denominator > 0 ? `${fmtPct(total, denominator)}%` : "0%"}</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.H.bg, borderLeft: "1px solid #dcfce7" }} onClick={() => H > 0 && onCellClick?.("HIGH")}>
//                 <span style={{ fontSize: 12, fontWeight: 700, color: CELL.H.count, ...cs(H) }}>{H}</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.H.bg }}>
//                 <span style={{ fontSize: 11, color: CELL.H.pct }}>{fmtPct(H, total)}%</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.M.bg, borderLeft: "1px solid #fef9c3" }} onClick={() => M > 0 && onCellClick?.("MEDIUM")}>
//                 <span style={{ fontSize: 12, fontWeight: 700, color: CELL.M.count, ...cs(M) }}>{M}</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.M.bg }}>
//                 <span style={{ fontSize: 11, color: CELL.M.pct }}>{fmtPct(M, total)}%</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.L.bg, borderLeft: "1px solid #ffe4e6" }} onClick={() => L > 0 && onCellClick?.("LOW")}>
//                 <span style={{ fontSize: 12, fontWeight: 700, color: CELL.L.count, ...cs(L) }}>{L}</span>
//             </td>
//             <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.L.bg }}>
//                 <span style={{ fontSize: 11, color: CELL.L.pct }}>{fmtPct(L, total)}%</span>
//             </td>
//         </>
//     );
// }

// // ─── Loading / Error / Empty ──────────────────────────────────────────────────

// function TableSkeleton() {
//     return (
//         <div className="p-6 space-y-3 animate-pulse">
//             {[...Array(5)].map((_, i) => <div key={i} className="h-12 bg-slate-100 rounded-lg" />)}
//         </div>
//     );
// }
// function TableError({ message, onRetry }: { message: string; onRetry: () => void }) {
//     return (
//         <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
//             <AlertCircle className="w-10 h-10 text-red-400" />
//             <p className="text-sm font-semibold text-slate-600">Failed to load data</p>
//             <p className="text-xs text-slate-400 max-w-sm">{message}</p>
//             <button onClick={onRetry} className="mt-1 px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold transition">Retry</button>
//         </div>
//     );
// }
// function TableEmpty() {
//     return (
//         <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
//             <div className="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center">{icons.table(22)}</div>
//             <p className="text-sm font-semibold text-slate-500">No data available</p>
//             <p className="text-xs text-slate-400">No records found for the selected filters.</p>
//         </div>
//     );
// }

// // ─── Breakdown Table ──────────────────────────────────────────────────────────

// function CompanyBreakdownTable({ company, sourceFilter, dateGroups, search, priority }: {
//     company: string; sourceFilter: string; dateGroups: DateGroup[]; search: string; priority: string;
// }) {
//     const filtered = useMemo(() => dateGroups
//         .map(dg => ({
//             ...dg,
//             sources: dg.sources.filter(s => {

//                 const matchCompany =
//                     company === "all" ||
//                     s.company?.split(",").some(c =>
//                         normalize(c) === normalize(company)
//                     );

//                 const matchSource =
//                     sourceFilter === "all" ||
//                     normalize(s.source) === normalize(sourceFilter);


//                 const matchSearch =
//                     !search.trim() ||
//                     s.source?.toLowerCase().includes(search.toLowerCase()) ||
//                     s.company?.toLowerCase().includes(search.toLowerCase());

//                 const matchPriority =
//                     priority === "all" ||
//                     (priority === "high" && (s.sentHigh > 0 || s.qualHigh > 0)) ||
//                     (priority === "medium" && (s.sentMedium > 0 || s.qualMedium > 0)) ||
//                     (priority === "low" && (s.sentLow > 0 || s.qualLow > 0));

//                 return matchCompany && matchSource && matchSearch && matchPriority;
//             }),
//         }))
//         .filter(dg => dg.sources.length > 0),
//         [dateGroups, company, sourceFilter, search, priority]
//     );
//     // const filtered = useMemo(() => dateGroups
//     //     .map(dg => ({
//     //         ...dg,
//     //         sources: dg.sources.filter(s => {
//     //             const matchCompany = company === "all" || s.company?.split(",").some(c => c.trim().toLowerCase().replace(/\s+/g, "_") === company);
//     //             const matchSource = sourceFilter === "all" || normalize(s.source) === normalize(sourceFilter);
//     //             return matchCompany && matchSource;
//     //         }),
//     //     }))
//     //     .filter(dg => dg.sources.length > 0),
//     //     [dateGroups, company, sourceFilter]
//     // );

//     const [expandedDates, setExpandedDates] = useState<Set<string>>(new Set());
//     const [sortField, setSortField] = useState<string>("date");
//     const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
//     const [currentPage, setCurrentPage] = useState(1);
//     const [rowsPerPage, setRowsPerPage] = useState(10);
//     const [gotoInput, setGotoInput] = useState("");

//     useEffect(() => {
//         if (filtered.length > 0) setExpandedDates(new Set([filtered[0].date]));
//     }, [filtered.length]);

//     useEffect(() => { setCurrentPage(1); }, [company, sourceFilter, dateGroups]);

//     const toggle = (date: string) => setExpandedDates(prev => {
//         const next = new Set(prev);
//         next.has(date) ? next.delete(date) : next.add(date);
//         return next;
//     });

//     const handleSort = (field: string) => {
//         if (sortField === field) setSortDir(d => d === "asc" ? "desc" : "asc");
//         else { setSortField(field); setSortDir("desc"); }
//     };

//     const SortIcon = ({ field }: { field: string }) => {
//         if (sortField !== field) return <ArrowUpDown className="w-3 h-3 opacity-50" />;
//         return sortDir === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />;
//     };

//     const sorted = useMemo(() => [...filtered].sort((a, b) => {
//         const tA = sumGroup(a.sources), tB = sumGroup(b.sources);
//         let vA: any, vB: any;
//         if (sortField === "date") { vA = a.date; vB = b.date; }
//         else {
//             const map = { sent: "sent", resp: "responses", qual: "qualified", dead: "dead" } as Record<string, keyof ReturnType<typeof sumGroup>>;
//             const key = map[sortField];
//             vA = key ? tA[key] : 0; vB = key ? tB[key] : 0;
//         }
//         return sortDir === "asc" ? (vA > vB ? 1 : -1) : (vA < vB ? 1 : -1);
//     }), [filtered, sortField, sortDir]);

//     const grand = useMemo(() => sumGroup(filtered.flatMap(dg => dg.sources)), [filtered]);
//     const totalDates = sorted.length;
//     const totalPages = Math.max(1, Math.ceil(totalDates / rowsPerPage));
//     const safePage = Math.min(currentPage, totalPages);
//     const startIdx = (safePage - 1) * rowsPerPage;
//     const paginated = sorted.slice(startIdx, startIdx + rowsPerPage);

//     const goToPage = (p: number) => setCurrentPage(Math.max(1, Math.min(p, totalPages)));
//     const handleRowsChange = (val: number) => { setRowsPerPage(val); setCurrentPage(1); };
//     const handleGoto = () => { const n = parseInt(gotoInput, 10); if (!isNaN(n)) goToPage(n); setGotoInput(""); };

//     if (totalDates === 0) return <TableEmpty />;

//     const PriSubHdr = ({ label }: { label: string }) => (
//         <th colSpan={2} className="px-2 py-2.5 text-center text-xs font-bold uppercase tracking-wider whitespace-nowrap"
//             style={{ backgroundColor: HDR_BG, color: "#fff", borderLeft: "1px solid rgba(255,255,255,0.15)" }}>
//             <div className="flex flex-col items-center gap-0.5">
//                 <span>{label}</span>
//                 <div className="flex gap-2 text-[10px] font-semibold normal-case mt-0.5" style={{ color: "rgba(255,255,255,0.55)" }}>
//                     <span>Count</span><span style={{ opacity: 0.4 }}>|</span><span>%</span>
//                 </div>
//             </div>
//         </th>
//     );

//     return (
//         <div>
//             <div className="overflow-x-auto">
//                 <div className="inline-block min-w-full align-middle">
//                     <table className="min-w-full" style={{ borderCollapse: "collapse" }}>
//                         <thead>
//                             <tr style={{ backgroundColor: HDR_BG }}>
//                                 <th rowSpan={2}
//                                     className="sticky left-0 z-20 px-4 py-3 text-left text-xs font-bold text-white uppercase tracking-wider whitespace-nowrap cursor-pointer hover:bg-white/10"
//                                     style={{ backgroundColor: HDR_BG, minWidth: 200, borderRight: "2px solid rgba(255,255,255,0.15)" }}
//                                     onClick={() => handleSort("date")}>
//                                     <div className="flex items-center gap-1.5">Date / Source <SortIcon field="date" /></div>
//                                 </th>
//                                 {GROUPS.map(g => (
//                                     <th key={g.key} colSpan={8}
//                                         className="px-3 py-2.5 text-center text-xs font-bold uppercase tracking-wider cursor-pointer whitespace-nowrap"
//                                         style={{ backgroundColor: g.hdrBg, color: g.hdrText, borderLeft: `2px solid ${g.hdrText}33` }}
//                                         onClick={() => handleSort(g.key)}>
//                                         <div className="flex items-center justify-center gap-1.5">{g.label} <SortIcon field={g.key} /></div>
//                                     </th>
//                                 ))}
//                             </tr>
//                             <tr style={{ backgroundColor: HDR_BG2 }}>
//                                 {GROUPS.map((g, i) => (
//                                     <React.Fragment key={g.key}>
//                                         <th colSpan={2}
//                                             className="px-3 py-2.5 text-center text-xs font-bold text-white uppercase tracking-wider whitespace-nowrap cursor-pointer hover:bg-white/10"
//                                             style={{ backgroundColor: HDR_BG2, borderLeft: i === 0 ? "none" : "2px solid rgba(255,255,255,0.2)" }}
//                                             onClick={() => handleSort(g.key)}>
//                                             <div className="flex flex-col items-center gap-0.5">
//                                                 <div className="flex items-center gap-1">Total <SortIcon field={g.key} /></div>
//                                                 <div className="flex gap-2 text-[10px] normal-case mt-0.5" style={{ color: "rgba(255,255,255,0.55)" }}>
//                                                     <span>Count</span><span style={{ opacity: 0.4 }}>|</span><span>%</span>
//                                                 </div>
//                                             </div>
//                                         </th>
//                                         <PriSubHdr label="High" />
//                                         <PriSubHdr label="Medium" />
//                                         <PriSubHdr label="Low" />
//                                     </React.Fragment>
//                                 ))}
//                             </tr>
//                         </thead>

//                         <tbody className="divide-y divide-slate-200 bg-white">
//                             {paginated.map(dg => {
//                                 const t = sumGroup(dg.sources);
//                                 const exp = expandedDates.has(dg.date);
//                                 const bg = exp ? "#eff6ff" : "#f8fafc";

//                                 return (
//                                     <React.Fragment key={dg.date}>
//                                         {/* Date row */}
//                                         <tr className="cursor-pointer hover:brightness-[0.97] transition-all border-b-2 border-slate-300"
//                                             style={{ background: bg }} onClick={() => toggle(dg.date)}>
//                                             <td className="sticky left-0 z-10 px-4 py-3 whitespace-nowrap" style={{ background: bg, borderRight: "2px solid #cbd5e1" }}>
//                                                 <div className="flex items-center gap-2">
//                                                     {exp ? <ChevronDown className="w-4 h-4 text-blue-600 flex-shrink-0" /> : <ChevronRight className="w-4 h-4 text-blue-600 flex-shrink-0" />}
//                                                     <Calendar className="w-3.5 h-3.5 text-slate-500 flex-shrink-0" />
//                                                     <span className="text-[13px] font-bold text-slate-800">{dg.displayDate ?? dg.date}</span>
//                                                     <span className="text-[11px] text-slate-500 ml-0.5">({dg.sources.length} src)</span>
//                                                 </div>
//                                             </td>
//                                             {GROUPS.map((g) => (
//                                                 <GroupCells key={g.key}
//                                                     total={g.getTotal(t)}
//                                                     H={g.getH(t)}
//                                                     M={g.getM(t)}
//                                                     L={g.getL(t)}
//                                                     denominator={g.getDenominator(t, grand)}
//                                                     isDateRow />
//                                             ))}
//                                         </tr>

//                                         {/* Source sub-rows */}
//                                         {exp && dg.sources.map(s => {
//                                             const handleClick = (intent: string, type: string) => {
//                                                 const base = "https://script.google.com/macros/s/AKfycbyZgL_rJ8A_8snRTfecPOs4fWtYVHvU6735g1scUgwcil0S4JpUK2tILv6MQuDhQEeixg/exec";
//                                                 const companyCount = s.company?.split(",").length ?? 1;
//                                                 const params = new URLSearchParams({
//                                                     date: dg.date, intent,
//                                                     company: companyCount > 1 ? "ALL" : s.company?.toUpperCase() || "ALL",
//                                                     src: s.source?.toUpperCase() || "ALL",
//                                                     type
//                                                 });
//                                                 window.open(`${base}?${params.toString()}`, "_blank");
//                                             };

//                                             return (
//                                                 <tr key={`${dg.date}-${s.company}-${s.source}`} className="bg-white hover:bg-slate-50 transition-colors">
//                                                     <td className="sticky left-0 z-10 bg-white px-6 py-2.5 whitespace-nowrap" style={{ borderRight: "2px solid #e2e8f0" }}>
//                                                         <div className="flex items-center gap-2">
//                                                             <div style={{ width: 9, height: 9, borderRadius: "50%", background: s.color, flexShrink: 0 }} />
//                                                             <span className="text-[13px] font-semibold text-slate-700">{s.source}</span>
//                                                         </div>
//                                                     </td>

//                                                     {/* Sent → s.sent / t.sent */}
//                                                     <GroupCells
//                                                         total={s.sent} H={s.sentHigh} M={s.sentMedium} L={s.sentLow}
//                                                         denominator={t.sent}
//                                                         onCellClick={(intent) => {
//                                                             const base = "https://script.google.com/macros/s/AKfycbym45pQfgcyqKRHLMtMt3gc0KWMcfPiHYngBZuswB7frxb7t4BMfxlVG1zFbe50bMH0/exec";
//                                                             const params = new URLSearchParams({
//                                                                 date: dg.date, intent,
//                                                                 company: (s.company?.split(",").length ?? 1) > 1 ? "ALL" : s.company?.toUpperCase() || "ALL",
//                                                                 src: s.source?.toUpperCase() || "ALL"
//                                                             });
//                                                             window.open(`${base}?${params.toString()}`, "_blank");
//                                                         }}
//                                                     />

//                                                     {/* ✅ FIX: Responses → s.responses / t.responses (was s.sent before) */}
//                                                     <GroupCells
//                                                         total={s.responses} H={s.respHigh} M={s.respMedium} L={s.respLow}
//                                                         denominator={t.responses}
//                                                         onCellClick={(intent) => handleClick(intent, "RECEIVED")}
//                                                     />

//                                                     {/* Qualified → s.qualified / t.qualified */}
//                                                     <GroupCells
//                                                         total={s.qualified} H={s.qualHigh} M={s.qualMedium} L={s.qualLow}
//                                                         denominator={t.qualified}
//                                                         onCellClick={(intent) => handleClick(intent, "QUALIFIED")}
//                                                     />

//                                                     {/* Dead → s.dead / t.dead */}
//                                                     <GroupCells
//                                                         total={s.dead} H={s.deadHigh} M={s.deadMedium} L={s.deadLow}
//                                                         denominator={t.dead}
//                                                         onCellClick={(intent) => handleClick(intent, "DEAD")}
//                                                     />
//                                                 </tr>
//                                             );
//                                         })}
//                                     </React.Fragment>
//                                 );
//                             })}
//                         </tbody>

//                         <tfoot>
//                             <tr style={{ background: "#0f172a", borderTop: "3px solid #334155" }}>
//                                 <td className="sticky left-0 z-10 px-4 py-3 whitespace-nowrap" style={{ background: "#0f172a", borderRight: "2px solid #1e293b" }}>
//                                     <span className="text-[12px] font-extrabold text-white uppercase tracking-wider">Grand Total</span>
//                                     <span className="ml-2 text-[11px] text-slate-400">({totalDates} dates)</span>
//                                 </td>
//                                 {/* Grand total: getDenominator(grand, grand) → same formula auto-applied */}
//                                 {GROUPS.map((g) => (
//                                     <GroupCells key={g.key}
//                                         total={g.getTotal(grand)}
//                                         H={g.getH(grand)}
//                                         M={g.getM(grand)}
//                                         L={g.getL(grand)}
//                                         denominator={g.getDenominator(grand, grand)}
//                                         isGrand />
//                                 ))}
//                             </tr>
//                         </tfoot>
//                     </table>
//                 </div>
//             </div>

//             {/* Pagination */}
//             <div className="flex flex-wrap items-center justify-between gap-y-2 gap-x-3 px-3 sm:px-4 py-3 border-t border-slate-200 bg-slate-50 text-[12px] text-slate-600 select-none">
//                 <span>Showing <strong className="text-slate-800">{totalDates === 0 ? "0" : `${startIdx + 1}–${Math.min(startIdx + rowsPerPage, totalDates)}`}</strong> of <strong className="text-slate-800">{totalDates}</strong> date{totalDates !== 1 ? "s" : ""}</span>
//                 <div className="flex items-center gap-1">
//                     <button onClick={() => goToPage(1)} disabled={safePage === 1} className="w-7 h-7 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-bold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition">«</button>
//                     <button onClick={() => goToPage(safePage - 1)} disabled={safePage === 1} className="h-7 px-2 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-semibold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition whitespace-nowrap">‹ Prev</button>
//                     {(() => {
//                         const pages: (number | "…")[] = [];
//                         if (totalPages <= 7) { for (let i = 1; i <= totalPages; i++) pages.push(i); }
//                         else {
//                             pages.push(1);
//                             if (safePage > 3) pages.push("…");
//                             for (let i = Math.max(2, safePage - 1); i <= Math.min(totalPages - 1, safePage + 1); i++) pages.push(i);
//                             if (safePage < totalPages - 2) pages.push("…");
//                             pages.push(totalPages);
//                         }
//                         return pages.map((p, idx) => p === "…"
//                             ? <span key={`e${idx}`} className="w-7 text-center text-slate-400">…</span>
//                             : <button key={p} onClick={() => goToPage(p as number)}
//                                 className={`w-7 h-7 flex items-center justify-center rounded text-[11px] font-semibold border transition ${safePage === p ? "bg-blue-600 border-blue-600 text-white shadow-sm" : "border-slate-200 bg-white text-slate-600 hover:bg-slate-100"}`}>{p}</button>
//                         );
//                     })()}
//                     <button onClick={() => goToPage(safePage + 1)} disabled={safePage === totalPages} className="h-7 px-2 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-semibold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition whitespace-nowrap">Next ›</button>
//                     <button onClick={() => goToPage(totalPages)} disabled={safePage === totalPages} className="w-7 h-7 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-bold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition">»</button>
//                 </div>
//                 <div className="flex items-center gap-3">
//                     <div className="flex items-center gap-1.5">
//                         <span className="text-slate-500 whitespace-nowrap">Rows/page</span>
//                         <select value={rowsPerPage} onChange={e => handleRowsChange(Number(e.target.value))} className="h-7 rounded border border-slate-300 bg-white text-slate-700 text-[11px] font-semibold px-1 focus:outline-none focus:ring-1 focus:ring-blue-500 cursor-pointer">
//                             {[5, 10, 25, 50, 100].map(n => <option key={n} value={n}>{n}</option>)}
//                         </select>
//                     </div>
//                     <div className="flex items-center gap-1.5">
//                         <span className="text-slate-500">Go to</span>
//                         <input type="number" min={1} max={totalPages} value={gotoInput} onChange={e => setGotoInput(e.target.value)} onKeyDown={e => e.key === "Enter" && handleGoto()} placeholder="#" className="w-12 h-7 rounded border border-slate-300 bg-white text-slate-700 text-[11px] text-center font-semibold px-1 focus:outline-none focus:ring-1 focus:ring-blue-500" />
//                         <button onClick={handleGoto} className="h-7 px-3 rounded bg-blue-600 hover:bg-blue-700 text-white text-[11px] font-bold transition">Go</button>
//                     </div>
//                 </div>
//             </div>
//         </div>
//     );
// }

// // ─── Main Page ────────────────────────────────────────────────────────────────

// export default function AIVoiceSummaryReportPage() {
//     const { data: rawDateGroups, loading, error, refetch } = useVoiceSummary();

//     const [view, setView] = useState<"table" | "charts">("table");
//     const [search, setSearch] = useState("");
//     const [dateFilter, setDateFilter] = useState("all");
//     const [company, setCompany] = useState("all");
//     const [source, setSource] = useState("all");
//     const [priority, setPriority] = useState("all");
//     const [customDate, setCustomDate] = useState({ start: "", end: "" });

//     const clearFilters = () => {
//         setSearch(""); setDateFilter("all"); setCompany("all");
//         setSource("all"); setPriority("all"); setCustomDate({ start: "", end: "" });
//     };

//     const dateFilteredGroups = useMemo(
//         () => filterByDateRange(rawDateGroups, dateFilter, customDate),
//         [rawDateGroups, dateFilter, customDate]
//     );

//     const allSources = useMemo(() => dateFilteredGroups.flatMap(dg =>
//         dg.sources.filter(s => {
//             const mc = company === "all" || s.company?.split(",").some(c => c.trim().toLowerCase().replace(/\s+/g, "_") === company);
//             const ms = source === "all" || s.source?.trim().toLowerCase().replace(/\s+/g, "_") === source;
//             const mp = priority === "all"
//                 || (priority === "high" && (s.sentHigh > 0 || s.qualHigh > 0))
//                 || (priority === "medium" && (s.sentMedium > 0 || s.qualMedium > 0))
//                 || (priority === "low" && (s.sentLow > 0 || s.qualLow > 0));
//             const mSearch = !search.trim() || s.company?.toLowerCase().includes(search.toLowerCase()) || s.source?.toLowerCase().includes(search.toLowerCase());
//             return mc && ms && mp && mSearch;
//         })
//     ), [dateFilteredGroups, company, source, priority, search]);

//     const kpi = useMemo(() => sumGroup(allSources), [allSources]);
//     const kpiQualRate = kpi.responses > 0 ? ((kpi.qualified / kpi.responses) * 100).toFixed(1) + "%" : "0%";

//     const companyAgg = useMemo(() => {
//         const map: Record<string, ReturnType<typeof sumGroup> & { name: string; color: string }> = {};
//         console.log("All Sources for Company Agg:", allSources);
//         allSources.forEach(s => {
//             if (!s.company) return;
//             // Split comma-joined companies and distribute stats equally
//             const companies = s.company.split(",").map(c => c.trim()).filter(Boolean);
//             const share = companies.length; // divide evenly among companies
//             companies.forEach(companyName => {
//                 if (!map[companyName]) map[companyName] = { ...ZERO_SUM, name: companyName, color: companyColor(companyName) };
//                 const m = map[companyName];
//                 (Object.keys(ZERO_SUM) as (keyof typeof ZERO_SUM)[]).forEach(k => {
//                     (m as any)[k] += Math.round(((s as any)[k] ?? 0) / share);
//                 });
//             });
//         });
//         console.log("Company Agg:", map);
//         return Object.values(map).sort((a, b) => (b.sent ?? 0) - (a.sent ?? 0));
//     }, [allSources]);

//     const sourceAgg = useMemo(() => {
//         const map: Record<string, ReturnType<typeof sumGroup> & { name: string; color: string }> = {};
//         allSources.forEach(s => {
//             if (!s.source) return;
//             if (!map[s.source]) map[s.source] = { ...ZERO_SUM, name: s.source, color: s.color };
//             const m = map[s.source];
//             (Object.keys(ZERO_SUM) as (keyof typeof ZERO_SUM)[]).forEach(k => { (m as any)[k] += (s as any)[k] ?? 0; });
//         });
//         return Object.values(map).sort((a, b) => b.sent - a.sent).slice(0, 8);
//     }, [allSources]);

//     const trendData = useMemo(() => {
//         const last14 = [...dateFilteredGroups].slice(0, 14).reverse();
//         return {
//             labels: last14.map(d => d.displayDate ?? d.date),
//             datasets: [
//                 { label: "Sent", data: last14.map(d => sumGroup(d.sources).sent), borderColor: "#6366f1", backgroundColor: "rgba(99,102,241,.08)", fill: true, tension: 0.4, pointBackgroundColor: "#6366f1", pointRadius: 4, borderWidth: 2 },
//                 { label: "Qualified", data: last14.map(d => sumGroup(d.sources).qualified), borderColor: "#10b981", backgroundColor: "rgba(16,185,129,.08)", fill: true, tension: 0.4, pointBackgroundColor: "#10b981", pointRadius: 4, borderWidth: 2 },
//             ],
//         };
//     }, [dateFilteredGroups]);

//     const barCompanyData = useMemo(() => ({
//         labels: companyAgg.map(c => c.name),
//         datasets: [
//             { label: "Sent", data: companyAgg.map(c => c.sent), backgroundColor: "#6366f1", borderRadius: 4 },
//             { label: "Qualified", data: companyAgg.map(c => c.qualified), backgroundColor: "#10b981", borderRadius: 4 },
//             { label: "Non-Qualified", data: companyAgg.map(c => c.dead), backgroundColor: "#f87171", borderRadius: 4 },
//         ],
//     }), [companyAgg]);

//     const barSourceData = useMemo(() => ({
//         labels: sourceAgg.map(s => s.name),
//         datasets: [
//             { label: "Sent", data: sourceAgg.map(s => s.sent), backgroundColor: "#6366f1", borderRadius: 4 },
//             { label: "Qualified", data: sourceAgg.map(s => s.qualified), backgroundColor: "#10b981", borderRadius: 4 },
//             { label: "Non-Qualified", data: sourceAgg.map(s => s.dead), backgroundColor: "#f87171", borderRadius: 4 },
//         ],
//     }), [sourceAgg]);

//     const doughnutPriority = useMemo(() => ({
//         labels: ["High", "Medium", "Low"],
//         datasets: [{ data: [kpi.sentHigh, kpi.sentMedium, kpi.sentLow], backgroundColor: ["#f87171", "#fbbf24", "#34d399"], borderWidth: 2, borderColor: "#fff", hoverOffset: 6 }],
//     }), [kpi]);

//     const barQualPct = useMemo(() => ({
//         labels: companyAgg.map(c => c.name),
//         datasets: [
//             { label: "Qualified %", data: companyAgg.map(c => c.responses > 0 ? +((c.qualified / c.responses) * 100).toFixed(1) : 0), backgroundColor: "#10b981", borderRadius: 4 },
//             { label: "Non-Qualified %", data: companyAgg.map(c => c.responses > 0 ? +((c.dead / c.responses) * 100).toFixed(1) : 0), backgroundColor: "#f87171", borderRadius: 4 },
//         ],
//     }), [companyAgg]);

//     const barSourceStacked = useMemo(() => ({
//         labels: sourceAgg.map(s => s.name),
//         datasets: [
//             { label: "Qualified", data: sourceAgg.map(s => s.qualified), backgroundColor: "#10b981", borderRadius: 0 },
//             { label: "Non-Qualified", data: sourceAgg.map(s => s.dead), backgroundColor: "#f87171", borderRadius: 0 },
//         ],
//     }), [sourceAgg]);

//     const doughnutStatus = useMemo(() => ({
//         labels: ["Qualified", "Non-Qualified"],
//         datasets: [{ data: [kpi.qualified, kpi.dead], backgroundColor: ["#10b981", "#f87171"], borderWidth: 2, borderColor: "#fff", hoverOffset: 6 }],
//     }), [kpi]);

//     const dynamicSources = useMemo(() => {
//         const names = new Set(rawDateGroups.flatMap(dg => dg.sources.map(s => s.source)));
//         return Array.from(names)
//             .filter(n => !!n && n.trim() !== "")
//             .sort()
//             .map(n => ({ value: n.trim().toLowerCase().replace(/\s+/g, "_"), label: n, raw: n }))
//             .filter(ds => ds.value !== "");
//     }, [rawDateGroups]);

//     const dynamicCompanies = useMemo(() => {
//         const names = new Set(rawDateGroups.flatMap(dg => dg.sources.flatMap(s => s.company?.split(",").map(c => c.trim()) ?? [])));
//         return Array.from(names).filter(n => !!n && n.trim() !== "").sort();
//     }, [rawDateGroups]);

//     if (loading) {
//         return (
//             <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50">
//                 <div className="flex flex-col items-center justify-center min-h-[60vh]">
//                     <Image src="/grouploader.gif" alt="Loading bookings" width={200} height={200} priority className="animate-pulse" />
//                     <p className="mt-4 text-base font-bold text-emerald-600 animate-pulse">Fetching latest AI Voice Call Summary...</p>
//                 </div>
//             </div>
//         );
//     }

//     return (
//         <div className="font-sans bg-[#f0f2f8] min-h-full text-slate-800">

//             {/* ── Banner ── */}
//             <div style={{ background: "linear-gradient(110deg,#1e1b4b 0%,#3730a3 40%,#4f46e5 75%,#6366f1 100%)", padding: "16px 20px", display: "flex", alignItems: "center", position: "relative", overflow: "hidden", flexWrap: "wrap", gap: 12 }}>
//                 <div style={{ position: "absolute", right: -60, top: -60, width: 220, height: 220, borderRadius: "50%", background: "rgba(255,255,255,.05)" }} />
//                 <div style={{ width: 40, height: 40, borderRadius: 10, background: "rgba(255,255,255,.15)", display: "flex", alignItems: "center", justifyContent: "center", marginRight: 12, flexShrink: 0, color: "#fff" }}>{icons.chart(22)}</div>
//                 <div style={{ flex: 1, minWidth: 180 }}>
//                     <div style={{ fontSize: 18, fontWeight: 800, color: "#fff", letterSpacing: "-.3px", lineHeight: 1.2 }}>AI Voice Lead Qualification — Summary Report</div>
//                     <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)", marginTop: 3 }}>KServe AI · Company-wise Performance Analysis &amp; Lead Qualification Insights</div>
//                 </div>
//                 <div className="hidden sm:flex" style={{ alignItems: "center", gap: 10, position: "relative", zIndex: 1, flexWrap: "wrap" }}>
//                     {loading
//                         ? <div className="flex items-center gap-2 text-white/60 text-xs"><Loader2 className="w-4 h-4 animate-spin" />Loading...</div>
//                         : [
//                             { val: String(kpi.sent), lbl: "Total Leads", color: "#fff" },
//                             { val: String(kpi.qualified), lbl: "Qualified", color: "#6ee7b7" },
//                             { val: String(kpi.dead), lbl: "Non-Qualified", color: "#fca5a5" },
//                             { val: kpiQualRate, lbl: "Qual. Rate", color: "#fde68a" },
//                         ].map(s => (
//                             <div key={s.lbl} style={{ textAlign: "center", background: "rgba(255,255,255,.1)", border: "1px solid rgba(255,255,255,.15)", borderRadius: 8, padding: "7px 12px", minWidth: 72 }}>
//                                 <div style={{ fontSize: 20, fontWeight: 800, color: s.color, lineHeight: 1 }}>{s.val}</div>
//                                 <div style={{ fontSize: 9, color: "rgba(255,255,255,.55)", textTransform: "uppercase", letterSpacing: ".7px", fontWeight: 600, marginTop: 3 }}>{s.lbl}</div>
//                             </div>
//                         ))
//                     }
//                 </div>
//                 <div className="flex sm:hidden w-full gap-2 mt-1" style={{ position: "relative", zIndex: 1 }}>
//                     {[
//                         { val: String(kpi.sent), lbl: "Leads", color: "#fff" },
//                         { val: String(kpi.qualified), lbl: "Qual.", color: "#6ee7b7" },
//                         { val: String(kpi.dead), lbl: "Dead", color: "#fca5a5" },
//                         { val: kpiQualRate, lbl: "Rate", color: "#fde68a" },
//                     ].map(s => (
//                         <div key={s.lbl} style={{ flex: 1, textAlign: "center", background: "rgba(255,255,255,.1)", border: "1px solid rgba(255,255,255,.15)", borderRadius: 7, padding: "6px 4px" }}>
//                             <div style={{ fontSize: 16, fontWeight: 800, color: s.color, lineHeight: 1 }}>{s.val}</div>
//                             <div style={{ fontSize: 8.5, color: "rgba(255,255,255,.55)", textTransform: "uppercase", letterSpacing: ".5px", fontWeight: 600, marginTop: 2 }}>{s.lbl}</div>
//                         </div>
//                     ))}
//                 </div>
//             </div>

//             {/* ── Filters ── */}
//             <div className="mt-3 mx-3 sm:mx-5">
//                 <div className="rounded-xl border border-slate-200 bg-white shadow-md">
//                     <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 px-5 py-4 bg-gradient-to-r from-blue-100 via-white to-indigo-100 border-b border-slate-200 rounded-t-xl">
//                         <div className="flex items-center gap-3">
//                             <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-600 via-indigo-600 to-blue-700 flex items-center justify-center shadow-md border border-blue-700/30">
//                                 <Search className="w-5 h-5 text-white" />
//                             </div>
//                             <div>
//                                 <h3 className="text-sm font-semibold text-slate-900">Filters</h3>
//                                 <p className="text-xs text-slate-500">Refine results by date, company, source and priority</p>
//                             </div>
//                         </div>
//                         <Button variant="outline" size="sm" onClick={clearFilters} className="bg-white border-slate-300 text-slate-700 font-medium hover:bg-blue-50">Clear Filters</Button>
//                     </div>
//                     <div className="px-5 py-4">
//                         <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4">
//                             <div className="flex flex-col gap-1.5 lg:col-span-2">
//                                 <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Search</label>
//                                 <Input placeholder="Search company or source..." value={search} onChange={e => setSearch(e.target.value)} className="h-10 w-full rounded-md border-gray-300" />
//                             </div>
//                             <div className="flex flex-col gap-1.5">
//                                 <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Date Range</label>
//                                 <Select value={dateFilter} onValueChange={setDateFilter}>
//                                     <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="Select range" /></SelectTrigger>
//                                     <SelectContent>
//                                         {[["all", "All"], ["today", "Today"], ["yesterday", "Yesterday"], ["this_week", "This Week"], ["last_week", "Last Week"], ["this_month", "This Month"], ["last_month", "Last Month"], ["this_year", "This Year"], ["last_year", "Last Year"], ["custom", "Custom"]].map(([v, l]) => (
//                                             <SelectItem key={v} value={v}>{l}</SelectItem>
//                                         ))}
//                                     </SelectContent>
//                                 </Select>
//                             </div>
//                             <div className="flex flex-col gap-1.5">
//                                 <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Company</label>
//                                 <Select value={company} onValueChange={setCompany}>
//                                     <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="All Companies" /></SelectTrigger>
//                                     <SelectContent>
//                                         <SelectItem value="all">All Companies</SelectItem>
//                                         {dynamicCompanies.map(c => {
//                                             const val = c.trim().toLowerCase().replace(/\s+/g, "_");
//                                             if (!val) return null;
//                                             return <SelectItem key={c} value={val}>{c}</SelectItem>;
//                                         })}
//                                     </SelectContent>
//                                 </Select>
//                             </div>
//                             <div className="flex flex-col gap-1.5">
//                                 <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Data Source</label>
//                                 <Select value={source} onValueChange={setSource}>
//                                     <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="All Sources" /></SelectTrigger>
//                                     <SelectContent>
//                                         <SelectItem value="all">All Sources</SelectItem>
//                                         {dynamicSources.map(ds => (
//                                             <SelectItem key={ds.value} value={ds.value}>{ds.label}</SelectItem>
//                                         ))}
//                                     </SelectContent>
//                                 </Select>
//                             </div>
//                             <div className="flex flex-col gap-1.5">
//                                 <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Priority</label>
//                                 <Select value={priority} onValueChange={setPriority}>
//                                     <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="All" /></SelectTrigger>
//                                     <SelectContent>
//                                         <SelectItem value="all">All</SelectItem>
//                                         <SelectItem value="high">High</SelectItem>
//                                         <SelectItem value="medium">Medium</SelectItem>
//                                         <SelectItem value="low">Low</SelectItem>
//                                     </SelectContent>
//                                 </Select>
//                             </div>
//                         </div>
//                         {dateFilter === "custom" && (
//                             <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4 pt-4 border-t border-slate-200">
//                                 <div className="flex flex-col gap-1.5">
//                                     <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Start Date</label>
//                                     <Input type="date" value={customDate.start} onChange={e => setCustomDate({ ...customDate, start: e.target.value })} className="h-10 w-full rounded-md border-gray-300" />
//                                 </div>
//                                 <div className="flex flex-col gap-1.5">
//                                     <label className="text-xs font-medium uppercase tracking-wide text-slate-500">End Date</label>
//                                     <Input type="date" value={customDate.end} onChange={e => setCustomDate({ ...customDate, end: e.target.value })} className="h-10 w-full rounded-md border-gray-300" />
//                                 </div>
//                             </div>
//                         )}
//                     </div>
//                 </div>
//             </div>

//             {/* ── KPI Cards ── */}
//             <div className="mx-3 sm:mx-5 mt-3">
//                 <div className="bg-white border-2 border-slate-200 rounded-xl shadow-xl">
//                     <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 px-5 py-3 bg-gradient-to-r from-slate-100 via-white to-blue-100 border-b border-slate-200 rounded-t-xl">
//                         <div className="flex items-center gap-3">
//                             <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-700 flex items-center justify-center shadow-md border border-blue-500/40">
//                                 <BarChart3 className="h-5 w-5 text-white" />
//                             </div>
//                             <div>
//                                 <h3 className="text-sm font-semibold text-slate-900">Key Performance Indicators</h3>
//                                 <p className="text-[11px] text-slate-500">Overview of lead metrics &amp; performance</p>
//                             </div>
//                         </div>
//                     </div>
//                     <div className="p-5">
//                         {loading ? (
//                             <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 animate-pulse">
//                                 {[...Array(4)].map((_, i) => <div key={i} className="h-28 bg-slate-100 rounded-lg" />)}
//                             </div>
//                         ) : (
//                             <div className="bg-blue-50/60 border border-blue-200 rounded-xl p-4 space-y-4">
//                                 <h4 className="text-sm font-bold text-slate-700 uppercase tracking-wide">AI Voice Metrics</h4>
//                                 <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">
//                                     {[
//                                         // Sent      % = sent / sent = 100%
//                                         { label: "Total Leads Sent", val: kpi.sent, pctOf: kpi.sent, bg: "bg-blue-50/70", border: "border-blue-300", lc: "text-blue-700" },
//                                         // Responses % = responses / sent (avg calls per lead)
//                                         { label: "Total Responses Received", val: kpi.responses, pctOf: kpi.sent, bg: "bg-slate-50/70", border: "border-slate-300", lc: "text-slate-700" },
//                                         // Qualified % = qualified / responses
//                                         { label: "Total Qualified Leads", val: kpi.qualified, pctOf: kpi.responses, bg: "bg-emerald-50/70", border: "border-emerald-300", lc: "text-emerald-700" },
//                                         // Dead      % = dead / responses
//                                         { label: "Dead / Non-Qualified", val: kpi.dead, pctOf: kpi.responses, bg: "bg-red-50/70", border: "border-red-300", lc: "text-red-700" },
//                                     ].map((card, ci) => (
//                                         <div key={card.label} className={`${card.bg} border-2 ${card.border} rounded-lg p-3 shadow-sm hover:shadow-md transition relative`}>
//                                             {ci === 1 && (card.pctOf ?? 0) > 0 && (
//                                                 <div className="absolute top-2 right-2 flex flex-col items-end">
//                                                     <div className="text-[10px] font-bold text-red-600 bg-red-50 px-1.5 py-0.5 rounded border border-red-200 shadow-sm">
//                                                         -{(100 - ((card.val ?? 0) / (card.pctOf ?? 1) * 100)).toFixed(1)}%
//                                                     </div>
//                                                     <span className="text-[8px] text-red-400 font-medium tracking-tight mt-0.5 whitespace-nowrap">REMAINING</span>
//                                                 </div>
//                                             )}
//                                             <p className={`text-[10px] font-semibold uppercase tracking-wide ${card.lc} leading-tight mb-2`}>{card.label}</p>
//                                             <p className="text-2xl font-bold text-slate-900 leading-none mb-2">
//                                                 {card.val ?? 0}
//                                                 {(card.pctOf ?? 0) > 0 && (
//                                                     <span className="text-sm font-semibold text-slate-800 ml-2">({(((card.val ?? 0) / (card.pctOf ?? 1)) * 100).toFixed(1)}%)</span>
//                                                 )}
//                                             </p>
//                                             <div className="flex flex-col gap-1 text-[10px]">
//                                                 {companyAgg.map(c => {
//                                                     const vals = [c.sent, c.responses, c.qualified, c.dead];
//                                                     const v = vals[ci] ?? 0;
//                                                     // ci=0 → sent%  = c.sent / kpi.sent
//                                                     // ci=1 → resp%  = c.responses / kpi.responses
//                                                     // ci=2 → qual%  = c.qualified / c.responses
//                                                     // ci=3 → dead%  = c.dead / c.responses
//                                                     const denomForPct =
//                                                         ci === 0 ? kpi.sent :
//                                                             ci === 1 ? kpi.responses :
//                                                                 (c.responses ?? 0); // ci=2 and ci=3
//                                                     return (
//                                                         <div key={c.name} className="flex items-center justify-between">
//                                                             <span className="font-medium" style={{ color: c.color }}>{c.name}:</span>
//                                                             <span className="font-semibold" style={{ color: c.color }}>
//                                                                 {(denomForPct ?? 0) > 0
//                                                                     ? `${v} (${((v / (denomForPct ?? 1)) * 100).toFixed(1)}%)`
//                                                                     : String(v)}
//                                                             </span>
//                                                         </div>
//                                                     );
//                                                 })}
//                                             </div>
//                                         </div>
//                                     ))}
//                                 </div>
//                             </div>
//                         )}
//                     </div>
//                 </div>
//             </div>

//             {/* ── Source Breakdown ── */}
//             <div className="mx-3 sm:mx-5 mt-3 mb-5">
//                 <div className="bg-white border border-slate-200 rounded-xl shadow-md overflow-hidden">
//                     <div className="flex flex-wrap items-center justify-between gap-3 px-4 sm:px-5 py-4 border-b border-slate-100">
//                         <div className="flex items-center gap-3">
//                             <div className="w-10 h-10 rounded-xl bg-orange-500 flex items-center justify-center shadow-md flex-shrink-0">{icons.dashboard(18)}</div>
//                             <div>
//                                 <h3 className="text-[14px] font-bold text-slate-900 leading-tight">Source-wise Breakdown</h3>
//                                 <p className="text-[11px] text-slate-400 mt-0.5">Date-wise Call performance — High · Medium · Low quality across all metrics</p>
//                             </div>
//                         </div>
//                         <div className="flex items-center gap-3">
//                             {loading && <div className="flex items-center gap-1.5 text-xs text-slate-500"><Loader2 className="w-3.5 h-3.5 animate-spin text-blue-500" /><span>Loading...</span></div>}
//                             <div className="flex items-center rounded-lg overflow-hidden border border-slate-200 shadow-sm">
//                                 {(["table", "charts"] as const).map(v => (
//                                     <button key={v} onClick={() => setView(v)}
//                                         className="flex items-center gap-2 px-4 py-2 text-xs font-semibold transition-all"
//                                         style={{ background: view === v ? "#4f46e5" : "#fff", color: view === v ? "#fff" : "#64748b", borderRight: v === "table" ? "1px solid #e2e8f0" : "none", fontFamily: "inherit", cursor: "pointer" }}>
//                                         {v === "table" ? icons.table(13) : icons.chart(13)}
//                                         {v === "table" ? "Table" : "Charts"}
//                                     </button>
//                                 ))}
//                             </div>
//                         </div>
//                     </div>

//                     {view === "table" && (
//                         loading ? <TableSkeleton />
//                             : error ? <TableError message={error} onRetry={refetch} />
//                                 : <CompanyBreakdownTable company={company} sourceFilter={source} dateGroups={dateFilteredGroups} search={search} priority={priority} />
//                     )}

//                     {view === "charts" && !loading && (
//                         <div className="p-4 space-y-3">
//                             <div className="grid grid-cols-2 gap-3">
//                                 <ChartCard title="Company-wise Lead Performance" subtitle="Sent vs Qualified vs Non-Qualified per company" iconBg="#eef2ff" iconColor="#4f46e5" icon={icons.dashboard()} legend={[{ color: "#6366f1", label: "Sent" }, { color: "#10b981", label: "Qualified" }, { color: "#f87171", label: "Non-Qualified" }]}>
//                                     <div style={{ position: "relative", height: 220 }}><Bar data={barCompanyData} options={commonBarOpts} /></div>
//                                 </ChartCard>
//                                 <ChartCard title="Source-wise Lead Performance" subtitle="Sent vs Qualified vs Non-Qualified per source" iconBg="#fef3c7" iconColor="#d97706" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>} legend={[{ color: "#6366f1", label: "Sent" }, { color: "#10b981", label: "Qualified" }, { color: "#f87171", label: "Non-Qualified" }]}>
//                                     <div style={{ position: "relative", height: 220 }}><Bar data={barSourceData} options={commonBarOpts} /></div>
//                                 </ChartCard>
//                             </div>
//                             <div className="grid gap-3" style={{ gridTemplateColumns: "1fr 1.6fr 1.4fr" }}>
//                                 <ChartCard title="Priority Distribution" subtitle="All leads by priority level" iconBg="#fee2e2" iconColor="#dc2626" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><circle cx="12" cy="12" r="10" strokeWidth="2" /><path d="M12 8v4l3 3" strokeWidth="2" strokeLinecap="round" /></svg>}>
//                                     <div style={{ height: 180, display: "flex", alignItems: "center", justifyContent: "center" }}><div style={{ maxWidth: 160, width: "100%" }}><Doughnut data={doughnutPriority} options={{ responsive: true, maintainAspectRatio: true, cutout: "68%", plugins: { legend: { display: false }, tooltip: { callbacks: { label: (ctx: any) => `${ctx.label}: ${ctx.parsed} leads` } } } }} /></div></div>
//                                     <ChartLegend items={[{ color: "#f87171", label: `High (${fmtPct(kpi.sentHigh, kpi.sent)}%)`, round: true }, { color: "#fbbf24", label: `Medium (${fmtPct(kpi.sentMedium, kpi.sent)}%)`, round: true }, { color: "#34d399", label: `Low (${fmtPct(kpi.sentLow, kpi.sent)}%)`, round: true }]} />
//                                 </ChartCard>
//                                 <ChartCard title="Qualification % by Company" subtitle="Qualified vs Non-Qualified % of responses per company" iconBg="#d1fae5" iconColor="#059669" icon={icons.check()} legend={[{ color: "#10b981", label: "Qualified %" }, { color: "#f87171", label: "Non-Qualified %" }]}>
//                                     <div style={{ position: "relative", height: 220 }}><Bar data={barQualPct} options={{ ...commonBarOpts, indexAxis: "y" as const, scales: { x: { stacked: true, max: 100, ticks: { callback: (v: any) => v + "%", font: chartFont, color: "#64748b" }, grid: { color: "#f1f5f9" }, border: { display: false } }, y: { stacked: true, ticks: { font: chartFont, color: "#1e293b" }, grid: { display: false }, border: { display: false } } }, barPercentage: 0.6, categoryPercentage: 0.7 }} /></div>
//                                 </ChartCard>
//                                 <ChartCard title="Daily Qualification Trend" subtitle="Leads sent & qualified over time" iconBg="#ede9fe" iconColor="#7c3aed" icon={icons.trend()} legend={[{ color: "#6366f1", label: "Sent", round: true }, { color: "#10b981", label: "Qualified", round: true }]}>
//                                     <div style={{ position: "relative", height: 220 }}><Line data={trendData} options={commonBarOpts} /></div>
//                                 </ChartCard>
//                             </div>
//                             <div className="grid gap-3" style={{ gridTemplateColumns: "1.5fr 1fr" }}>
//                                 <ChartCard title="Qualification % by Source (Stacked)" subtitle="Qualified vs Non-Qualified split across sources" iconBg="#dbeafe" iconColor="#2563eb" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" strokeWidth="2" /><path d="M3 9h18M9 21V9" strokeWidth="2" strokeLinecap="round" /></svg>} legend={[{ color: "#10b981", label: "Qualified" }, { color: "#f87171", label: "Non-Qualified" }]}>
//                                     <div style={{ position: "relative", height: 260 }}><Bar data={barSourceStacked} options={{ ...commonBarOpts, scales: { x: { stacked: true, ticks: { font: chartFont, color: "#64748b" }, grid: { display: false }, border: { display: false } }, y: { stacked: true, ticks: { font: chartFont, color: "#64748b" }, grid: { color: "#f1f5f9" }, border: { display: false } } }, barPercentage: 0.6, categoryPercentage: 0.7 }} /></div>
//                                 </ChartCard>
//                                 <ChartCard title="Overall Lead Status Split" subtitle={`${kpi.qualified + kpi.dead} total responses — qualification outcome`} iconBg="#fce7f3" iconColor="#be185d" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><circle cx="12" cy="12" r="10" strokeWidth="2" /><path d="M12 8v4l3 3" strokeWidth="2" strokeLinecap="round" /></svg>}>
//                                     <div style={{ height: 190, display: "flex", alignItems: "center", justifyContent: "center" }}><div style={{ maxWidth: 180, width: "100%" }}><Doughnut data={doughnutStatus} options={{ responsive: true, maintainAspectRatio: true, cutout: "65%", plugins: { legend: { display: false }, tooltip: { callbacks: { label: (ctx: any) => `${ctx.label}: ${ctx.parsed}` } } } }} /></div></div>
//                                     <ChartLegend items={[
//                                         { color: "#10b981", label: `Qualified — ${kpi.qualified} (${fmtPct(kpi.qualified, kpi.responses)}%)`, round: true },
//                                         { color: "#f87171", label: `Non-Qualified — ${kpi.dead} (${fmtPct(kpi.dead, kpi.responses)}%)`, round: true },
//                                     ]} />
//                                 </ChartCard>
//                             </div>
//                         </div>
//                     )}
//                 </div>
//             </div>

//         </div>
//     );
// }



"use client";

import React, { useState, useEffect, useMemo } from "react";
import { useVoiceSummary, DateGroup, SourceDayRow } from "@/hooks/voicecall/useVoiceSummary";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import Image from "next/image";
// import { useSentLeads } from "@/hooks/useSentLeads";
// import { useReceivedLeads } from "@/hooks/useReceivedLeads";
import {
    Search, BarChart3, ChevronDown, ChevronRight, Calendar,
    ArrowUpDown, ArrowUp, ArrowDown, Loader2, AlertCircle,
} from "lucide-react";
import {
    Chart as ChartJS, CategoryScale, LinearScale, BarElement, LineElement,
    PointElement, ArcElement, Title, Tooltip, Legend, Filler,
} from "chart.js";
import { Bar, Line, Doughnut } from "react-chartjs-2";

ChartJS.register(CategoryScale, LinearScale, BarElement, LineElement, PointElement, ArcElement, Title, Tooltip, Legend, Filler);

// ─── Company color map ────────────────────────────────────────────────────────

const COMPANY_COLORS: Record<string, string> = {
    KTAHV: "#059669", "VILLA RAAG": "#d97706", KAPPL: "#be185d", KAC: "#6366f1",
};
const CC_FALLBACK = ["#2563eb", "#7c3aed", "#0891b2", "#b45309", "#4338ca"];

function companyColor(name: string): string {
    if (COMPANY_COLORS[name]) return COMPANY_COLORS[name];
    let hash = 0;
    for (let i = 0; i < name.length; i++) hash = name.charCodeAt(i) + ((hash << 5) - hash);
    COMPANY_COLORS[name] = CC_FALLBACK[Math.abs(hash) % CC_FALLBACK.length];
    return COMPANY_COLORS[name];
}

function parseCRMDate(str: string): number {
    if (!str || str === "—") return 0;
    // Format: "DD/MM/YYYY HH:mm" or "YYYY-MM-DD"
    if (str.includes("-") && !str.includes("/")) return new Date(str).getTime();
    const [datePart, timePart = "00:00"] = str.split(" ");
    const parts = datePart.split("/");
    if (parts.length !== 3) return new Date(str).getTime();
    const [dd, mm, yyyy] = parts;
    return new Date(`${yyyy}-${mm}-${dd}T${timePart}`).getTime();
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

const fmtPct = (n: number, d: number) => d > 0 ? ((n / d) * 100).toFixed(1) : "0.0";
const normalize = (val?: string) => val?.trim().toLowerCase().replace(/\s+/g, "_") || "";

const formatDelay = (seconds: number) => {
    if (seconds <= 0) return "00:00:00";
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = Math.floor(seconds % 60);
    return `${String(h).padStart(2, '0')}:${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
};

const delayColor = (seconds: number) => {
    const mins = seconds / 60;
    if (mins <= 30) return { bg: "bg-green-50", border: "border-green-200", text: "text-green-700" };
    if (mins <= 60) return { bg: "bg-orange-50", border: "border-orange-200", text: "text-orange-700" };
    return { bg: "bg-red-50", border: "border-red-200", text: "text-red-700" };
};

const ZERO_SUM = {
    sent: 0, sentHigh: 0, sentMedium: 0, sentLow: 0,
    responses: 0, respHigh: 0, respMedium: 0, respLow: 0,
    qualified: 0, qualHigh: 0, qualMedium: 0, qualLow: 0,
    dead: 0, deadHigh: 0, deadMedium: 0, deadLow: 0,
    pending: 0, pendingHigh: 0, pendingMedium: 0, pendingLow: 0,
    tatResponses: 0, tatRespHigh: 0, tatRespMedium: 0, tatRespLow: 0,
    tatQualified: 0, tatQualHigh: 0, tatQualMedium: 0, tatQualLow: 0,
    tatDead: 0, tatDeadHigh: 0, tatDeadMedium: 0, tatDeadLow: 0,
    tatPending: 0, tatPendingHigh: 0, tatPendingMedium: 0, tatPendingLow: 0,
};

function sumGroup(rows: Partial<SourceDayRow>[] = []): typeof ZERO_SUM {
    const a = { ...ZERO_SUM };
    for (let i = 0; i < rows.length; i++) {
        const c = rows[i];
        if (!c) continue;
        const q = (c.qualified ?? 0);
        const d = (c.dead ?? 0);
        const r = q + d; // Responses = Qualified + Dead

        const qH = (c.qualHigh ?? 0);
        const dH = (c.deadHigh ?? 0);
        const rH = qH + dH;

        const qM = (c.qualMedium ?? 0);
        const dM = (c.deadMedium ?? 0);
        const rM = qM + dM;

        const qL = (c.qualLow ?? 0);
        const dL = (c.deadLow ?? 0);
        const rL = qL + dL;

        const tq = (c.tatQualified ?? 0);
        const td = (c.tatDead ?? 0);
        const tr = tq + td;

        const tqH = (c.tatQualHigh ?? 0);
        const tdH = (c.tatDeadHigh ?? 0);
        const trH = tqH + tdH;

        const tqM = (c.tatQualMedium ?? 0);
        const tdM = (c.tatDeadMedium ?? 0);
        const trM = tqM + tdM;

        const tqL = (c.tatQualLow ?? 0);
        const tdL = (c.tatDeadLow ?? 0);
        const trL = tqL + tdL;

        a.sent += (c.sent ?? 0);
        a.sentHigh += (c.sentHigh ?? 0);
        a.sentMedium += (c.sentMedium ?? 0);
        a.sentLow += (c.sentLow ?? 0);
        a.responses += r;
        a.respHigh += rH;
        a.respMedium += rM;
        a.respLow += rL;
        a.qualified += q;
        a.qualHigh += qH;
        a.qualMedium += qM;
        a.qualLow += qL;
        a.dead += d;
        a.deadHigh += dH;
        a.deadMedium += dM;
        a.deadLow += dL;
        a.pending += (c.pending ?? 0);
        a.pendingHigh += (c.pendingHigh ?? 0);
        a.pendingMedium += (c.pendingMedium ?? 0);
        a.pendingLow += (c.pendingLow ?? 0);
        a.tatResponses += tr;
        a.tatRespHigh += trH;
        a.tatRespMedium += trM;
        a.tatRespLow += trL;
        a.tatQualified += tq;
        a.tatQualHigh += tqH;
        a.tatQualMedium += tqM;
        a.tatQualLow += tqL;
        a.tatDead += td;
        a.tatDeadHigh += tdH;
        a.tatDeadMedium += tdM;
        a.tatDeadLow += tdL;
        a.tatPending += (c.tatPending ?? 0);
        a.tatPendingHigh += (c.tatPendingHigh ?? 0);
        a.tatPendingMedium += (c.tatPendingMedium ?? 0);
        a.tatPendingLow += (c.tatPendingLow ?? 0);
    }
    return a;
}


function filterByDateRange(groups: DateGroup[], range: string, custom: { start: string; end: string }): DateGroup[] {
    if (range === "all") return groups;
    // const now = new Date();
    // const today = now.toISOString().slice(0, 10);

    const pad = (n: number) => String(n).padStart(2, "0");
    const fmt = (dt: Date) => `${dt.getFullYear()}-${pad(dt.getMonth() + 1)}-${pad(dt.getDate())}`;

    const now = new Date();
    const today = fmt(now);
    let from = "", to = today;

    if (range === "today") {
        from = today;

    } else if (range === "yesterday") {
        const d = new Date(now);
        d.setDate(d.getDate() - 1);
        from = to = fmt(d);

    } else if (range === "this_week") {
        const d = new Date(now);
        d.setDate(d.getDate() - d.getDay());
        from = fmt(d);

    } else if (range === "last_week") {
        const end = new Date(now);
        end.setDate(end.getDate() - end.getDay() - 1);
        const start = new Date(end);
        start.setDate(start.getDate() - 6);
        from = fmt(start);
        to = fmt(end);

    } else if (range === "this_month") {
        from = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-01`;

    } else if (range === "last_month") {
        const d = new Date(now.getFullYear(), now.getMonth() - 1, 1);
        const e = new Date(now.getFullYear(), now.getMonth(), 0);
        from = fmt(d);
        to = fmt(e);

    } else if (range === "this_year") {
        from = `${now.getFullYear()}-01-01`;

    } else if (range === "last_year") {
        from = `${now.getFullYear() - 1}-01-01`;
        to = `${now.getFullYear() - 1}-12-31`;

    } else if (range === "custom") {
        from = custom.start;
        to = custom.end || today;
    }
    // console.log(`Filtering groups from ${from} to ${to}`);
    return groups.filter(g => g.date >= from && g.date <= to);
}

// ─── Icons ────────────────────────────────────────────────────────────────────

const S = 12;
const icons = {
    chart: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
    table: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" strokeWidth="2" /><path d="M3 9h18M3 15h18M9 3v18" strokeWidth="2" strokeLinecap="round" /></svg>,
    trend: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><polyline points="22 12 18 12 15 21 9 3 6 12 2 12" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
    dashboard: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><rect x="3" y="3" width="7" height="7" rx="1" strokeWidth="2" /><rect x="14" y="3" width="7" height="7" rx="1" strokeWidth="2" /><rect x="3" y="14" width="7" height="7" rx="1" strokeWidth="2" /><rect x="14" y="14" width="7" height="7" rx="1" strokeWidth="2" /></svg>,
    check: (sz = S) => <svg width={sz} height={sz} fill="none" viewBox="0 0 24 24" stroke="currentColor"><polyline points="20 6 9 17 4 12" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>,
};

// ─── Chart helpers ────────────────────────────────────────────────────────────

const chartFont = { family: "'Inter', sans-serif" };
const commonBarOpts: any = {
    responsive: true, maintainAspectRatio: false,
    plugins: { legend: { display: false }, tooltip: { titleFont: { ...chartFont, size: 11 }, bodyFont: { ...chartFont, size: 11 } } },
    scales: {
        x: { ticks: { font: chartFont, color: "#64748b" }, grid: { display: false }, border: { display: false } },
        y: { ticks: { font: chartFont, color: "#64748b" }, grid: { color: "#f1f5f9" }, border: { display: false } },
    },
    barPercentage: 0.75, categoryPercentage: 0.7,
};

function ChartLegend({ items }: { items: { color: string; label: string; round?: boolean }[] }) {
    return (
        <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginTop: 10 }}>
            {items.map(l => (
                <div key={l.label} style={{ display: "flex", alignItems: "center", gap: 5, fontSize: 11, color: "#64748b" }}>
                    <div style={{ width: 8, height: 8, borderRadius: l.round ? "50%" : 2, background: l.color, flexShrink: 0 }} />{l.label}
                </div>
            ))}
        </div>
    );
}

function ChartCard({ title, subtitle, iconBg, iconColor, icon, legend, children }: {
    title: string; subtitle: string; iconBg: string; iconColor: string; icon: React.ReactNode;
    legend?: { color: string; label: string; round?: boolean }[]; children: React.ReactNode;
}) {
    return (
        <div className="bg-white border border-slate-200 rounded-xl shadow-sm overflow-hidden">
            <div className="flex items-start gap-3 px-4 py-3 border-b border-slate-100">
                <div style={{ width: 24, height: 24, borderRadius: 6, background: iconBg, color: iconColor, display: "flex", alignItems: "center", justifyContent: "center", flexShrink: 0 }}>{icon}</div>
                <div>
                    <div className="text-[12.5px] font-bold text-slate-800">{title}</div>
                    <div className="text-[11px] text-slate-400 mt-0.5">{subtitle}</div>
                </div>
            </div>
            <div className="p-4">{children}{legend && <ChartLegend items={legend} />}</div>
        </div>
    );
}

// ─── Table constants ──────────────────────────────────────────────────────────

const HDR_BG = "#1e3a5f";
const HDR_BG2 = "#162d4a";
const CELL = {
    H: { bg: "#f0fdf4", count: "#166534", pct: "#15803d" },
    M: { bg: "#fefce8", count: "#92400e", pct: "#a16207" },
    L: { bg: "#fef2f2", count: "#991b1b", pct: "#b91c1c" },
};

// ─── % Formula (Table columns) ────────────────────────────────────────────────
//
//   Sent      → sent      / grand.sent       (is date/source ka share of total sent)
//   Responses → responses / grand.sent       (conversion from sent — finalized outcomes)
//   Qualified → qualified / responses        (call outcome — % of finalized that qualified)
//   Dead      → dead      / responses        (call outcome — % of finalized that went dead)
//   Pending   → pending   / sent             (status outcome — % of total sent still pending)
//
// Source sub-rows same formula:
//   Sent      → s.sent      / t.sent         (source share of day's sent)
//   Responses → s.responses / t.sent         (source finalized conversion)
//   Qualified → s.qualified / s.responses
//   Dead      → s.dead      / s.responses
//   Pending   → s.pending   / s.sent

const GROUPS = [
    {
        key: "sent", label: "Leads Sent",
        hdrBg: "#ebfffd", hdrText: "#013b37",
        getTotal: (t: ReturnType<typeof sumGroup>) => t.sent,
        getH: (t: ReturnType<typeof sumGroup>) => t.sentHigh,
        getM: (t: ReturnType<typeof sumGroup>) => t.sentMedium,
        getL: (t: ReturnType<typeof sumGroup>) => t.sentLow,
        // sent / grand.sent
        getDenominator: (_t: ReturnType<typeof sumGroup>, grand: ReturnType<typeof sumGroup>) => grand.sent,
    },
    {
        key: "resp", label: "Responses Received",
        hdrBg: "#fef3c7", hdrText: "#92400e",
        getTotal: (t: ReturnType<typeof sumGroup>) => t.responses,
        getH: (t: ReturnType<typeof sumGroup>) => t.respHigh,
        getM: (t: ReturnType<typeof sumGroup>) => t.respMedium,
        getL: (t: ReturnType<typeof sumGroup>) => t.respLow,
        // responses / sent
        getDenominator: (t: ReturnType<typeof sumGroup>, _grand: ReturnType<typeof sumGroup>) => t.sent,
        showTAT: true,
        getTAT: (t: ReturnType<typeof sumGroup>) => t.responses > 0 ? t.tatResponses / t.responses : 0,
        getTATH: (t: ReturnType<typeof sumGroup>) => t.respHigh > 0 ? t.tatRespHigh / t.respHigh : 0,
        getTATM: (t: ReturnType<typeof sumGroup>) => t.respMedium > 0 ? t.tatRespMedium / t.respMedium : 0,
        getTATL: (t: ReturnType<typeof sumGroup>) => t.respLow > 0 ? t.tatRespLow / t.respLow : 0,
    },
    {
        key: "qual", label: "Qualified",
        hdrBg: "#dcfce7", hdrText: "#166534",
        getTotal: (t: ReturnType<typeof sumGroup>) => t.qualified,
        getH: (t: ReturnType<typeof sumGroup>) => t.qualHigh,
        getM: (t: ReturnType<typeof sumGroup>) => t.qualMedium,
        getL: (t: ReturnType<typeof sumGroup>) => t.qualLow,
        // qualified / responses
        getDenominator: (t: ReturnType<typeof sumGroup>, _grand: ReturnType<typeof sumGroup>) => t.responses,
        showTAT: true,
        getTAT: (t: ReturnType<typeof sumGroup>) => t.qualified > 0 ? t.tatQualified / t.qualified : 0,
        getTATH: (t: ReturnType<typeof sumGroup>) => t.qualHigh > 0 ? t.tatQualHigh / t.qualHigh : 0,
        getTATM: (t: ReturnType<typeof sumGroup>) => t.qualMedium > 0 ? t.tatQualMedium / t.qualMedium : 0,
        getTATL: (t: ReturnType<typeof sumGroup>) => t.qualLow > 0 ? t.tatQualLow / t.qualLow : 0,
    },
    {
        key: "dead", label: "Dead / Non-Qual",
        hdrBg: "#ffe4e6", hdrText: "#9f1239",
        getTotal: (t: ReturnType<typeof sumGroup>) => t.dead,
        getH: (t: ReturnType<typeof sumGroup>) => t.deadHigh,
        getM: (t: ReturnType<typeof sumGroup>) => t.deadMedium,
        getL: (t: ReturnType<typeof sumGroup>) => t.deadLow,
        // dead / responses
        getDenominator: (t: ReturnType<typeof sumGroup>, _grand: ReturnType<typeof sumGroup>) => t.responses,
        showTAT: true,
        getTAT: (t: ReturnType<typeof sumGroup>) => t.dead > 0 ? t.tatDead / t.dead : 0,
        getTATH: (t: ReturnType<typeof sumGroup>) => t.deadHigh > 0 ? t.tatDeadHigh / t.deadHigh : 0,
        getTATM: (t: ReturnType<typeof sumGroup>) => t.deadMedium > 0 ? t.tatDeadMedium / t.deadMedium : 0,
        getTATL: (t: ReturnType<typeof sumGroup>) => t.deadLow > 0 ? t.tatDeadLow / t.deadLow : 0,
    },
    {
        key: "pend", label: "Pending / Rescheduled",
        hdrBg: "#f3e8ff", hdrText: "#6b21a8",
        getTotal: (t: ReturnType<typeof sumGroup>) => t.pending,
        getH: (t: ReturnType<typeof sumGroup>) => t.pendingHigh,
        getM: (t: ReturnType<typeof sumGroup>) => t.pendingMedium,
        getL: (t: ReturnType<typeof sumGroup>) => t.pendingLow,
        // pending / sent
        getDenominator: (t: ReturnType<typeof sumGroup>, _grand: ReturnType<typeof sumGroup>) => t.sent,
        showTAT: true,
        getTAT: (t: ReturnType<typeof sumGroup>) => t.pending > 0 ? t.tatPending / t.pending : 0,
        getTATH: (t: ReturnType<typeof sumGroup>) => t.pendingHigh > 0 ? t.tatPendingHigh / t.pendingHigh : 0,
        getTATM: (t: ReturnType<typeof sumGroup>) => t.pendingMedium > 0 ? t.tatPendingMedium / t.pendingMedium : 0,
        getTATL: (t: ReturnType<typeof sumGroup>) => t.pendingLow > 0 ? t.tatPendingLow / t.pendingLow : 0,
    },
] as const;

// ─── GroupCells ───────────────────────────────────────────────────────────────

const GroupCells = React.memo(({
    total, H, M, L, denominator = 0,
    tatTotal = 0, tatH = 0, tatM = 0, tatL = 0,
    isDateRow = false, isGrand = false, showTAT = true,
    onCellClick
}: {
    total: number; H: number; M: number; L: number; denominator?: number;
    tatTotal?: number; tatH?: number; tatM?: number; tatL?: number;
    isDateRow?: boolean; isGrand?: boolean; showTAT?: boolean;
    onCellClick?: (intent: string) => void
}) => {

    const TatCell = ({ mins, isGrand }: { mins: number; isGrand?: boolean }) => {
        if (!showTAT) return null;
        const dc = delayColor(mins);
        const color = isGrand ? (mins > 0 ? "#ffffff" : "rgba(255,255,255,0.2)") : (mins > 0 ? dc.text : "text-slate-300");
        return (
            <td className="px-1.5 py-2 text-center whitespace-nowrap" style={isGrand ? { borderLeft: "1px solid rgba(255,255,255,0.08)" } : { borderBottom: "1px solid #e5e7eb" }}>
                <div className={`inline-flex items-center ${isGrand ? "" : dc.bg} px-1.5 py-0.5 rounded text-[10px] font-bold`} style={isGrand ? { color } : { color: typeof color === "string" && color.includes("text-") ? undefined : color }}>
                    {mins > 0 ? formatDelay(mins) : "—"}
                </div>
            </td>
        );
    };

    if (isGrand) {
        return (
            <>
                <td className="px-3 py-2.5 text-center whitespace-nowrap" style={{ borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 14, fontWeight: 800, color: "#ffffff" }}>{total}</span>
                </td>
                <td className="px-2 py-2 text-center whitespace-nowrap" style={{ borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 11, color: "#f3f4f6" }}>{denominator > 0 ? `${fmtPct(total, denominator)}%` : "0%"}</span>
                </td>
                {showTAT && <TatCell mins={tatTotal} isGrand />}

                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(22,101,52,0.25)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: "#86efac" }}>{H}</span>
                </td>
                <td className="px-2 py-2 text-center whitespace-nowrap" style={{ background: "rgba(22,101,52,0.15)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 11, color: "#86efac" }}>{fmtPct(H, total)}%</span>
                </td>
                {showTAT && <TatCell mins={tatH} isGrand />}

                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(120,53,15,0.25)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: "#fcd34d" }}>{M}</span>
                </td>
                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(120,53,15,0.15)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 11, color: "#fcd34d" }}>{fmtPct(M, total)}%</span>
                </td>
                {showTAT && <TatCell mins={tatM} isGrand />}

                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(127,29,29,0.25)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: "#f87171" }}>{L}</span>
                </td>
                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: "rgba(127,29,29,0.15)", borderLeft: "1px solid rgba(255,255,255,0.08)" }}>
                    <span style={{ fontSize: 11, color: "#f87171" }}>{fmtPct(L, total)}%</span>
                </td>
                {showTAT && <TatCell mins={tatL} isGrand />}
            </>
        );
    }

    if (isDateRow) {
        return (
            <>
                <td className="px-3 py-2.5 text-center whitespace-nowrap border-l-2 border-slate-300">
                    <span className="text-sm font-bold text-slate-800">{total}</span>
                </td>
                <td className="px-2 py-2.5 text-center whitespace-nowrap">
                    <span className="text-[11px] font-semibold text-slate-500">{denominator > 0 ? `${fmtPct(total, denominator)}%` : "0%"}</span>
                </td>
                {showTAT && <TatCell mins={tatTotal} />}

                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.H.bg, borderLeft: "1px solid #bbf7d0" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: CELL.H.count }}>{H}</span>
                </td>
                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.H.bg }}>
                    <span style={{ fontSize: 11, color: CELL.H.pct }}>{fmtPct(H, total)}%</span>
                </td>
                {showTAT && <TatCell mins={tatH} />}

                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.M.bg, borderLeft: "1px solid #fde68a" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: CELL.M.count }}>{M}</span>
                </td>
                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.M.bg }}>
                    <span style={{ fontSize: 11, color: CELL.M.pct }}>{fmtPct(M, total)}%</span>
                </td>
                {showTAT && <TatCell mins={tatM} />}

                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.L.bg, borderLeft: "1px solid #fca5a5" }}>
                    <span style={{ fontSize: 12, fontWeight: 700, color: CELL.L.count }}>{L}</span>
                </td>
                <td className="px-2 py-2.5 text-center whitespace-nowrap" style={{ background: CELL.L.bg }}>
                    <span style={{ fontSize: 11, color: CELL.L.pct }}>{fmtPct(L, total)}%</span>
                </td>
                {showTAT && <TatCell mins={tatL} />}
            </>
        );
    }

    // Source expanded row
    const cs = (count: number) => onCellClick && count > 0
        ? { cursor: "pointer" as const, textDecoration: "underline" as const }
        : {};
    return (
        <>
            <td className="px-3 py-2 text-center whitespace-nowrap border-l-2 border-slate-200 border-b border-slate-100" onClick={() => total > 0 && onCellClick?.("ALL")} style={cs(total)}>
                <span className="text-[13px] font-semibold text-slate-800" style={cs(total)}>{total}</span>
            </td>
            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100">
                <span className="text-[11px] text-slate-500">{denominator > 0 ? `${fmtPct(total, denominator)}%` : "0%"}</span>
            </td>
            {showTAT && <TatCell mins={tatTotal} />}

            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.H.bg, borderLeft: "1px solid #dcfce7" }} onClick={() => H > 0 && onCellClick?.("HIGH")}>
                <span style={{ fontSize: 12, fontWeight: 700, color: CELL.H.count, ...cs(H) }}>{H}</span>
            </td>
            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.H.bg }}>
                <span style={{ fontSize: 11, color: CELL.H.pct }}>{fmtPct(H, total)}%</span>
            </td>
            {showTAT && <TatCell mins={tatH} />}

            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.M.bg, borderLeft: "1px solid #fef9c3" }} onClick={() => M > 0 && onCellClick?.("MEDIUM")}>
                <span style={{ fontSize: 12, fontWeight: 700, color: CELL.M.count, ...cs(M) }}>{M}</span>
            </td>
            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.M.bg }}>
                <span style={{ fontSize: 11, color: CELL.M.pct }}>{fmtPct(M, total)}%</span>
            </td>
            {showTAT && <TatCell mins={tatM} />}

            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.L.bg, borderLeft: "1px solid #ffe4e6" }} onClick={() => L > 0 && onCellClick?.("LOW")}>
                <span style={{ fontSize: 12, fontWeight: 700, color: CELL.L.count, ...cs(L) }}>{L}</span>
            </td>
            <td className="px-2 py-2 text-center whitespace-nowrap border-b border-slate-100" style={{ background: CELL.L.bg }}>
                <span style={{ fontSize: 11, color: CELL.L.pct }}>{fmtPct(L, total)}%</span>
            </td>
            {showTAT && <TatCell mins={tatL} />}
        </>
    );
});


// ─── Loading / Error / Empty ──────────────────────────────────────────────────

function TableSkeleton() {
    return (
        <div className="p-6 space-y-3 animate-pulse">
            {[...Array(5)].map((_, i) => <div key={i} className="h-12 bg-slate-100 rounded-lg" />)}
        </div>
    );
}
function TableError({ message, onRetry }: { message: string; onRetry: () => void }) {
    return (
        <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
            <AlertCircle className="w-10 h-10 text-red-400" />
            <p className="text-sm font-semibold text-slate-600">Failed to load data</p>
            <p className="text-xs text-slate-400 max-w-sm">{message}</p>
            <button onClick={onRetry} className="mt-1 px-4 py-2 rounded-lg bg-blue-600 hover:bg-blue-700 text-white text-xs font-semibold transition">Retry</button>
        </div>
    );
}
function TableEmpty() {
    return (
        <div className="flex flex-col items-center justify-center gap-3 py-16 text-center">
            <div className="w-12 h-12 rounded-full bg-slate-100 flex items-center justify-center">{icons.table(22)}</div>
            <p className="text-sm font-semibold text-slate-500">No data available</p>
            <p className="text-xs text-slate-400">No records found for the selected filters.</p>
        </div>
    );
}

// ─── Breakdown Table ──────────────────────────────────────────────────────────

// Standalone helper to get averaged TAT for any filter combination
const getAveragedTAT = (dateVal: string, sourceVal: string, compVal: string, prioVal: string, stats: Record<string, { totalSeconds: number; count: number }[]>) => {
    const categories = Array(5).fill(null).map(() => ({ totalSeconds: 0, count: 0 }));
    // Redefine normalize locally if needed, or ensure global one is used
    const norm = (val?: string) => val?.trim().toLowerCase().replace(/\s+/g, "_") || "";

    Object.entries(stats).forEach(([key, arr]) => {
        const [d, s, c, p] = key.split('|');

        const matchDate = dateVal === "all" || d === dateVal;
        const matchSource = sourceVal === "all" || norm(s) === norm(sourceVal);
        const matchCompany = compVal === "all" || norm(c) === norm(compVal);
        const matchPriority = prioVal === "all" || p === prioVal;

        if (matchDate && matchSource && matchCompany && matchPriority) {
            arr.forEach((stat, i) => {
                categories[i].totalSeconds += stat.totalSeconds;
                categories[i].count += stat.count;
            });
        }
    });

    return categories.map(c => c.count > 0 ? Math.floor(c.totalSeconds / c.count) : 0);
};

function CompanyBreakdownTable({ company, sourceFilter, dateGroups, search, priority }: {
    company: string; sourceFilter: string; dateGroups: DateGroup[]; search: string; priority: string;
}) {
    // Data is now pre-filtered in the parent component for performance
    const filtered = dateGroups;

    const [expandedDates, setExpandedDates] = useState<Set<string>>(new Set());
    const [sortField, setSortField] = useState<string>("date");
    const [sortDir, setSortDir] = useState<"asc" | "desc">("desc");
    const [currentPage, setCurrentPage] = useState(1);
    const [rowsPerPage, setRowsPerPage] = useState(10);
    const [gotoInput, setGotoInput] = useState("");

    useEffect(() => {
        if (filtered.length > 0) setExpandedDates(new Set([filtered[0].date]));
    }, [filtered.length]);

    useEffect(() => { setCurrentPage(1); }, [company, sourceFilter, dateGroups]);

    const toggle = (date: string) => setExpandedDates(prev => {
        const next = new Set(prev);
        next.has(date) ? next.delete(date) : next.add(date);
        return next;
    });

    const handleSort = (field: string) => {
        if (sortField === field) setSortDir(d => d === "asc" ? "desc" : "asc");
        else { setSortField(field); setSortDir("desc"); }
    };

    const SortIcon = ({ field }: { field: string }) => {
        if (sortField !== field) return <ArrowUpDown className="w-3 h-3 opacity-50" />;
        return sortDir === "asc" ? <ArrowUp className="w-3 h-3" /> : <ArrowDown className="w-3 h-3" />;
    };

    const sorted = useMemo(() => [...filtered].sort((a, b) => {
        const tA = sumGroup(a.sources), tB = sumGroup(b.sources);
        let vA: any, vB: any;
        if (sortField === "date") { vA = a.date; vB = b.date; }
        else {
            const map = { sent: "sent", resp: "responses", qual: "qualified", dead: "dead", pend: "pending" } as Record<string, keyof ReturnType<typeof sumGroup>>;
            const key = map[sortField];
            vA = key ? tA[key] : 0; vB = key ? tB[key] : 0;
        }
        return sortDir === "asc" ? (vA > vB ? 1 : -1) : (vA < vB ? 1 : -1);
    }), [filtered, sortField, sortDir]);

    const grand = useMemo(() => sumGroup(filtered.flatMap(dg => dg.sources)), [filtered]);
    const totalDates = sorted.length;
    const totalPages = Math.max(1, Math.ceil(totalDates / rowsPerPage));
    const safePage = Math.min(currentPage, totalPages);
    const startIdx = (safePage - 1) * rowsPerPage;
    const paginated = sorted.slice(startIdx, startIdx + rowsPerPage);

    const goToPage = (p: number) => setCurrentPage(Math.max(1, Math.min(p, totalPages)));
    const handleRowsChange = (val: number) => { setRowsPerPage(val); setCurrentPage(1); };
    const handleGoto = () => { const n = parseInt(gotoInput, 10); if (!isNaN(n)) goToPage(n); setGotoInput(""); };

    if (totalDates === 0) return <TableEmpty />;

    const PriSubHdr = ({ label, showTAT = true }: { label: string; showTAT?: boolean }) => (
        <th colSpan={showTAT ? 3 : 2} className="px-2 py-2.5 text-center text-xs font-bold uppercase tracking-wider whitespace-nowrap"
            style={{ backgroundColor: HDR_BG, color: "#fff", borderLeft: "1px solid rgba(255,255,255,0.15)" }}>
            <div className="flex flex-col items-center gap-0.5">
                <span>{label}</span>
                <div className="flex gap-2 text-[10px] font-semibold normal-case mt-0.5" style={{ color: "rgba(255,255,255,0.55)" }}>
                    <span>Count</span><span style={{ opacity: 0.4 }}>|</span><span>%</span>
                    {showTAT && <><span style={{ opacity: 0.4 }}>|</span><span>TAT</span></>}
                </div>
            </div>
        </th>
    );

    return (
        <div>
            <div className="overflow-x-auto">
                <div className="inline-block min-w-full align-middle">
                    <table className="min-w-full" style={{ borderCollapse: "collapse" }}>
                        <thead>
                            <tr style={{ backgroundColor: HDR_BG }}>
                                <th rowSpan={2}
                                    className="sticky left-0 z-20 px-4 py-3 text-left text-xs font-bold text-white uppercase tracking-wider whitespace-nowrap cursor-pointer hover:bg-white/10"
                                    style={{ backgroundColor: HDR_BG, minWidth: 200, borderRight: "2px solid rgba(255,255,255,0.15)" }}
                                    onClick={() => handleSort("date")}>
                                    <div className="flex items-center gap-1.5">Date / Source <SortIcon field="date" /></div>
                                </th>
                                {GROUPS.map(g => (
                                    <th key={g.key} colSpan={g.key === "sent" ? 8 : 12}
                                        className="px-3 py-2.5 text-center text-xs font-bold uppercase tracking-wider cursor-pointer whitespace-nowrap"
                                        style={{ backgroundColor: g.hdrBg, color: g.hdrText, borderLeft: `2px solid ${g.hdrText}33` }}
                                        onClick={() => handleSort(g.key)}>
                                        <div className="flex items-center justify-center gap-1.5">{g.label} <SortIcon field={g.key} /></div>
                                    </th>
                                ))}
                            </tr>
                            <tr style={{ backgroundColor: HDR_BG2 }}>
                                {GROUPS.map((g, i) => (
                                    <React.Fragment key={g.key}>
                                        <th colSpan={g.key === "sent" ? 2 : 3}
                                            className="px-3 py-2.5 text-center text-xs font-bold text-white uppercase tracking-wider whitespace-nowrap cursor-pointer hover:bg-white/10"
                                            style={{ backgroundColor: HDR_BG2, borderLeft: i === 0 ? "none" : "2px solid rgba(255,255,255,0.2)" }}
                                            onClick={() => handleSort(g.key)}>
                                            <div className="flex flex-col items-center gap-0.5">
                                                <div className="flex items-center gap-1">
                                                    Total <SortIcon field={g.key} />
                                                </div>

                                                <div
                                                    className="flex gap-2 text-[10px] normal-case mt-0.5"
                                                    style={{ color: "rgba(255,255,255,0.55)" }}
                                                >
                                                    <span>Count</span>
                                                    <span style={{ opacity: 0.4 }}>|</span>
                                                    <span>%</span>
                                                    {g.key !== "sent" && (
                                                        <>
                                                            <span style={{ opacity: 0.4 }}>|</span>
                                                            <span>TAT (H:M:S)</span>
                                                        </>
                                                    )}
                                                </div>
                                            </div>
                                        </th>
                                        <PriSubHdr label="High" showTAT={g.key !== "sent"} />
                                        <PriSubHdr label="Medium" showTAT={g.key !== "sent"} />
                                        <PriSubHdr label="Low" showTAT={g.key !== "sent"} />
                                    </React.Fragment>
                                ))}
                            </tr>
                        </thead>

                        <tbody className="divide-y divide-slate-200 bg-white">
                            {paginated.map(dg => {
                                const t = sumGroup(dg.sources);
                                const exp = expandedDates.has(dg.date);
                                const bg = exp ? "#eff6ff" : "#f8fafc";

                                return (
                                    <React.Fragment key={dg.date}>
                                        {/* Date row */}
                                        <tr className="cursor-pointer hover:brightness-[0.97] transition-all border-b-2 border-slate-300"
                                            style={{ background: bg }} onClick={() => toggle(dg.date)}>
                                            <td className="sticky left-0 z-10 px-4 py-3 whitespace-nowrap" style={{ background: bg, borderRight: "2px solid #cbd5e1" }}>
                                                <div className="flex items-center gap-2">
                                                    {exp ? <ChevronDown className="w-4 h-4 text-blue-600 flex-shrink-0" /> : <ChevronRight className="w-4 h-4 text-blue-600 flex-shrink-0" />}
                                                    <Calendar className="w-3.5 h-3.5 text-slate-500 flex-shrink-0" />
                                                    <span className="text-[13px] font-bold text-slate-800">{dg.displayDate ?? dg.date}</span>
                                                    <span className="text-[11px] text-slate-500 ml-0.5">({dg.sources.length} src)</span>
                                                </div>
                                            </td>
                                            {GROUPS.map((g) => {
                                                const catIdx = GROUPS.indexOf(g);
                                                return (
                                                    <GroupCells key={g.key}
                                                        total={g.getTotal(t) ?? 0}
                                                        H={g.getH(t) ?? 0}
                                                        M={g.getM(t) ?? 0}
                                                        L={g.getL(t) ?? 0}
                                                        denominator={g.getDenominator(t, grand) ?? 0}
                                                        tatTotal={(g as any).getTAT ? (g as any).getTAT(t) : 0}
                                                        tatH={(g as any).getTATH ? (g as any).getTATH(t) : 0}
                                                        tatM={(g as any).getTATM ? (g as any).getTATM(t) : 0}
                                                        tatL={(g as any).getTATL ? (g as any).getTATL(t) : 0}
                                                        showTAT={g.key !== "sent"}
                                                        isDateRow />
                                                );
                                            })}
                                        </tr>

                                        {/* Source sub-rows */}
                                        {exp && dg.sources.map(s => {
                                            const handleClick = (intent: string, type: string) => {
                                                const base = "https://script.google.com/macros/s/AKfycbyZgL_rJ8A_8snRTfecPOs4fWtYVHvU6735g1scUgwcil0S4JpUK2tILv6MQuDhQEeixg/exec";
                                                const companyCount = s.company?.split(",").length ?? 1;
                                                const params = new URLSearchParams({
                                                    date: dg.date, intent,
                                                    company: companyCount > 1 ? "ALL" : s.company?.toUpperCase() || "ALL",
                                                    src: s.source?.toUpperCase() || "ALL",
                                                    type
                                                });
                                                window.open(`${base}?${params.toString()}`, "_blank");
                                            };

                                            return (
                                                <tr key={`${dg.date}-${s.company}-${s.source}`} className="bg-white hover:bg-slate-50 transition-colors">
                                                    <td className="sticky left-0 z-10 bg-white px-6 py-2.5 whitespace-nowrap" style={{ borderRight: "2px solid #e2e8f0" }}>
                                                        <div className="flex items-center gap-2">
                                                            <div style={{ width: 9, height: 9, borderRadius: "50%", background: s.color, flexShrink: 0 }} />
                                                            <span className="text-[13px] font-semibold text-slate-700">{s.source}</span>
                                                        </div>
                                                    </td>

                                                    {GROUPS.map((g) => {
                                                        if (g.key === "sent") return (
                                                            <GroupCells key={g.key}
                                                                total={s.sent ?? 0} H={s.sentHigh ?? 0} M={s.sentMedium ?? 0} L={s.sentLow ?? 0}
                                                                denominator={t.sent ?? 0}
                                                                showTAT={false}
                                                                onCellClick={(intent) => {
                                                                    const base = "https://script.google.com/macros/s/AKfycbym45pQfgcyqKRHLMtMt3gc0KWMcfPiHYngBZuswB7frxb7t4BMfxlVG1zFbe50bMH0/exec";
                                                                    const params = new URLSearchParams({
                                                                        date: dg.date, intent,
                                                                        company: (s.company?.split(",").length ?? 1) > 1 ? "ALL" : s.company?.toUpperCase() || "ALL",
                                                                        src: s.source?.toUpperCase() || "ALL"
                                                                    });
                                                                    window.open(`${base}?${params.toString()}`, "_blank");
                                                                }}
                                                            />
                                                        );

                                                        const catIdx = GROUPS.indexOf(g);
                                                        const st = sumGroup([s]);
                                                        return (
                                                            <GroupCells key={g.key}
                                                                total={g.getTotal(st) ?? 0}
                                                                H={g.getH(st) ?? 0}
                                                                M={g.getM(st) ?? 0}
                                                                L={g.getL(st) ?? 0}
                                                                denominator={g.getDenominator(st, t) ?? 0}
                                                                tatTotal={(g as any).getTAT ? (g as any).getTAT(st) : 0}
                                                                tatH={(g as any).getTATH ? (g as any).getTATH(st) : 0}
                                                                tatM={(g as any).getTATM ? (g as any).getTATM(st) : 0}
                                                                tatL={(g as any).getTATL ? (g as any).getTATL(st) : 0}
                                                                onCellClick={(intent) => handleClick(intent, g.key === "resp" ? "RECEIVED" : g.key === "qual" ? "QUALIFIED" : g.key === "pend" ? "PENDING" : g.key.toUpperCase())}
                                                            />
                                                        );
                                                    })}
                                                </tr>
                                            );
                                        })}
                                    </React.Fragment>
                                );
                            })}
                        </tbody>

                        <tfoot>
                            <tr style={{ background: "#1e293b", borderTop: "3px solid #0f172a" }}>
                                <td className="sticky left-0 z-10 px-4 py-3 whitespace-nowrap" style={{ background: "#1e293b", borderRight: "2px solid #0f172a" }}>
                                    <span className="text-[12px] font-extrabold text-white uppercase tracking-wider">Grand Total</span>
                                    <span className="ml-2 text-[11px] text-gray-300">({totalDates} dates)</span>
                                </td>
                                {/* Grand total: getDenominator(grand, grand) → same formula auto-applied */}
                                {GROUPS.map((g) => {
                                    return (
                                        <GroupCells key={g.key}
                                            total={g.getTotal(grand) ?? 0}
                                            H={g.getH(grand) ?? 0}
                                            M={g.getM(grand) ?? 0}
                                            L={g.getL(grand) ?? 0}
                                            denominator={g.getDenominator(grand, grand) ?? 0}
                                            tatTotal={(g as any).getTAT ? (g as any).getTAT(grand) : 0}
                                            tatH={(g as any).getTATH ? (g as any).getTATH(grand) : 0}
                                            tatM={(g as any).getTATM ? (g as any).getTATM(grand) : 0}
                                            tatL={(g as any).getTATL ? (g as any).getTATL(grand) : 0}
                                            showTAT={g.key !== "sent"}
                                            isGrand />
                                    );
                                })}
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>

            {/* Pagination */}
            <div className="flex flex-wrap items-center justify-between gap-y-2 gap-x-3 px-3 sm:px-4 py-3 border-t border-slate-200 bg-slate-50 text-[12px] text-slate-600 select-none">
                <span>Showing <strong className="text-slate-800">{totalDates === 0 ? "0" : `${startIdx + 1}–${Math.min(startIdx + rowsPerPage, totalDates)}`}</strong> of <strong className="text-slate-800">{totalDates}</strong> date{totalDates !== 1 ? "s" : ""}</span>
                <div className="flex items-center gap-1">
                    <button onClick={() => goToPage(1)} disabled={safePage === 1} className="w-7 h-7 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-bold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition">«</button>
                    <button onClick={() => goToPage(safePage - 1)} disabled={safePage === 1} className="h-7 px-2 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-semibold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition whitespace-nowrap">‹ Prev</button>
                    {(() => {
                        const pages: (number | "…")[] = [];
                        if (totalPages <= 7) { for (let i = 1; i <= totalPages; i++) pages.push(i); }
                        else {
                            pages.push(1);
                            if (safePage > 3) pages.push("…");
                            for (let i = Math.max(2, safePage - 1); i <= Math.min(totalPages - 1, safePage + 1); i++) pages.push(i);
                            if (safePage < totalPages - 2) pages.push("…");
                            pages.push(totalPages);
                        }
                        return pages.map((p, idx) => p === "…"
                            ? <span key={`e${idx}`} className="w-7 text-center text-slate-400">…</span>
                            : <button key={p} onClick={() => goToPage(p as number)}
                                className={`w-7 h-7 flex items-center justify-center rounded text-[11px] font-semibold border transition ${safePage === p ? "bg-blue-600 border-blue-600 text-white shadow-sm" : "border-slate-200 bg-white text-slate-600 hover:bg-slate-100"}`}>{p}</button>
                        );
                    })()}
                    <button onClick={() => goToPage(safePage + 1)} disabled={safePage === totalPages} className="h-7 px-2 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-semibold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition whitespace-nowrap">Next ›</button>
                    <button onClick={() => goToPage(totalPages)} disabled={safePage === totalPages} className="w-7 h-7 flex items-center justify-center rounded border border-slate-200 bg-white text-slate-500 text-[11px] font-bold hover:bg-slate-100 disabled:opacity-30 disabled:cursor-not-allowed transition">»</button>
                </div>
                <div className="flex items-center gap-3">
                    <div className="flex items-center gap-1.5">
                        <span className="text-slate-500 whitespace-nowrap">Rows/page</span>
                        <select value={rowsPerPage} onChange={e => handleRowsChange(Number(e.target.value))} className="h-7 rounded border border-slate-300 bg-white text-slate-700 text-[11px] font-semibold px-1 focus:outline-none focus:ring-1 focus:ring-blue-500 cursor-pointer">
                            {[5, 10, 25, 50, 100].map(n => <option key={n} value={n}>{n}</option>)}
                        </select>
                    </div>
                    <div className="flex items-center gap-1.5">
                        <span className="text-slate-500">Go to</span>
                        <input type="number" min={1} max={totalPages} value={gotoInput} onChange={e => setGotoInput(e.target.value)} onKeyDown={e => e.key === "Enter" && handleGoto()} placeholder="#" className="w-12 h-7 rounded border border-slate-300 bg-white text-slate-700 text-[11px] text-center font-semibold px-1 focus:outline-none focus:ring-1 focus:ring-blue-500" />
                        <button onClick={handleGoto} className="h-7 px-3 rounded bg-blue-600 hover:bg-blue-700 text-white text-[11px] font-bold transition">Go</button>
                    </div>
                </div>
            </div>
        </div>
    );
}

// ─── Main Page ────────────────────────────────────────────────────────────────

export default function AIVoiceSummaryReportPage() {
    const { data: rawDateGroups, loading, isRefreshing: hookRefreshing, error, refetch } = useVoiceSummary();
    const [isRefreshing, setIsRefreshing] = useState(false);
    const isRefreshingAny = isRefreshing || hookRefreshing;

    const handleRefresh = async () => {
        setIsRefreshing(true);
        await refetch();
        setIsRefreshing(false);
    };

    const [cacheTime, setCacheTime] = useState<string | null>(null);
    useEffect(() => {
        const t = localStorage.getItem("voice_summary_cache_time");
        if (t) setCacheTime(new Date(Number(t)).toLocaleTimeString());
    }, [loading, hookRefreshing]);

    const [view, setView] = useState<"table" | "charts">("table");
    const [search, setSearch] = useState("");
    const [debouncedSearch, setDebouncedSearch] = useState("");

    useEffect(() => {
        const timer = setTimeout(() => setDebouncedSearch(search), 300);
        return () => clearTimeout(timer);
    }, [search]);

    const [dateFilter, setDateFilter] = useState("this_week");
    const [company, setCompany] = useState("all");
    const [source, setSource] = useState("all");
    const [priority, setPriority] = useState("all");
    const [customDate, setCustomDate] = useState({ start: "", end: "" });

    const clearFilters = () => {
        setSearch(""); setDebouncedSearch(""); setDateFilter("all"); setCompany("all");
        setSource("all"); setPriority("all"); setCustomDate({ start: "", end: "" });
    };

    // ─── Optimized Data Processing ───
    const stats = useMemo(() => {
        // 1. Initial Date Filter
        const dateFiltered = filterByDateRange(rawDateGroups, dateFilter, customDate);

        // 2. Multi-purpose single pass over the data
        const dateFilteredGroups: DateGroup[] = [];
        const allFilteredSources: SourceDayRow[] = [];

        const kpiSum = { ...ZERO_SUM };
        const companyMap: Record<string, any> = {};
        const sourceMap: Record<string, any> = {};

        // Initialize default companies to ensure they always show
        ["KTAHV", "KAPPL", "VILLA RAAG", "KAC"].forEach(name => {
            companyMap[name] = { ...ZERO_SUM, name, color: companyColor(name) };
        });

        const lSearch = debouncedSearch.trim().toLowerCase();
        const normCompany = normalize(company);
        const normSource = normalize(source);

        dateFiltered.forEach(dg => {
            const daySourceMap = new Map<string, SourceDayRow>();

            dg.sources.forEach(s => {
                // Filtering logic
                const mc = company === "all" || normalize(s.company) === normCompany;
                const ms = source === "all" || normalize(s.source) === normSource;
                const mp = priority === "all"
                    || (priority === "high" && (s.sentHigh > 0 || s.qualHigh > 0))
                    || (priority === "medium" && (s.sentMedium > 0 || s.qualMedium > 0))
                    || (priority === "low" && (s.sentLow > 0 || s.qualLow > 0));

                const mSearch = !lSearch ||
                    (s.company?.toLowerCase().includes(lSearch)) ||
                    (s.source?.toLowerCase().includes(lSearch));

                if (mc && ms && mp && mSearch) {
                    allFilteredSources.push(s);

                    // Aggregate Global KPIs
                    const q = s.qualified ?? 0;
                    const d = s.dead ?? 0;
                    const r = q + d;

                    kpiSum.sent += s.sent;
                    kpiSum.sentHigh += s.sentHigh;
                    kpiSum.sentMedium += s.sentMedium;
                    kpiSum.sentLow += s.sentLow;
                    kpiSum.responses += r;
                    kpiSum.respHigh += (s.qualHigh ?? 0) + (s.deadHigh ?? 0);
                    kpiSum.respMedium += (s.qualMedium ?? 0) + (s.deadMedium ?? 0);
                    kpiSum.respLow += (s.qualLow ?? 0) + (s.deadLow ?? 0);
                    kpiSum.qualified += q;
                    kpiSum.qualHigh += s.qualHigh;
                    kpiSum.qualMedium += s.qualMedium;
                    kpiSum.qualLow += s.qualLow;
                    kpiSum.dead += d;
                    kpiSum.deadHigh += s.deadHigh;
                    kpiSum.deadMedium += s.deadMedium;
                    kpiSum.deadLow += s.deadLow;
                    kpiSum.pending += s.pending;
                    kpiSum.pendingHigh += s.pendingHigh;
                    kpiSum.pendingMedium += s.pendingMedium;
                    kpiSum.pendingLow += s.pendingLow;

                    const tr = (s.tatQualified ?? 0) + (s.tatDead ?? 0);
                    kpiSum.tatResponses += tr;
                    kpiSum.tatQualified += s.tatQualified;
                    kpiSum.tatDead += s.tatDead;
                    kpiSum.tatPending += s.tatPending;

                    // Aggregate Company Stats
                    let cName = s.company?.trim().toUpperCase() || "UNKNOWN";
                    if (cName === "VILLRAAG" || cName === "VILLARAAG") cName = "VILLA RAAG";

                    if (!companyMap[cName]) companyMap[cName] = { ...ZERO_SUM, name: cName, color: companyColor(cName), tatResponses: 0, tatQualified: 0, tatDead: 0, tatPending: 0 };
                    const cm = companyMap[cName];
                    cm.sent += s.sent;
                    cm.responses += r;
                    cm.qualified += q;
                    cm.dead += d;
                    cm.pending += s.pending;
                    cm.tatResponses += tr;
                    cm.tatQualified += s.tatQualified;
                    cm.tatDead += s.tatDead;
                    cm.tatPending += s.tatPending;

                    // Aggregate Source Stats
                    if (!sourceMap[s.source]) sourceMap[s.source] = { ...ZERO_SUM, name: s.source, color: s.color };
                    const sm = sourceMap[s.source];
                    sm.sent += s.sent;
                    sm.responses += r;
                    sm.qualified += q;
                    sm.dead += d;
                    sm.pending += s.pending;

                    // Table View Merge (one row per source per day)
                    const existing = daySourceMap.get(s.source);
                    if (existing) {
                        const sComp = s.company.trim();
                        if (!existing.company.split(",").some(c => c.trim() === sComp)) {
                            existing.company += "," + sComp;
                        }
                        existing.sent += s.sent;
                        existing.sentHigh += s.sentHigh;
                        existing.sentMedium += s.sentMedium;
                        existing.sentLow += s.sentLow;
                        existing.responses += s.responses;
                        existing.respHigh += s.respHigh;
                        existing.respMedium += s.respMedium;
                        existing.respLow += s.respLow;
                        existing.qualified += s.qualified;
                        existing.qualHigh += s.qualHigh;
                        existing.qualMedium += s.qualMedium;
                        existing.qualLow += s.qualLow;
                        existing.dead += s.dead;
                        existing.deadHigh += s.deadHigh;
                        existing.deadMedium += s.deadMedium;
                        existing.deadLow += s.deadLow;
                        existing.pending += s.pending;
                        existing.pendingHigh += s.pendingHigh;
                        existing.pendingMedium += s.pendingMedium;
                        existing.pendingLow += s.pendingLow;
                        existing.tatResponses += s.tatResponses;
                        existing.tatQualified += s.tatQualified;
                        existing.tatDead += s.tatDead;
                        existing.tatPending += s.tatPending;
                    } else {
                        daySourceMap.set(s.source, { ...s });
                    }
                }
            });

            if (daySourceMap.size > 0) {
                dateFilteredGroups.push({
                    ...dg,
                    sources: Array.from(daySourceMap.values())
                });
            }
        });

        // 3. Finalize aggregations
        const companyAgg = Object.values(companyMap).sort((a: any, b: any) => (b.sent ?? 0) - (a.sent ?? 0));
        const sourceAgg = Object.values(sourceMap).sort((a: any, b: any) => b.sent - a.sent).slice(0, 8);

        // 4. Chart Data Preparation
        const last14 = [...dateFiltered].slice(0, 14).reverse();
        const trendData = {
            labels: last14.map(d => d.displayDate ?? d.date),
            datasets: [
                { label: "Sent", data: last14.map(d => sumGroup(d.sources).sent), borderColor: "#6366f1", backgroundColor: "rgba(99,102,241,.08)", fill: true, tension: 0.4, pointBackgroundColor: "#6366f1", pointRadius: 4, borderWidth: 2 },
                { label: "Qualified", data: last14.map(d => sumGroup(d.sources).qualified), borderColor: "#10b981", backgroundColor: "rgba(16,185,129,.08)", fill: true, tension: 0.4, pointBackgroundColor: "#10b981", pointRadius: 4, borderWidth: 2 },
            ],
        };

        const barCompanyData = {
            labels: companyAgg.map((c: any) => c.name),
            datasets: [
                { label: "Sent", data: companyAgg.map((c: any) => c.sent), backgroundColor: "#6366f1", borderRadius: 4 },
                { label: "Qualified", data: companyAgg.map((c: any) => c.qualified), backgroundColor: "#10b981", borderRadius: 4 },
                { label: "Non-Qualified", data: companyAgg.map((c: any) => c.dead), backgroundColor: "#f87171", borderRadius: 4 },
                { label: "Pending", data: companyAgg.map((c: any) => c.pending), backgroundColor: "#c084fc", borderRadius: 4 },
            ],
        };

        const barSourceData = {
            labels: sourceAgg.map((s: any) => s.name),
            datasets: [
                { label: "Sent", data: sourceAgg.map((s: any) => s.sent), backgroundColor: "#6366f1", borderRadius: 4 },
                { label: "Qualified", data: sourceAgg.map((s: any) => s.qualified), backgroundColor: "#10b981", borderRadius: 4 },
                { label: "Non-Qualified", data: sourceAgg.map((s: any) => s.dead), backgroundColor: "#f87171", borderRadius: 4 },
                { label: "Pending", data: sourceAgg.map((s: any) => s.pending), backgroundColor: "#c084fc", borderRadius: 4 },
            ],
        };

        const barQualPct = {
            labels: companyAgg.map((c: any) => c.name),
            datasets: [
                { label: "Qualified %", data: companyAgg.map((c: any) => c.responses > 0 ? +((c.qualified / c.responses) * 100).toFixed(1) : 0), backgroundColor: "#10b981", borderRadius: 4 },
                { label: "Non-Qualified %", data: companyAgg.map((c: any) => c.responses > 0 ? +((c.dead / c.responses) * 100).toFixed(1) : 0), backgroundColor: "#f87171", borderRadius: 4 },
                { label: "Pending %", data: companyAgg.map((c: any) => c.sent > 0 ? +((c.pending / c.sent) * 100).toFixed(1) : 0), backgroundColor: "#c084fc", borderRadius: 4 },
            ],
        };

        const barSourceStacked = {
            labels: sourceAgg.map((s: any) => s.name),
            datasets: [
                { label: "Qualified", data: sourceAgg.map((s: any) => s.qualified), backgroundColor: "#10b981", borderRadius: 0 },
                { label: "Non-Qualified", data: sourceAgg.map((s: any) => s.dead), backgroundColor: "#f87171", borderRadius: 0 },
                { label: "Pending", data: sourceAgg.map((s: any) => s.pending), backgroundColor: "#c084fc", borderRadius: 0 },
            ],
        };

        const dynamicSources = Array.from(new Set(rawDateGroups.flatMap(dg => dg.sources.map(s => s.source))))
            .filter(n => !!n && n.trim() !== "")
            .sort()
            .map(n => ({ value: n.trim().toLowerCase().replace(/\s+/g, "_"), label: n, raw: n }))
            .filter(ds => ds.value !== "");

        const dynamicCompanies = Array.from(new Set(rawDateGroups.flatMap(dg => dg.sources.map(s => s.company?.trim()).filter(Boolean))))
            .filter(n => !!n && n.trim() !== "").sort();

        return {
            dateFilteredGroups,
            allSources: allFilteredSources,
            kpi: kpiSum,
            companyAgg,
            sourceAgg,
            trendData,
            barCompanyData,
            barSourceData,
            barQualPct,
            barSourceStacked,
            dynamicSources,
            dynamicCompanies
        };
    }, [rawDateGroups, dateFilter, customDate, company, source, priority, debouncedSearch]);

    const {
        dateFilteredGroups, kpi, companyAgg, sourceAgg, trendData,
        barCompanyData, barSourceData, barQualPct, barSourceStacked,
        dynamicSources, dynamicCompanies
    } = stats;

    const kpiQualRate = kpi.responses > 0 ? ((kpi.qualified / kpi.responses) * 100).toFixed(1) + "%" : "0%";

    const doughnutPriority = useMemo(() => ({
        labels: ["High", "Medium", "Low"],
        datasets: [{ data: [kpi.sentHigh, kpi.sentMedium, kpi.sentLow], backgroundColor: ["#f87171", "#fbbf24", "#34d399"], borderWidth: 2, borderColor: "#fff", hoverOffset: 6 }],
    }), [kpi]);

    const doughnutStatus = useMemo(() => ({
        labels: ["Qualified", "Non-Qualified", "Pending"],
        datasets: [{ data: [kpi.qualified, kpi.dead, kpi.pending], backgroundColor: ["#10b981", "#f87171", "#c084fc"], borderWidth: 2, borderColor: "#fff", hoverOffset: 6 }],
    }), [kpi]);

    // const { data: sentLeads } = useSentLeads();
    // const { data: receivedLeads } = useReceivedLeads();

    const realPerformanceMetrics = {};
    // const realPerformanceMetrics = useMemo(() => {
    //     ...
    // }, [sentLeads, receivedLeads]);

    // const realCardDelays = useMemo(() => getAveragedTAT("all", "all", "all", "all", realPerformanceMetrics), [realPerformanceMetrics]);

    if (loading && rawDateGroups.length === 0) {
        return (
            <div className="min-h-screen bg-gradient-to-br from-slate-50 via-white to-blue-50">
                <div className="flex flex-col items-center justify-center min-h-[60vh]">
                    <Image src="/grouploader.gif" alt="Loading" width={200} height={200} priority className="animate-pulse" />
                    <p className="mt-4 text-base font-bold text-emerald-600 animate-pulse">Fetching latest AI Voice Call Summary...</p>
                </div>
            </div>
        );
    }

    return (
        <div className="font-sans bg-[#f0f2f8] min-h-full text-slate-800">

            {/* ── Banner ── */}
            <div style={{ background: "linear-gradient(110deg,#1e1b4b 0%,#3730a3 40%,#4f46e5 75%,#6366f1 100%)", padding: "16px 20px", display: "flex", alignItems: "center", position: "relative", overflow: "hidden", flexWrap: "wrap", gap: 12 }}>
                <div style={{ position: "absolute", right: -60, top: -60, width: 220, height: 220, borderRadius: "50%", background: "rgba(255,255,255,.05)" }} />
                <div style={{ width: 40, height: 40, borderRadius: 10, background: "rgba(255,255,255,.15)", display: "flex", alignItems: "center", justifyContent: "center", marginRight: 12, flexShrink: 0, color: "#fff" }}>{icons.chart(22)}</div>
                <div style={{ flex: 1, minWidth: 180 }}>
                    <div style={{ fontSize: 18, fontWeight: 800, color: "#fff", letterSpacing: "-.3px", lineHeight: 1.2 }}>AI Voice Lead Qualification — Summary Report</div>
                    <div style={{ fontSize: 11, color: "rgba(255,255,255,.6)", marginTop: 3 }}>KServe AI · Company-wise Performance Analysis &amp; Lead Qualification Insights</div>
                </div>
                {/* <div className="hidden lg:flex items-center gap-4" style={{ position: "relative", zIndex: 1 }}>
                    {hookRefreshing && !isRefreshing && (
                        <div className="flex items-center gap-2 text-white/60 text-[11px] font-medium animate-pulse">
                            <Loader2 className="w-3 h-3 animate-spin" />
                            Background Syncing...
                        </div>
                    )}
                    <button onClick={handleRefresh} disabled={isRefreshingAny}
                        style={{ background: "rgba(255,255,255,.15)", border: "1px solid rgba(255,255,255,.2)", borderRadius: 8, height: 38, padding: "0 14px", color: "#fff", fontSize: 12, fontWeight: 700, cursor: isRefreshingAny ? "not-allowed" : "pointer", display: "flex", alignItems: "center", gap: 6, transition: "all .2s" }}>
                        <div style={{ width: 12, height: 12, border: "2px solid rgba(255,255,255,0.3)", borderTopColor: "#fff", borderRadius: "50%", animation: isRefreshingAny ? "spin 0.8s linear infinite" : "none" }} />
                        {isRefreshingAny ? "Syncing..." : "Sync Now"}
                    </button>
                    <div style={{ width: 1, height: 24, background: "rgba(255,255,255,0.1)" }} />
                </div> */}

                <div className="hidden sm:flex" style={{ alignItems: "center", gap: 10, position: "relative", zIndex: 1, flexWrap: "wrap" }}>
                    {[
                        { val: String(kpi.sent), lbl: "Total Leads", color: "#fff" },
                        { val: String(kpi.qualified), lbl: "Qualified", color: "#6ee7b7" },
                        { val: String(kpi.dead), lbl: "Non-Qualified", color: "#fca5a5" },
                        { val: String(kpi.pending), lbl: "Pending", color: "#c084fc" },
                        { val: kpiQualRate, lbl: "Qual. Rate", color: "#fde68a" },
                    ].map(s => (
                        <div key={s.lbl} style={{ textAlign: "center", background: "rgba(255,255,255,.1)", border: "1px solid rgba(255,255,255,.15)", borderRadius: 8, padding: "7px 12px", minWidth: 72 }}>
                            <div style={{ fontSize: 20, fontWeight: 800, color: s.color, lineHeight: 1 }}>{s.val}</div>
                            <div style={{ fontSize: 9, color: "rgba(255,255,255,.55)", textTransform: "uppercase", letterSpacing: ".7px", fontWeight: 600, marginTop: 3 }}>{s.lbl}</div>
                        </div>
                    ))
                    }
                </div>
                <div className="grid sm:hidden grid-cols-3 gap-2 mt-1 w-full" style={{ position: "relative", zIndex: 1 }}>
                    {[
                        { val: String(kpi.sent), lbl: "Leads", color: "#fff" },
                        { val: String(kpi.qualified), lbl: "Qual.", color: "#6ee7b7" },
                        { val: String(kpi.dead), lbl: "Dead", color: "#fca5a5" },
                        { val: String(kpi.pending), lbl: "Pend.", color: "#c084fc" },
                        { val: kpiQualRate, lbl: "Rate", color: "#fde68a" },
                    ].map(s => (
                        <div key={s.lbl} className="text-center" style={{ background: "rgba(255,255,255,.1)", border: "1px solid rgba(255,255,255,.15)", borderRadius: 7, padding: "6px 4px" }}>
                            <div style={{ fontSize: 16, fontWeight: 800, color: s.color, lineHeight: 1 }}>{s.val}</div>
                            <div style={{ fontSize: 8.5, color: "rgba(255,255,255,.55)", textTransform: "uppercase", letterSpacing: ".5px", fontWeight: 600, marginTop: 2 }}>{s.lbl}</div>
                        </div>
                    ))}
                </div>
            </div>

            {/* ── Filters ── */}
            <div className="mt-3 mx-3 sm:mx-5">
                <div className="rounded-xl border border-slate-200 bg-white shadow-md">
                    <div className="flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4 px-5 py-4 bg-gradient-to-r from-blue-100 via-white to-indigo-100 border-b border-slate-200 rounded-t-xl">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-600 via-indigo-600 to-blue-700 flex items-center justify-center shadow-md border border-blue-700/30">
                                <Search className="w-5 h-5 text-white" />
                            </div>
                            <div>
                                <h3 className="text-sm font-semibold text-slate-900">Filters</h3>
                                <p className="text-xs text-slate-500">Refine results by date, company, source and priority</p>
                            </div>
                        </div>
                        <Button variant="outline" size="sm" onClick={clearFilters} className="bg-white border-slate-300 text-slate-700 font-medium hover:bg-blue-50">Clear Filters</Button>
                    </div>
                    <div className="px-5 py-4">
                        <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-6 gap-4">
                            <div className="flex flex-col gap-1.5 lg:col-span-2">
                                <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Search</label>
                                <Input placeholder="Search company or source..." value={search} onChange={e => setSearch(e.target.value)} className="h-10 w-full rounded-md border-gray-300" />
                            </div>
                            <div className="flex flex-col gap-1.5">
                                <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Date Range</label>
                                <Select value={dateFilter} onValueChange={setDateFilter}>
                                    <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="Select range" /></SelectTrigger>
                                    <SelectContent>
                                        {[["all", "All"], ["today", "Today"], ["yesterday", "Yesterday"], ["this_week", "This Week"], ["last_week", "Last Week"], ["this_month", "This Month"], ["last_month", "Last Month"], ["this_year", "This Year"], ["last_year", "Last Year"], ["custom", "Custom"]].map(([v, l]) => (
                                            <SelectItem key={v} value={v}>{l}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="flex flex-col gap-1.5">
                                <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Company</label>
                                <Select value={company} onValueChange={setCompany}>
                                    <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="All Companies" /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All Companies</SelectItem>
                                        {dynamicCompanies.map(c => {
                                            const val = c.trim().toLowerCase().replace(/\s+/g, "_");
                                            if (!val) return null;
                                            return <SelectItem key={c} value={val}>{c}</SelectItem>;
                                        })}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="flex flex-col gap-1.5">
                                <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Data Source</label>
                                <Select value={source} onValueChange={setSource}>
                                    <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="All Sources" /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All Sources</SelectItem>
                                        {dynamicSources.map(ds => (
                                            <SelectItem key={ds.value} value={ds.value}>{ds.label}</SelectItem>
                                        ))}
                                    </SelectContent>
                                </Select>
                            </div>
                            <div className="flex flex-col gap-1.5">
                                <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Priority</label>
                                <Select value={priority} onValueChange={setPriority}>
                                    <SelectTrigger className="h-10 w-full rounded-md border-gray-300"><SelectValue placeholder="All" /></SelectTrigger>
                                    <SelectContent>
                                        <SelectItem value="all">All</SelectItem>
                                        <SelectItem value="high">High</SelectItem>
                                        <SelectItem value="medium">Medium</SelectItem>
                                        <SelectItem value="low">Low</SelectItem>
                                    </SelectContent>
                                </Select>
                            </div>
                        </div>
                        {dateFilter === "custom" && (
                            <div className="grid grid-cols-1 sm:grid-cols-2 gap-4 mt-4 pt-4 border-t border-slate-200">
                                <div className="flex flex-col gap-1.5">
                                    <label className="text-xs font-medium uppercase tracking-wide text-slate-500">Start Date</label>
                                    <Input type="date" value={customDate.start} onChange={e => setCustomDate({ ...customDate, start: e.target.value })} className="h-10 w-full rounded-md border-gray-300" />
                                </div>
                                <div className="flex flex-col gap-1.5">
                                    <label className="text-xs font-medium uppercase tracking-wide text-slate-500">End Date</label>
                                    <Input type="date" value={customDate.end} onChange={e => setCustomDate({ ...customDate, end: e.target.value })} className="h-10 w-full rounded-md border-gray-300" />
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* ── KPI Cards ── */}
            <div className="mx-3 sm:mx-5 mt-3">
                <div className="bg-white border-2 border-slate-200 rounded-xl shadow-xl">
                    <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 px-5 py-3 bg-gradient-to-r from-slate-100 via-white to-blue-100 border-b border-slate-200 rounded-t-xl">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-lg bg-gradient-to-br from-blue-600 via-blue-700 to-indigo-700 flex items-center justify-center shadow-md border border-blue-500/40">
                                <BarChart3 className="h-5 w-5 text-white" />
                            </div>
                            <div>
                                <h3 className="text-sm font-semibold text-slate-900">Key Performance Indicators</h3>
                                <p className="text-[11px] text-slate-500">Overview of lead metrics &amp; performance</p>
                            </div>
                        </div>
                    </div>
                    <div className="p-5">
                        {loading ? (
                            <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 animate-pulse">
                                {[...Array(4)].map((_, i) => <div key={i} className="h-28 bg-slate-100 rounded-lg" />)}
                            </div>
                        ) : (
                            <div className="bg-blue-50/60 border border-blue-200 rounded-xl p-4 space-y-4">
                                <h4 className="text-sm font-bold text-slate-700 uppercase tracking-wide">AI Voice Metrics</h4>
                                <div className="grid grid-cols-1 sm:grid-cols-3 lg:grid-cols-5 gap-3">
                                    {[
                                        // Sent      % = sent / sent = 100%
                                        { label: "Total Leads Sent", val: kpi.sent, pctOf: kpi.sent, bg: "bg-blue-50/70", border: "border-blue-300", lc: "text-blue-700" },
                                        // Responses % = responses / sent
                                        { label: "Total Responses Received", val: kpi.responses, pctOf: kpi.sent, bg: "bg-slate-50/70", border: "border-slate-300", lc: "text-slate-700" },
                                        // Qualified % = qualified / responses
                                        { label: "Total Qualified Leads", val: kpi.qualified, pctOf: kpi.responses, bg: "bg-emerald-50/70", border: "border-emerald-300", lc: "text-emerald-700" },
                                        // Dead      % = dead / responses
                                        { label: "Dead / Non-Qualified", val: kpi.dead, pctOf: kpi.responses, bg: "bg-red-50/70", border: "border-red-300", lc: "text-red-700" },
                                        // Pending   % = pending / sent
                                        { label: "Pending / Rescheduled", val: kpi.pending, pctOf: kpi.sent, bg: "bg-violet-50/70", border: "border-violet-300", lc: "text-violet-700" },
                                    ].map((card, ci) => (
                                        <div key={card.label} className={`${card.bg} border-2 ${card.border} rounded-lg p-3 shadow-sm hover:shadow-md transition relative`}>

                                            {/* GROWTH / REMAINING badge — only on ci===1 */}
                                            {ci === 1 && (card.pctOf ?? 0) > 0 && (() => {
                                                const pct = (((card.val ?? 0) / (card.pctOf ?? 1) * 100) - 100);
                                                const isNegative = pct < 0;
                                                return (
                                                    <div className="absolute top-2 right-2 flex flex-col items-end">
                                                        <div className={`text-[10px] font-bold px-1.5 py-0.5 rounded border shadow-sm ${isNegative ? "text-red-600 bg-red-50 border-red-200" : "text-green-600 bg-green-50 border-green-200"}`}>
                                                            {pct.toFixed(1)}%
                                                        </div>
                                                        <span className={`text-[8px] font-medium tracking-tight mt-0.5 whitespace-nowrap ${isNegative ? "text-red-400" : "text-green-400"}`}>
                                                            {isNegative ? "REMAINING" : "GROWTH"}
                                                        </span>
                                                    </div>
                                                );
                                            })()}

                                            {/* Label */}
                                            <p className={`text-[10px] font-semibold uppercase tracking-wide ${card.lc} leading-tight mb-2`}>{card.label}</p>

                                            {/* Value + % + delay pill inline */}
                                            <p className="text-2xl font-bold text-slate-900 leading-none mb-2 flex items-baseline gap-2 flex-wrap">
                                                {card.val ?? 0}
                                                {(card.pctOf ?? 0) > 0 && (
                                                    <span className="text-sm font-semibold text-slate-800">
                                                        ({(((card.val ?? 0) / (card.pctOf ?? 1)) * 100).toFixed(1)}%)
                                                    </span>
                                                )}
                                                {ci !== 0 && (() => {
                                                    const tatVals = [0, kpi.tatResponses, kpi.tatQualified, kpi.tatDead, kpi.tatPending];
                                                    const counts = [kpi.sent, kpi.responses, kpi.qualified, kpi.dead, kpi.pending];
                                                    const avgTat = counts[ci] > 0 ? tatVals[ci] / counts[ci] : 0;

                                                    if (avgTat < 0) return null;

                                                    const dc = delayColor(avgTat);
                                                    return (
                                                        <span className={`inline-flex items-center ${dc.bg} border ${dc.border} rounded-full px-2 py-0.5`}>
                                                            <span className={`text-[10px] font-semibold ${dc.text}`}>{formatDelay(avgTat)}</span>
                                                        </span>
                                                    );
                                                })()}
                                            </p>

                                            {/* Company breakdown */}
                                            <div className="flex flex-col gap-1 text-[10px]">
                                                {companyAgg.map(c => {
                                                    const vals = [c.sent, c.responses, c.qualified, c.dead, c.pending];
                                                    const v = vals[ci] ?? 0;
                                                    const denomForPct =
                                                        ci === 0 ? kpi.sent :
                                                            ci === 1 ? kpi.sent :
                                                                ci === 2 ? kpi.responses :
                                                                    ci === 3 ? kpi.responses :
                                                                        kpi.sent; // ci === 4 (Pending)

                                                    // const companyTat = getAveragedTAT("all", "all", c.name, "all", realPerformanceMetrics);
                                                    // const delayVal = companyTat[ci];

                                                    return (
                                                        <div key={c.name} className="flex items-center justify-between gap-1">
                                                            <span className="font-medium" style={{ color: c.color }}>{c.name}:</span>
                                                            <span className="font-semibold flex items-center gap-1" style={{ color: c.color }}>
                                                                {(denomForPct ?? 0) > 0
                                                                    ? `${v} (${((v / (denomForPct ?? 1)) * 100).toFixed(1)}%)`
                                                                    : String(v)}
                                                                {ci !== 0 && (
                                                                    (() => {
                                                                        const tatVals = [0, c.tatResponses, c.tatQualified, c.tatDead, c.tatPending];
                                                                        const counts = [c.sent, c.responses, c.qualified, c.dead, c.pending];
                                                                        const avgTat = counts[ci] > 0 ? tatVals[ci] / counts[ci] : 0;

                                                                        if (avgTat < 0) return null;

                                                                        const dc = delayColor(avgTat);
                                                                        return (
                                                                            <span className={`text-[9px] font-semibold ${dc.bg} border ${dc.border} rounded px-1 ${dc.text}`}>
                                                                                {formatDelay(avgTat)}
                                                                            </span>
                                                                        );
                                                                    })()
                                                                )}
                                                            </span>
                                                        </div>
                                                    );
                                                })}
                                            </div>
                                        </div>
                                    ))}
                                </div>
                            </div>
                        )}
                    </div>
                </div>
            </div>

            {/* ── Source Breakdown ── */}
            <div className="mx-3 sm:mx-5 mt-3 mb-5">
                <div className="bg-white border border-slate-200 rounded-xl shadow-md overflow-hidden">
                    <div className="flex flex-wrap items-center justify-between gap-3 px-4 sm:px-5 py-4 border-b border-slate-100">
                        <div className="flex items-center gap-3">
                            <div className="w-10 h-10 rounded-xl bg-orange-500 flex items-center justify-center shadow-md flex-shrink-0">{icons.dashboard(18)}</div>
                            <div>
                                <h3 className="text-[14px] font-bold text-slate-900 leading-tight">Source-wise Breakdown</h3>
                                <p className="text-[11px] text-slate-400 mt-0.5">Date-wise Call performance — High · Medium · Low quality across all metrics</p>
                            </div>
                        </div>
                        <div className="flex items-center gap-3">
                            {/* {cacheTime && (
                                <div className="hidden md:flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg bg-slate-50 border border-slate-200">
                                    <div className={`w-1.5 h-1.5 rounded-full ${loading ? "bg-amber-400 animate-pulse" : "bg-emerald-500"}`} />
                                    <span className="text-[10px] font-bold text-slate-500 uppercase tracking-tight">Sync: {cacheTime}</span>
                                </div>
                            )}
                            <button
                                onClick={() => refetch()}
                                disabled={loading}
                                className="flex items-center gap-2 px-3 py-1.5 bg-white border border-slate-200 rounded-lg text-xs font-bold text-slate-600 hover:bg-slate-50 disabled:opacity-50 transition-all shadow-sm"
                            >
                                <Loader2 className={`w-3 h-3 ${loading ? "animate-spin text-indigo-600" : ""}`} />
                                {loading ? "Syncing..." : "Sync Now"}
                            </button> */}
                            <div className="flex items-center rounded-lg overflow-hidden border border-slate-200 shadow-sm">
                                {(["table", "charts"] as const).map(v => (
                                    <button key={v} onClick={() => setView(v)}
                                        className="flex items-center gap-2 px-4 py-1.5 text-[11px] font-bold transition-all"
                                        style={{ background: view === v ? "#4f46e5" : "#fff", color: view === v ? "#fff" : "#64748b", borderRight: v === "table" ? "1px solid #e2e8f0" : "none", fontFamily: "inherit", cursor: "pointer" }}>
                                        {v === "table" ? icons.table(12) : icons.chart(12)}
                                        {v === "table" ? "Table View" : "Analytics"}
                                    </button>
                                ))}
                            </div>
                        </div>
                    </div>

                    {view === "table" && (
                        loading ? <TableSkeleton />
                            : error ? <TableError message={error} onRetry={refetch} />
                                : <CompanyBreakdownTable company={company} sourceFilter={source} dateGroups={dateFilteredGroups} search={debouncedSearch} priority={priority} />
                    )}

                    {view === "charts" && !loading && (
                        <div className="p-4 space-y-3">
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <ChartCard title="Company-wise Lead Performance" subtitle="Sent vs Qualified vs Non-Qualified vs Pending per company" iconBg="#eef2ff" iconColor="#4f46e5" icon={icons.dashboard()} legend={[{ color: "#6366f1", label: "Sent" }, { color: "#10b981", label: "Qualified" }, { color: "#f87171", label: "Non-Qualified" }, { color: "#c084fc", label: "Pending" }]}>
                                    <div style={{ position: "relative", height: 220 }}><Bar data={barCompanyData} options={commonBarOpts} /></div>
                                </ChartCard>
                                <ChartCard title="Source-wise Lead Performance" subtitle="Sent vs Qualified vs Non-Qualified vs Pending per source" iconBg="#fef3c7" iconColor="#d97706" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><path d="M21 16V8a2 2 0 00-1-1.73l-7-4a2 2 0 00-2 0l-7 4A2 2 0 003 8v8a2 2 0 001 1.73l7 4a2 2 0 002 0l7-4A2 2 0 0021 16z" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>} legend={[{ color: "#6366f1", label: "Sent" }, { color: "#10b981", label: "Qualified" }, { color: "#f87171", label: "Non-Qualified" }, { color: "#c084fc", label: "Pending" }]}>
                                    <div style={{ position: "relative", height: 220 }}><Bar data={barSourceData} options={commonBarOpts} /></div>
                                </ChartCard>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                                <ChartCard title="Priority Distribution" subtitle="All leads by priority level" iconBg="#fee2e2" iconColor="#dc2626" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><circle cx="12" cy="12" r="10" strokeWidth="2" /><path d="M12 8v4l3 3" strokeWidth="2" strokeLinecap="round" /></svg>}>
                                    <div style={{ height: 180, display: "flex", alignItems: "center", justifyContent: "center" }}><div style={{ maxWidth: 160, width: "100%" }}><Doughnut data={doughnutPriority} options={{ responsive: true, maintainAspectRatio: true, cutout: "68%", plugins: { legend: { display: false }, tooltip: { callbacks: { label: (ctx: any) => `${ctx.label}: ${ctx.parsed} leads` } } } }} /></div></div>
                                    <ChartLegend items={[{ color: "#f87171", label: `High (${fmtPct(kpi.sentHigh, kpi.sent)}%)`, round: true }, { color: "#fbbf24", label: `Medium (${fmtPct(kpi.sentMedium, kpi.sent)}%)`, round: true }, { color: "#34d399", label: `Low (${fmtPct(kpi.sentLow, kpi.sent)}%)`, round: true }]} />
                                </ChartCard>
                                <ChartCard title="Qualification % by Company" subtitle="Qualified & Non-Qualified (% of Responses) vs Pending (% of Sent)" iconBg="#d1fae5" iconColor="#059669" icon={icons.check()} legend={[{ color: "#10b981", label: "Qualified %" }, { color: "#f87171", label: "Non-Qualified %" }, { color: "#c084fc", label: "Pending %" }]}>
                                    <div style={{ position: "relative", height: 220 }}><Bar data={barQualPct} options={{ ...commonBarOpts, indexAxis: "y" as const, scales: { x: { stacked: true, max: 100, ticks: { callback: (v: any) => v + "%", font: chartFont, color: "#64748b" }, grid: { color: "#f1f5f9" }, border: { display: false } }, y: { stacked: true, ticks: { font: chartFont, color: "#1e293b" }, grid: { display: false }, border: { display: false } } }, barPercentage: 0.6, categoryPercentage: 0.7 }} /></div>
                                </ChartCard>
                                <ChartCard title="Daily Qualification Trend" subtitle="Leads sent & qualified over time" iconBg="#ede9fe" iconColor="#7c3aed" icon={icons.trend()} legend={[{ color: "#6366f1", label: "Sent", round: true }, { color: "#10b981", label: "Qualified", round: true }]}>
                                    <div style={{ position: "relative", height: 220 }}><Line data={trendData} options={commonBarOpts} /></div>
                                </ChartCard>
                            </div>
                            <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
                                <ChartCard title="Qualification % by Source (Stacked)" subtitle="Qualified & Non-Qualified split across sources" iconBg="#dbeafe" iconColor="#2563eb" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><rect x="3" y="3" width="18" height="18" rx="2" strokeWidth="2" /><path d="M3 9h18M9 21V9" strokeWidth="2" strokeLinecap="round" /></svg>} legend={[{ color: "#10b981", label: "Qualified" }, { color: "#f87171", label: "Non-Qualified" }, { color: "#c084fc", label: "Pending" }]}>
                                    <div style={{ position: "relative", height: 260 }}><Bar data={barSourceStacked} options={{ ...commonBarOpts, scales: { x: { stacked: true, ticks: { font: chartFont, color: "#64748b" }, grid: { display: false }, border: { display: false } }, y: { stacked: true, ticks: { font: chartFont, color: "#64748b" }, grid: { color: "#f1f5f9" }, border: { display: false } } }, barPercentage: 0.6, categoryPercentage: 0.7 }} /></div>
                                </ChartCard>
                                <ChartCard title="Overall Lead Status Split" subtitle={`${kpi.responses} total finalized responses — qualification outcome`} iconBg="#fce7f3" iconColor="#be185d" icon={<svg width={12} height={12} fill="none" viewBox="0 0 24 24" stroke="currentColor"><circle cx="12" cy="12" r="10" strokeWidth="2" /><path d="M12 8v4l3 3" strokeWidth="2" strokeLinecap="round" /></svg>}>
                                    <div style={{ height: 190, display: "flex", alignItems: "center", justifyContent: "center" }}><div style={{ maxWidth: 180, width: "100%" }}><Doughnut data={{ labels: ["Qualified", "Non-Qualified"], datasets: [{ data: [kpi.qualified, kpi.dead], backgroundColor: ["#10b981", "#f87171"], borderWidth: 2, borderColor: "#fff", hoverOffset: 6 }] }} options={{ responsive: true, maintainAspectRatio: true, cutout: "65%", plugins: { legend: { display: false }, tooltip: { callbacks: { label: (ctx: any) => `${ctx.label}: ${ctx.parsed}` } } } }} /></div></div>
                                    <ChartLegend items={[
                                        { color: "#10b981", label: `Qualified — ${kpi.qualified} (${fmtPct(kpi.qualified, kpi.responses)}%)`, round: true },
                                        { color: "#f87171", label: `Non-Qualified — ${kpi.dead} (${fmtPct(kpi.dead, kpi.responses)}%)`, round: true },
                                    ]} />
                                </ChartCard>
                            </div>
                        </div>
                    )}
                </div>
            </div>

        </div>
    );
}
