import { n as __toESM } from "../_runtime.mjs";
import { I as require_jsx_runtime, d as DialogClose, f as DialogContent$1, g as DialogTitle$1, h as DialogPortal$1, m as DialogOverlay$1, p as DialogDescription$1, u as Dialog$1 } 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, i as TableFooter, n as TableBody, o as TableHeader, r as TableCell, s as TableRow, t as Table } from "./table-BAceZcga.mjs";
import { n as useItems, r as useLatestFacts } from "./data-hooks--e_NaUze.mjs";
import { t as Badge } from "./badge-D1Dupn2y.mjs";
import { t as Button } from "./button-BLZ6ednA.mjs";
import { t as Input } from "./input-B8Q2ztVi.mjs";
import { C as FileSpreadsheet, h as Printer, p as Search, t as X } from "../_libs/lucide-react.mjs";
import { o as zoneClass, r as compliancePct } from "./calculations-JyW9rCxF.mjs";
import { n as utils, r as writeFileSync } from "../_libs/xlsx.mjs";
//#region node_modules/.nitro/vite/services/ssr/assets/item-risk-BepXu-lC.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
var Dialog = Dialog$1;
var DialogPortal = DialogPortal$1;
var DialogOverlay = import_react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogOverlay$1, {
	ref,
	className: cn("fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0", className),
	...props
}));
DialogOverlay.displayName = DialogOverlay$1.displayName;
var DialogContent = import_react.forwardRef(({ className, children, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogPortal, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogOverlay, {}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent$1, {
	ref,
	className: cn("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 sm:rounded-lg", className),
	...props,
	children: [children, /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogClose, {
		className: "absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background cursor-pointer transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(X, { className: "h-4 w-4" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
			className: "sr-only",
			children: "Close"
		})]
	})]
})] }));
DialogContent.displayName = DialogContent$1.displayName;
var DialogHeader = ({ className, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
	className: cn("flex flex-col space-y-1.5 text-center sm:text-left", className),
	...props
});
DialogHeader.displayName = "DialogHeader";
var DialogFooter = ({ className, ...props }) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
	className: cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className),
	...props
});
DialogFooter.displayName = "DialogFooter";
var DialogTitle = import_react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogTitle$1, {
	ref,
	className: cn("text-lg font-semibold leading-none tracking-tight", className),
	...props
}));
DialogTitle.displayName = DialogTitle$1.displayName;
var DialogDescription = import_react.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogDescription$1, {
	ref,
	className: cn("text-sm text-muted-foreground", className),
	...props
}));
DialogDescription.displayName = DialogDescription$1.displayName;
var printCss = `@media print {
  body * { visibility: hidden; }
  #print-area, #print-area * { visibility: visible; }
  #print-area { position: absolute; left: 0; top: 0; width: 100%; }
  .no-print { display: none !important; }
}`;
function ItemRisk() {
	const { data: facts = [] } = useLatestFacts("AEN");
	const { data: items = [] } = useItems();
	const [q, setQ] = (0, import_react.useState)("");
	const [selected, setSelected] = (0, import_react.useState)(null);
	const nameMap = (0, import_react.useMemo)(() => new Map(items.map((i) => [i.sr_no, i.name])), [items]);
	const filtered = (0, import_react.useMemo)(() => {
		const agg = /* @__PURE__ */ new Map();
		for (const r of facts) {
			if (!agg.has(r.item_sr_no)) agg.set(r.item_sr_no, {
				cumScope: 0,
				cumProg: 0,
				unit: r.unit
			});
			const g = agg.get(r.item_sr_no);
			g.cumScope += r.cum_scope;
			g.cumProg += r.cum_progress;
			if (!g.unit && r.unit) g.unit = r.unit;
		}
		return [...items].filter((it) => it.weightage != null && it.unit != null).sort((a, b) => a.sort_order - b.sort_order).map((it, i) => {
			const g = agg.get(it.sr_no) ?? {
				cumScope: 0,
				cumProg: 0,
				unit: null
			};
			const compliance = g.cumScope > 0 ? g.cumProg / g.cumScope * 100 : 0;
			return {
				sr_no: it.sr_no,
				name: it.name,
				unit: it.unit ?? g.unit,
				weight: it.weightage ?? 0,
				cumScope: g.cumScope,
				cumProg: g.cumProg,
				compliance,
				rank: i + 1
			};
		});
	}, [facts, items]).filter((r) => !q || r.name.toLowerCase().includes(q.toLowerCase()) || r.sr_no.toLowerCase().includes(q.toLowerCase()));
	const drill = (0, import_react.useMemo)(() => {
		if (!selected) return [];
		return facts.filter((r) => r.item_sr_no === selected).map((r) => ({
			id: r.id,
			division: r.division,
			aen: r.aen,
			cum_scope: r.cum_scope,
			cum_progress: r.cum_progress,
			net_balance: r.net_balance,
			compliance: compliancePct(r.cum_progress, r.cum_scope)
		})).sort((a, b) => a.compliance - b.compliance);
	}, [facts, selected]);
	const exportMain = () => {
		const rows = filtered.map((r) => ({
			Rank: r.rank,
			"Sr No": r.sr_no,
			Item: r.name,
			Unit: r.unit ?? "",
			Weight: r.weight,
			"Cum Scope": r.cumScope,
			"Cum Progress": r.cumProg,
			"Compliance %": +r.compliance.toFixed(2)
		}));
		const ws = utils.json_to_sheet(rows);
		const wb = utils.book_new();
		utils.book_append_sheet(wb, ws, "Item Risk");
		writeFileSync(wb, `item-risk-${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.xlsx`);
	};
	const exportDrill = () => {
		if (!selected) return;
		const rows = drill.map((r) => ({
			Division: r.division,
			AEN: r.aen,
			"Cum Scope": r.cum_scope,
			"Cum Progress": r.cum_progress,
			"Net Balance": r.net_balance,
			"Compliance %": +r.compliance.toFixed(2)
		}));
		const ws = utils.json_to_sheet(rows);
		const wb = utils.book_new();
		utils.book_append_sheet(wb, ws, "Breakdown");
		writeFileSync(wb, `item-${selected}-breakdown.xlsx`);
	};
	const printDrill = () => {
		const el = document.getElementById("drill-print-area");
		if (!el) return;
		const w = window.open("", "_blank", "width=900,height=700");
		if (!w) return;
		w.document.write(`<html><head><title>Item ${selected}</title>
      <style>body{font-family:system-ui;padding:20px}table{border-collapse:collapse;width:100%}th,td{border:1px solid #ccc;padding:6px 8px;font-size:12px;text-align:left}th{background:#f3f4f6}</style>
      </head><body>${el.innerHTML}</body></html>`);
		w.document.close();
		w.focus();
		w.print();
	};
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "p-6 max-w-[1600px] mx-auto",
		children: [
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)("style", { children: printCss }),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageHeader, {
				title: "Item Risk Dashboard",
				subtitle: "All items summed across divisions · in AEN sheet order."
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, {
				className: "mb-4 no-print",
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardContent, {
					className: "p-4 flex gap-3 items-center",
					children: [
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "relative flex-1",
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Search, { className: "absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground" }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Input, {
								value: q,
								onChange: (e) => setQ(e.target.value),
								placeholder: "Search item…",
								className: "pl-9"
							})]
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
							variant: "outline",
							onClick: () => window.print(),
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Printer, { className: "h-4 w-4 mr-2" }), "Print"]
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
							variant: "outline",
							onClick: exportMain,
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileSpreadsheet, { className: "h-4 w-4 mr-2" }), "Excel"]
						})
					]
				})
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
				id: "print-area",
				children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "hidden print:block mb-3",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("h1", {
						className: "text-lg font-bold",
						children: "Item Risk Dashboard"
					}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("p", {
						className: "text-xs",
						children: "Summed across all divisions · in AEN sheet order"
					})]
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Card, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(CardTitle, { children: [
					"Items by compliance (",
					filtered.length,
					")"
				] }) }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardContent, {
					className: "p-0 max-h-[70vh] overflow-auto print:max-h-none print:overflow-visible",
					children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Table, { children: [
						/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHeader, {
							className: "sticky top-0 bg-card z-10",
							children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "Rank" }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "Item" }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "Unit" }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
									className: "text-right",
									children: "Weight"
								}),
								/* @__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: "Compliance %"
								})
							] })
						}),
						/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableBody, { children: [filtered.map((r) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, {
							className: "cursor-pointer",
							onClick: () => setSelected(r.sr_no),
							children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
									variant: "outline",
									children: ["#", r.rank]
								}) }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableCell, {
									className: "max-w-[400px]",
									children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
										className: "text-xs text-muted-foreground",
										children: r.sr_no
									}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
										className: "truncate",
										children: r.name
									})]
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: r.unit ?? "—" }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: r.weight.toFixed(2)
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: r.cumScope.toFixed(0)
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: r.cumProg.toFixed(0)
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
										className: `inline-block rounded px-2 py-0.5 text-xs ${zoneClass(r.compliance)}`,
										children: [r.compliance.toFixed(1), "%"]
									})
								})
							]
						}, r.sr_no)), filtered.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
							colSpan: 7,
							className: "text-center text-sm text-muted-foreground py-8",
							children: "No items."
						}) })] }),
						filtered.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableFooter, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, {
							className: "font-semibold bg-muted/50",
							children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									colSpan: 4,
									children: "Total"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: filtered.reduce((s, r) => s + r.cumScope, 0).toFixed(0)
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: filtered.reduce((s, r) => s + r.cumProg, 0).toFixed(0)
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {})
							]
						}) })
					] })
				})] })]
			}),
			/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Dialog, {
				open: !!selected,
				onOpenChange: (o) => {
					if (!o) setSelected(null);
				},
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogContent, {
					className: "max-w-4xl",
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(DialogHeader, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DialogTitle, {
						className: "flex items-center justify-between gap-3",
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: [
							selected,
							" — ",
							nameMap.get(selected ?? "") ?? ""
						] }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
							className: "flex gap-2",
							children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
								size: "sm",
								variant: "outline",
								onClick: printDrill,
								children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Printer, { className: "h-4 w-4 mr-1" }), "Print"]
							}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
								size: "sm",
								variant: "outline",
								onClick: exportDrill,
								children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileSpreadsheet, { className: "h-4 w-4 mr-1" }), "Excel"]
							})]
						})]
					}) }), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
						id: "drill-print-area",
						className: "max-h-[60vh] overflow-auto",
						children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("h2", {
							style: {
								fontSize: 14,
								fontWeight: 600,
								marginBottom: 8
							},
							children: [
								selected,
								" — ",
								nameMap.get(selected ?? "") ?? "",
								" · division/AEN breakdown"
							]
						}), /* @__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, { children: "Division" }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, { children: "AEN" }),
								/* @__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: "Net Balance"
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableHead, {
									className: "text-right",
									children: "Compliance %"
								})
							] }) }),
							/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableBody, { children: [drill.map((r) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, { children: [
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: r.division }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, { children: r.aen }),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: r.cum_scope
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: r.cum_progress
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: r.net_balance
								}),
								/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
									className: "text-right",
									children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
										className: `inline-block rounded px-2 py-0.5 text-xs ${zoneClass(r.compliance)}`,
										children: [r.compliance.toFixed(1), "%"]
									})
								})
							] }, r.id)), drill.length === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableRow, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
								colSpan: 6,
								className: "text-center text-sm text-muted-foreground py-6",
								children: "No data for this item."
							}) })] }),
							drill.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableFooter, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(TableRow, {
								className: "font-semibold bg-muted/50",
								children: [
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										colSpan: 2,
										children: "Total"
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right",
										children: drill.reduce((s, r) => s + Number(r.cum_scope || 0), 0).toFixed(0)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right",
										children: drill.reduce((s, r) => s + Number(r.cum_progress || 0), 0).toFixed(0)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {
										className: "text-right",
										children: drill.reduce((s, r) => s + Number(r.net_balance || 0), 0).toFixed(0)
									}),
									/* @__PURE__ */ (0, import_jsx_runtime.jsx)(TableCell, {})
								]
							}) })
						] })]
					})]
				})
			})
		]
	});
}
//#endregion
export { ItemRisk as component };
