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 { 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 { h as Printer } 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 TabsTrigger, n as TabsContent, r as TabsList, t as Tabs } from "./tabs-CCJRliUM.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/risk-centre-BVz5Pney.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
async function fetchAll(year, month, level) {
	const pageSize = 1e3;
	let from = 0;
	const out = [];
	while (true) {
		const { data, error } = await supabase.from("fact_progress").select("division,aen,sse,level,item_sr_no,item_name,cum_scope,cum_progress,weightage,month,year").eq("year", year).eq("month", month).eq("level", level).range(from, from + pageSize - 1);
		if (error) throw error;
		const rows = data ?? [];
		out.push(...rows);
		if (rows.length < pageSize) break;
		from += pageSize;
	}
	return out;
}
function useFacts(year, month, level) {
	return useQuery({
		queryKey: [
			"rc-facts",
			year,
			month,
			level
		],
		queryFn: () => fetchAll(year, month, level)
	});
}
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";
var riskWeightMatches = (w, f) => {
	if (f === "ALL") return w > 0;
	if (f === "HIGH") return w >= 1;
	if (f === "MED") return Math.abs(w - .5) < 1e-6;
	if (f === "LOW") return Math.abs(w - .25) < 1e-6;
	return true;
};
function RiskCentre() {
	const [fy, setFy] = (0, import_react.useState)(fyForDate());
	const [month, setMonth] = (0, import_react.useState)((/* @__PURE__ */ new Date()).getMonth() + 1);
	const [risk, setRisk] = (0, import_react.useState)("ALL");
	const [itemSr, setItemSr] = (0, import_react.useState)("ALL");
	const [tab, setTab] = (0, import_react.useState)("AEN");
	const year = yearForFyMonth(fy, month);
	const { data: items = [] } = useItems();
	const { data: sseFacts = [], isLoading: ls } = useFacts(year, month, "SSE");
	const wMap = (0, import_react.useMemo)(() => new Map(items.map((i) => [i.sr_no, i.weightage ?? 0])), [items]);
	const orderedItems = (0, import_react.useMemo)(() => {
		return [...items].sort((a, b) => a.sort_order - b.sort_order).filter((i) => riskWeightMatches(i.weightage ?? 0, risk));
	}, [items, risk]);
	const filtered = (0, import_react.useMemo)(() => {
		return sseFacts.filter((r) => {
			const w = wMap.get(r.item_sr_no) ?? r.weightage ?? 0;
			if (itemSr !== "ALL") {
				if (r.item_sr_no !== itemSr) return false;
			} else if (!riskWeightMatches(w, risk)) return false;
			return true;
		});
	}, [
		sseFacts,
		wMap,
		itemSr,
		risk
	]);
	const aggregate = (keyFn, extra) => {
		const m = /* @__PURE__ */ new Map();
		for (const r of filtered) {
			const w = wMap.get(r.item_sr_no) ?? r.weightage ?? 0;
			if (w <= 0) continue;
			const k = keyFn(r);
			if (!m.has(k)) m.set(k, {
				key: k,
				wScope: 0,
				wProg: 0,
				scope: 0,
				prog: 0,
				risk: 0,
				...extra?.(r) ?? {}
			});
			const g = m.get(k);
			g.wScope += (r.cum_scope || 0) * w;
			g.wProg += (r.cum_progress || 0) * w;
			g.scope += r.cum_scope || 0;
			g.prog += r.cum_progress || 0;
		}
		return Array.from(m.values()).map((r) => ({
			...r,
			risk: r.wScope > 0 ? r.wProg / r.wScope * 100 : 0
		})).sort((a, b) => b.risk - a.risk);
	};
	const divRows = (0, import_react.useMemo)(() => aggregate((r) => r.division), [filtered, wMap]);
	const aenRows = (0, import_react.useMemo)(() => aggregate((r) => `${r.division} · ${r.aen}`, (r) => ({
		division: r.division,
		aen: r.aen
	})), [filtered, wMap]);
	const sseRows = (0, import_react.useMemo)(() => aggregate((r) => `${r.division} · ${r.aen} · ${r.sse ?? "—"}`, (r) => ({
		division: r.division,
		aen: r.aen
	})), [filtered, wMap]);
	const selectedItemName = itemSr !== "ALL" ? items.find((i) => i.sr_no === itemSr)?.name : null;
	const riskLabel = risk === "ALL" ? "All Risks" : risk === "HIGH" ? "High (1.00)" : risk === "MED" ? "Medium (0.50)" : "Low (0.25)";
	const monthLabel = FY_MONTHS.find((m) => m.v === month)?.label ?? "";
	const printPdf = () => window.print();
	const activeRows = tab === "AEN" ? aenRows : sseRows;
	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; }
          #rc-print, #rc-print * { visibility: visible; }
          #rc-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: "Risk Command Centre",
					subtitle: "Division cards + combined AEN / SSE ranking by Risk Weighted Compliance."
				})
			}),
			/* @__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", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
							className: "text-xs text-muted-foreground mb-1",
							children: "Risk Category"
						}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Select, {
							value: risk,
							onValueChange: (v) => {
								setRisk(v);
								setItemSr("ALL");
							},
							disabled: itemSr !== "ALL",
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectValue, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectContent, { children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "ALL",
									children: "All Risks"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "HIGH",
									children: "High Risk (1.00)"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "MED",
									children: "Medium Risk (0.50)"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
									value: "LOW",
									children: "Low Risk (0.25)"
								})
							] })]
						})] }),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
							className: "text-xs text-muted-foreground mb-1",
							children: "Item"
						}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Select, {
							value: itemSr,
							onValueChange: setItemSr,
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectTrigger, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectValue, {}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectContent, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(SelectItem, {
								value: "ALL",
								children: "All Items"
							}), orderedItems.map((i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(SelectItem, {
								value: i.sr_no,
								children: [
									i.sr_no,
									". ",
									i.name
								]
							}, i.sr_no))] })]
						})] })
					]
				})
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				id: "rc-print",
				className: "space-y-4",
				children: [
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "hidden print:block mb-3",
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
							className: "text-lg font-semibold",
							children: "Risk Command Centre — Ranking Report"
						}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "text-xs text-muted-foreground",
							children: [
								"FY ",
								fy,
								" · ",
								monthLabel,
								" · Risk: ",
								riskLabel,
								selectedItemName ? ` · Item: ${selectedItemName}` : ""
							]
						})]
					}),
					/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						className: "flex items-center justify-between mb-2",
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
							className: "text-sm font-semibold",
							children: "Division Ranking"
						}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "flex gap-2 text-xs text-muted-foreground no-print",
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
								variant: "outline",
								children: ["Risk: ", riskLabel]
							}), selectedItemName && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
								variant: "outline",
								children: ["Item: ", selectedItemName]
							})]
						})]
					}), ls ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "text-sm text-muted-foreground py-6 text-center",
						children: "Loading…"
					}) : divRows.length === 0 ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "text-sm text-muted-foreground py-6 text-center",
						children: "No data for the selected filters."
					}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
						className: "grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3",
						children: divRows.map((r, i) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, {
							className: `border ${zoneBg(r.risk)}`,
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardHeader, {
								className: "pb-2 flex flex-row items-center justify-between",
								children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardTitle, {
									className: "text-base",
									children: r.key
								}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
									variant: "outline",
									children: ["#", i + 1]
								})]
							}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
								className: "space-y-1 text-sm",
								children: [
									/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
										className: "flex justify-between",
										children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
											className: "text-muted-foreground",
											children: "Cum. Scope"
										}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
											className: "font-medium",
											children: num(r.scope, 2)
										})]
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
										className: "flex justify-between",
										children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
											className: "text-muted-foreground",
											children: "Cum. Progress"
										}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
											className: "font-medium",
											children: num(r.prog, 2)
										})]
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
										className: "flex justify-between items-center pt-1 border-t mt-2",
										children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
											className: "text-muted-foreground",
											children: "Risk Compliance"
										}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
											className: `text-lg font-bold ${zoneClass(r.risk)}`,
											children: [num(r.risk), "%"]
										})]
									})
								]
							})]
						}, r.key))
					})] }),
					/* @__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.jsx)(CardTitle, {
								className: "text-base",
								children: "Combined Ranking"
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
								className: "flex items-center gap-2 no-print",
								children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Tabs, {
									value: tab,
									onValueChange: (v) => setTab(v),
									children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TabsList, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TabsTrigger, {
										value: "AEN",
										children: [
											"All AENs (",
											aenRows.length,
											")"
										]
									}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TabsTrigger, {
										value: "SSE",
										children: [
											"All SSEs (",
											sseRows.length,
											")"
										]
									})] })
								}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
									size: "sm",
									variant: "outline",
									onClick: printPdf,
									children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Printer, { className: "h-4 w-4 mr-1" }), " Print / PDF"]
								})]
							}),
							/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
								className: "hidden print:block text-xs",
								children: tab === "AEN" ? "All AENs" : "All SSEs"
							})
						]
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardContent, {
						className: "p-0",
						children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Tabs, {
							value: tab,
							children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TabsContent, {
								value: tab,
								className: "mt-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: "Division" }),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "AEN" }),
									tab === "SSE" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "SSE" }),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
										className: "text-right",
										children: "Cum. Scope"
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
										className: "text-right",
										children: "Cum. Progress"
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
										className: "text-right",
										children: "Risk Compliance %"
									})
								] }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableBody, { children: [
									ls && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										colSpan: 7,
										className: "text-center py-8 text-muted-foreground",
										children: "Loading…"
									}) }),
									!ls && activeRows.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										colSpan: 7,
										className: "text-center py-8 text-muted-foreground",
										children: "No data."
									}) }),
									activeRows.map((r, i) => {
										const parts = r.key.split(" · ");
										const div = r.division ?? parts[0];
										const aen = r.aen ?? parts[1];
										const sse = parts[2];
										return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
											/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
												variant: "outline",
												children: ["#", i + 1]
											}) }),
											/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
												className: "font-medium",
												children: div
											}),
											/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: aen }),
											tab === "SSE" && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: sse }),
											/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
												className: "text-right",
												children: num(r.scope, 2)
											}),
											/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
												className: "text-right",
												children: num(r.prog, 2)
											}),
											/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableCell, {
												className: `text-right font-semibold ${zoneClass(r.risk)}`,
												children: [num(r.risk), "%"]
											})
										] }, r.key);
									})
								] })] })
							})
						})
					})] })
				]
			})
		]
	});
}
//#endregion
export { RiskCentre as component };
