import { n as __toESM } from "../_runtime.mjs";
import { I as require_jsx_runtime } from "../_libs/@radix-ui/react-alert-dialog+[...].mjs";
import { t as PageHeader } from "./page-header-BE1EG5aP.mjs";
import { t as cn } from "./utils-C_uf36nf.mjs";
import { u as require_react } from "../_libs/@floating-ui/react-dom+[...].mjs";
import { i as CardTitle, n as CardContent, r as CardHeader, t as Card } from "./card-BXjpJ96D.mjs";
import { a as TableHead, n as TableBody, o as TableHeader, r as TableCell, s as TableRow, t as Table } from "./table-BAceZcga.mjs";
import { t as supabase } from "./client-_1GYITl-.mjs";
import { t as useQuery } from "../_libs/tanstack__react-query.mjs";
import { n as useItems } from "./data-hooks--e_NaUze.mjs";
import { t as Badge } from "./badge-D1Dupn2y.mjs";
import { t as Button } from "./button-BLZ6ednA.mjs";
import { M as ArrowLeft, O as ChevronRight, a as Trophy, h as Printer, o as TriangleAlert, s as TrendingUp, u as Target } from "../_libs/lucide-react.mjs";
import { a as SelectValue, i as SelectTrigger, n as SelectContent, r as SelectItem, t as Select } from "./select-CYB-gyWu.mjs";
import { i as yearForFyMonth, n as fyForDate, r as fyList, t as FY_MONTHS } from "./fy-C7Q3MBgO.mjs";
//#region node_modules/.nitro/vite/services/ssr/assets/dashboard-DgUzJyX4.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
async function fetchAll(year, month) {
	const pageSize = 1e3;
	let from = 0;
	const out = [];
	while (true) {
		const { data, error } = await supabase.from("fact_progress").select("division,aen,sse,item_sr_no,item_name,cum_scope,cum_progress,progress_month,weightage,month,year").eq("year", year).eq("month", month).eq("level", "SSE").range(from, from + pageSize - 1);
		if (error) throw error;
		const rows = data ?? [];
		out.push(...rows);
		if (rows.length < pageSize) break;
		from += pageSize;
	}
	return out;
}
var num = (n, d = 1) => Number.isFinite(n) ? n.toFixed(d) : "0.0";
var zoneClass = (c) => c >= 90 ? "text-emerald-600" : c >= 70 ? "text-yellow-600" : c >= 50 ? "text-orange-600" : "text-red-600";
var zoneBg = (c) => c >= 90 ? "border-emerald-500/40 bg-emerald-500/5" : c >= 70 ? "border-yellow-500/40 bg-yellow-500/5" : c >= 50 ? "border-orange-500/40 bg-orange-500/5" : "border-red-500/40 bg-red-500/5";
function Dashboard() {
	const [fy, setFy] = (0, import_react.useState)(fyForDate());
	const [month, setMonth] = (0, import_react.useState)((/* @__PURE__ */ new Date()).getMonth() + 1);
	const [drill, setDrill] = (0, import_react.useState)({ level: "DIV" });
	const year = yearForFyMonth(fy, month);
	const { data: items = [] } = useItems();
	const wMap = (0, import_react.useMemo)(() => new Map(items.map((i) => [i.sr_no, i.weightage ?? 0])), [items]);
	const { data: facts = [], isLoading } = useQuery({
		queryKey: [
			"dash-facts",
			year,
			month
		],
		queryFn: () => fetchAll(year, month)
	});
	const aggregate = (keyFn, filter) => {
		const m = /* @__PURE__ */ new Map();
		for (const r of facts) {
			if (filter && !filter(r)) continue;
			const w = wMap.get(r.item_sr_no) ?? r.weightage ?? 0;
			if (w <= 0) continue;
			const k = keyFn(r);
			if (!m.has(k.key)) m.set(k.key, {
				...k,
				target: 0,
				progress: 0,
				scope: 0,
				progRaw: 0,
				compliance: 0
			});
			const g = m.get(k.key);
			const monthlyTarget = (r.cum_scope || 0) / 12;
			const monthlyProg = r.progress_month || 0;
			g.target += monthlyTarget * w;
			g.progress += monthlyProg * w;
			g.scope += monthlyTarget;
			g.progRaw += monthlyProg;
		}
		return Array.from(m.values()).map((r) => ({
			...r,
			compliance: r.target > 0 ? r.progress / r.target * 100 : 0
		})).sort((a, b) => b.compliance - a.compliance);
	};
	const divRows = (0, import_react.useMemo)(() => aggregate((r) => ({
		key: r.division,
		label: r.division,
		division: r.division
	})), [facts, wMap]);
	const aenRows = (0, import_react.useMemo)(() => drill.division ? aggregate((r) => ({
		key: `${r.division}·${r.aen}`,
		label: r.aen,
		division: r.division,
		aen: r.aen
	}), (r) => r.division === drill.division) : [], [
		facts,
		wMap,
		drill.division
	]);
	const sseRows = (0, import_react.useMemo)(() => drill.division && drill.aen ? aggregate((r) => ({
		key: `${r.division}·${r.aen}·${r.sse}`,
		label: r.sse ?? "—",
		division: r.division,
		aen: r.aen,
		sse: r.sse
	}), (r) => r.division === drill.division && r.aen === drill.aen) : [], [
		facts,
		wMap,
		drill.division,
		drill.aen
	]);
	const bestWorst = (0, import_react.useMemo)(() => {
		const sorted = [...divRows].sort((a, b) => b.compliance - a.compliance);
		return {
			best: sorted[0],
			worst: sorted[sorted.length - 1]
		};
	}, [divRows]);
	const overall = (0, import_react.useMemo)(() => {
		const t = divRows.reduce((s, r) => s + r.target, 0);
		const p = divRows.reduce((s, r) => s + r.progress, 0);
		return {
			target: t,
			progress: p,
			compliance: t > 0 ? p / t * 100 : 0,
			scope: divRows.reduce((s, r) => s + r.scope, 0),
			progRaw: divRows.reduce((s, r) => s + r.progRaw, 0)
		};
	}, [divRows]);
	const monthLabel = FY_MONTHS.find((m) => m.v === month)?.label ?? "";
	const activeRows = drill.level === "DIV" ? divRows : drill.level === "AEN" ? aenRows : sseRows;
	const rankedRows = (0, import_react.useMemo)(() => [...activeRows].sort((a, b) => b.compliance - a.compliance || a.label.localeCompare(b.label)), [activeRows]);
	const levelTitle = drill.level === "DIV" ? "Divisions" : drill.level === "AEN" ? `AENs in ${drill.division}` : `SSEs under ${drill.aen} (${drill.division})`;
	const modeLabel = "Monthly Risk Compliance Ranking";
	const printPdf = () => window.print();
	const openDivision = (r) => setDrill({
		level: "AEN",
		division: r.division
	});
	const openAen = (r) => setDrill({
		level: "SSE",
		division: r.division,
		aen: r.aen
	});
	const back = () => setDrill((d) => d.level === "SSE" ? {
		level: "AEN",
		division: d.division
	} : d.level === "AEN" ? { level: "DIV" } : d);
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "p-6 max-w-[1400px] mx-auto space-y-4",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { children: `
        @media print {
          body * { visibility: hidden; }
          #ex-print, #ex-print * { visibility: visible; }
          #ex-print { position: absolute; left: 0; top: 0; width: 100%; padding: 16px; }
          .no-print { display: none !important; }
        }
      ` }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
				className: "no-print",
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageHeader, {
					title: "Executive Dashboard",
					subtitle: "Rank is always based on Monthly Risk Compliance %, highest to lowest."
				})
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, {
				className: "no-print",
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
					className: "p-4 grid grid-cols-2 md:grid-cols-4 gap-3",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "text-xs text-muted-foreground mb-1",
						children: "Financial Year"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Select, {
						value: fy,
						onValueChange: setFy,
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectValue, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectContent, { children: fyList(6).map((f) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectItem, {
							value: f,
							children: ["FY ", f]
						}, f)) })]
					})] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "text-xs text-muted-foreground mb-1",
						children: "Month"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Select, {
						value: String(month),
						onValueChange: (v) => setMonth(Number(v)),
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectValue, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectContent, { children: FY_MONTHS.map((m) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
							value: String(m.v),
							children: m.label
						}, m.v)) })]
					})] })]
				})
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 no-print",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(KpiTile, {
						title: "Monthly Target",
						value: num(overall.target, 1),
						sub: `Weighted · raw sum ${num(overall.scope, 1)}`,
						icon: Target,
						onClick: () => setDrill({ level: "DIV" })
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(KpiTile, {
						title: "Monthly Risk Compliance",
						value: `${num(overall.compliance)}%`,
						sub: `Progress ${num(overall.progress, 1)} / Target ${num(overall.target, 1)}`,
						icon: TrendingUp,
						tone: overall.compliance >= 70 ? "good" : overall.compliance >= 50 ? "warn" : "bad",
						active: drill.level === "DIV",
						onClick: () => setDrill({ level: "DIV" })
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(KpiTile, {
						title: "Best Division",
						value: bestWorst.best?.division ?? "—",
						sub: bestWorst.best ? `${num(bestWorst.best.compliance)}% compliance` : "No data",
						icon: Trophy,
						tone: "good",
						active: !!bestWorst.best && drill.level === "AEN" && drill.division === bestWorst.best.division,
						onClick: () => bestWorst.best && setDrill({
							level: "AEN",
							division: bestWorst.best.division
						})
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsx)(KpiTile, {
						title: "Poorest Division",
						value: bestWorst.worst?.division ?? "—",
						sub: bestWorst.worst ? `${num(bestWorst.worst.compliance)}% compliance` : "No data",
						icon: TriangleAlert,
						tone: "bad",
						active: !!bestWorst.worst && drill.level === "AEN" && drill.division === bestWorst.worst.division,
						onClick: () => bestWorst.worst && setDrill({
							level: "AEN",
							division: bestWorst.worst.division
						})
					})
				]
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				id: "ex-print",
				className: "space-y-3",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "hidden print:block mb-3",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "text-lg font-semibold",
						children: ["Executive Dashboard — ", modeLabel]
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "text-xs text-muted-foreground",
						children: [
							"FY ",
							fy,
							" · ",
							monthLabel,
							" · ",
							levelTitle
						]
					})]
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardHeader, {
					className: "pb-2 flex flex-row items-center justify-between",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "flex items-center gap-2",
						children: [drill.level !== "DIV" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
							variant: "ghost",
							size: "sm",
							onClick: back,
							className: "no-print",
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowLeft, { className: "h-4 w-4 mr-1" }), " Back"]
						}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardTitle, {
							className: "text-base",
							children: levelTitle
						}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "text-xs text-muted-foreground mt-0.5",
							children: [
								modeLabel,
								" · FY ",
								fy,
								" · ",
								monthLabel,
								drill.level !== "DIV" && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [" · ", /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
									className: "inline-flex items-center gap-1",
									children: [drill.division, drill.aen && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [
										" ",
										/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "h-3 w-3 inline" }),
										" ",
										drill.aen
									] })]
								})] })
							]
						})] })]
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
						size: "sm",
						variant: "outline",
						onClick: printPdf,
						className: "no-print",
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Printer, { className: "h-4 w-4 mr-1" }), " Print / PDF"]
					})]
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardContent, {
					className: "p-0",
					children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
							className: "w-16",
							children: "Rank"
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: drill.level === "DIV" ? "Division" : drill.level === "AEN" ? "AEN" : "SSE" }),
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
							className: "text-right",
							children: "Monthly Target (weighted)"
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
							className: "text-right",
							children: "Monthly Progress (weighted)"
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
							className: "text-right",
							children: "Raw Target"
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
							className: "text-right",
							children: "Raw Progress"
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
							className: "text-right",
							children: "Compliance %"
						}),
						drill.level !== "SSE" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { className: "w-10 no-print" })
					] }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableBody, { children: [
						isLoading && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
							colSpan: 8,
							className: "text-center py-8 text-muted-foreground",
							children: "Loading…"
						}) }),
						!isLoading && rankedRows.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
							colSpan: 8,
							className: "text-center py-8 text-muted-foreground",
							children: "No data."
						}) }),
						rankedRows.map((r, i) => {
							const clickable = drill.level !== "SSE";
							const onClick = drill.level === "DIV" ? () => openDivision(r) : drill.level === "AEN" ? () => openAen(r) : void 0;
							return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, {
								className: cn(clickable && "cursor-pointer hover:bg-muted/40"),
								onClick,
								children: [
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
										variant: "outline",
										className: zoneBg(r.compliance),
										children: ["#", i + 1]
									}) }),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "font-medium",
										children: r.label
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right",
										children: num(r.target, 2)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right",
										children: num(r.progress, 2)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right text-muted-foreground",
										children: num(r.scope, 1)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right text-muted-foreground",
										children: num(r.progRaw, 1)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableCell, {
										className: cn("text-right font-semibold", zoneClass(r.compliance)),
										children: [num(r.compliance), "%"]
									}),
									drill.level !== "SSE" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "no-print",
										children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ChevronRight, { className: "h-4 w-4 text-muted-foreground" })
									})
								]
							}, r.key);
						})
					] })] })
				})] })]
			})
		]
	});
}
function KpiTile({ title, value, sub, icon: Icon, tone, active, onClick }) {
	const toneRing = tone === "good" ? "border-emerald-500/40" : tone === "warn" ? "border-yellow-500/40" : tone === "bad" ? "border-red-500/40" : "border-border";
	const toneIcon = tone === "good" ? "bg-emerald-500/15 text-emerald-600" : tone === "warn" ? "bg-yellow-500/15 text-yellow-700" : tone === "bad" ? "bg-red-500/15 text-red-600" : "bg-muted text-foreground";
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, {
		onClick,
		className: cn("transition border cursor-pointer hover:shadow-md hover:-translate-y-0.5", toneRing, active && "ring-2 ring-primary/40"),
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardHeader, {
			className: "pb-2 flex flex-row items-center justify-between space-y-0",
			children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardTitle, {
				className: "text-xs font-medium text-muted-foreground uppercase tracking-wide",
				children: title
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
				className: cn("grid h-8 w-8 place-items-center rounded-md", toneIcon),
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Icon, { className: "h-4 w-4" })
			})]
		}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
			className: "text-2xl font-semibold",
			children: value
		}), sub && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
			className: "mt-1 text-xs text-muted-foreground",
			children: sub
		})] })]
	});
}
//#endregion
export { Dashboard as component };
