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 { n as CardContent, t as Card } from "./card-BXjpJ96D.mjs";
import { t as supabase } from "./client-_1GYITl-.mjs";
import { r as useQueryClient, t as useQuery } from "../_libs/tanstack__react-query.mjs";
import { t as useAuth } from "./use-auth-bumQAdtQ.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 { n as toast } from "../_libs/sonner.mjs";
import { E as Download, M as ArrowLeft, g as Pencil, h as Printer, m as Save, p as Search, t as X, w as FileDown } from "../_libs/lucide-react.mjs";
import { n as MONTHS } from "./calculations-JyW9rCxF.mjs";
import { g as Link } from "../_libs/@tanstack/react-router+[...].mjs";
import { t as Route } from "./upload._division._aen._uploadId-BfhsEH2w.mjs";
//#region node_modules/.nitro/vite/services/ssr/assets/upload._division._aen._uploadId-oMccpfi6.js
var import_react = /* @__PURE__ */ __toESM(require_react());
var import_jsx_runtime = require_jsx_runtime();
function ExcelViewer({ html, canEdit, storagePath, fileName, onSave }) {
	const containerRef = (0, import_react.useRef)(null);
	const [editing, setEditing] = (0, import_react.useState)(false);
	const [query, setQuery] = (0, import_react.useState)("");
	const [busy, setBusy] = (0, import_react.useState)(false);
	const editsRef = (0, import_react.useRef)(/* @__PURE__ */ new Map());
	(0, import_react.useEffect)(() => {
		const root = containerRef.current;
		if (!root) return;
		const rows = root.querySelectorAll("tr.excel-row");
		const q = query.trim().toLowerCase();
		rows.forEach((tr) => {
			if (!q || tr.classList.contains("excel-sticky-row")) {
				tr.style.display = "";
				return;
			}
			const t = (tr.textContent || "").toLowerCase();
			tr.style.display = t.includes(q) ? "" : "none";
		});
	}, [query, html]);
	(0, import_react.useEffect)(() => {
		const root = containerRef.current;
		if (!root) return;
		const cells = root.querySelectorAll("td.excel-cell");
		cells.forEach((td) => {
			if (editing) {
				td.setAttribute("contenteditable", "true");
				td.dataset.orig = td.innerText;
				td.addEventListener("blur", onCellBlur);
			} else {
				td.removeAttribute("contenteditable");
				td.removeEventListener("blur", onCellBlur);
			}
		});
		return () => cells.forEach((td) => td.removeEventListener("blur", onCellBlur));
	}, [editing, html]);
	const onCellBlur = (e) => {
		const td = e.currentTarget;
		const addr = td.dataset.addr;
		const newV = td.innerText;
		const oldV = td.dataset.orig ?? "";
		if (newV === oldV) return;
		const prev = editsRef.current.get(addr);
		editsRef.current.set(addr, {
			addr,
			oldValue: prev ? prev.oldValue : oldV,
			newValue: newV
		});
		td.classList.add("excel-cell-edited");
	};
	const doPrint = () => window.print();
	const doPdf = () => window.print();
	const doDownloadOriginal = async () => {
		if (!storagePath) return toast.error("No original file available");
		const { data, error } = await supabase.storage.from("aen-uploads").createSignedUrl(storagePath, 60);
		if (error || !data) return toast.error(error?.message ?? "Failed to get file");
		const a = document.createElement("a");
		a.href = data.signedUrl;
		a.download = fileName ?? "sheet.xlsx";
		a.click();
	};
	const doSave = async () => {
		const edits = Array.from(editsRef.current.values());
		if (edits.length === 0) {
			setEditing(false);
			return;
		}
		const reason = prompt(`Reason for ${edits.length} cell change(s):`);
		if (!reason) return;
		setBusy(true);
		try {
			await onSave?.(containerRef.current.innerHTML, edits, reason);
			editsRef.current.clear();
			containerRef.current?.querySelectorAll(".excel-cell-edited").forEach((el) => el.classList.remove("excel-cell-edited"));
			setEditing(false);
			toast.success("Saved");
		} catch (e) {
			toast.error("Save failed: " + e.message);
		} finally {
			setBusy(false);
		}
	};
	const doCancel = () => {
		if (editsRef.current.size && !confirm("Discard unsaved edits?")) return;
		editsRef.current.clear();
		setEditing(false);
		window.location.reload();
	};
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "excel-viewer",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
			className: "flex flex-wrap gap-2 items-center mb-3 print:hidden",
			children: [
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
					className: "relative flex-1 min-w-[220px] max-w-sm",
					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: query,
						onChange: (e) => setQuery(e.target.value),
						placeholder: "Search cells…",
						className: "pl-9"
					})]
				}),
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					variant: "outline",
					size: "sm",
					onClick: doPrint,
					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",
					size: "sm",
					onClick: doPdf,
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(FileDown, { className: "h-4 w-4 mr-2" }), "PDF"]
				}),
				/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					variant: "outline",
					size: "sm",
					onClick: doDownloadOriginal,
					disabled: !storagePath,
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Download, { className: "h-4 w-4 mr-2" }), "Download Original"]
				}),
				canEdit && !editing && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					size: "sm",
					onClick: () => setEditing(true),
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Pencil, { className: "h-4 w-4 mr-2" }), "Edit"]
				}),
				editing && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					size: "sm",
					onClick: doSave,
					disabled: busy,
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(Save, { className: "h-4 w-4 mr-2" }), "Save"]
				}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Button, {
					size: "sm",
					variant: "ghost",
					onClick: doCancel,
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(X, { className: "h-4 w-4 mr-2" }), "Cancel"]
				})] })
			]
		}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
			ref: containerRef,
			className: "excel-viewer-content border rounded-md bg-background",
			dangerouslySetInnerHTML: { __html: html }
		})]
	});
}
function SheetViewerPage() {
	const { division, aen, uploadId } = Route.useParams();
	const { isAdmin, user } = useAuth();
	const qc = useQueryClient();
	const { data: upload, isLoading } = useQuery({
		queryKey: ["upload", uploadId],
		queryFn: async () => {
			const { data, error } = await supabase.from("uploads").select("*").eq("id", uploadId).single();
			if (error) throw error;
			return data;
		}
	});
	const onSave = async (newHtml, edits, reason) => {
		const { error } = await supabase.from("uploads").update({ sheet_html: newHtml }).eq("id", uploadId);
		if (error) throw error;
		const audit = edits.map((e) => ({
			upload_id: uploadId,
			user_id: user?.id,
			field_name: "cell",
			cell_ref: e.addr,
			old_value: e.oldValue,
			new_value: e.newValue,
			reason
		}));
		if (audit.length) await supabase.from("audit_log").insert(audit);
		toast.info("Sheet updated. KPI analytics will refresh on next dashboard load.");
		qc.invalidateQueries();
	};
	if (isLoading) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
		className: "p-6 text-sm text-muted-foreground",
		children: "Loading…"
	});
	if (!upload) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
		className: "p-6",
		children: "Upload not found."
	});
	const u = upload;
	return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
		className: "p-6 max-w-[1600px] mx-auto",
		children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(PageHeader, {
			title: `${u.aen} · ${MONTHS[u.month - 1].label} ${u.year}`,
			subtitle: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Badge, {
				variant: "outline",
				className: "mr-2",
				children: ["v", u.version]
			}), /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
				className: "text-xs text-muted-foreground",
				children: [
					"FY ",
					u.financial_year,
					" · uploaded ",
					new Date(u.uploaded_at).toLocaleString()
				]
			})] }),
			right: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Button, {
				variant: "outline",
				asChild: true,
				children: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(Link, {
					to: "/upload/$division/$aen",
					params: {
						division,
						aen
					},
					children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)(ArrowLeft, { className: "h-4 w-4 mr-2" }), "Back"]
				})
			})
		}), /* @__PURE__ */ (0, import_jsx_runtime.jsx)(Card, { children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CardContent, {
			className: "p-4",
			children: u.sheet_html ? /* @__PURE__ */ (0, import_jsx_runtime.jsx)(ExcelViewer, {
				html: u.sheet_html,
				canEdit: isAdmin,
				storagePath: u.storage_path,
				fileName: u.file_name,
				onSave
			}) : /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
				className: "p-6 text-sm text-muted-foreground",
				children: "No rendered sheet available for this upload. Download the original file instead."
			})
		}) })]
	});
}
//#endregion
export { SheetViewerPage as component };
