import "./chunk-olfrzTEO.js";
import { b as generateId, w as setName } from "./dist-uUUuTqM0.js";
import "./module-RiCpyFsE.js";
import "./creators-1UUtt16O.js";
import { m as actions } from "./module-DJjNH-7f.js";
import { F as setPeriodStart, I as setReportConfig, P as setPeriodEnd, T as addSnapshotAccount, h as addTransaction, j as removeOwnerId, k as addOwnerId } from "./module-CIT3HO-c.js";
import "./upgrade-manifest-0aQdR1Ni.js";
import "./upgrade-manifest-Cg4wvNM9.js";
import { D as useParentFolderForSelectedNode, b as useGetDocument, c as setSelectedNode, g as useDocumentsInSelectedDrive, h as useDocumentOfType, j as useSelectedDrive, k as useSelectedDocumentId, n as addFolder, r as dispatchActions, v as useDriveById, x as useGetDocuments, y as useDrives } from "./dist-mx7YTOSV.js";
import "./chunk-VBDAOXYI-DjbP4DfS.js";
import "./account-transactions-DeAsdH8B.js";
import "./accounts-BPRp-Roc.js";
import "./snapshot-report-B5WIHbu8.js";
import "./splitted-input-diff-kvHJ6NHp.js";
import { c as toast$1, i as DocumentToolbar } from "./connect-MjNGHHUz-BfDIyhte.js";
import { t as Button } from "./button-DVsyzSgU.js";
import { t as Select } from "./select-Z-3s_k3i.js";
import { t as addFile } from "./document-drive-BEVbKaCi.js";
import "./alchemyIntegration-DsK1H6XE.js";
import { t as ChevronDown } from "./chevron-down-H8gEAPEz.js";
import { n as ChevronUp, t as RefreshCw } from "./refresh-cw-dMMeNfPX.js";
import { t as accountTransactionsService } from "./accountTransactionsService-DL9yTuR9.js";
import { t as calculateTransactionFlowInfo } from "./flowTypeCalculations-bbd9HPhP.js";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
//#region editors/snapshot-report-editor/components/DateRangePicker.tsx
function toDateOnly(value) {
	return value.split("T")[0] || "";
}
function toStartOfDayISO(dateStr) {
	const d = /* @__PURE__ */ new Date(dateStr + "T00:00:00.000Z");
	return isNaN(d.getTime()) ? "" : d.toISOString();
}
function toEndOfDayISO(dateStr) {
	const d = /* @__PURE__ */ new Date(dateStr + "T23:59:59.999Z");
	return isNaN(d.getTime()) ? "" : d.toISOString();
}
/**
* Unified date range picker rendered as a single row with two date inputs
* joined visually. Enforces from <= to.
*/
function DateRangePicker({ fromDate, toDate, onChange, label, className }) {
	const [localFrom, setLocalFrom] = useState(() => toDateOnly(fromDate));
	const [localTo, setLocalTo] = useState(() => toDateOnly(toDate));
	useEffect(() => {
		const extFrom = toDateOnly(fromDate);
		if (extFrom && extFrom !== localFrom) setLocalFrom(extFrom);
	}, [fromDate]);
	useEffect(() => {
		const extTo = toDateOnly(toDate);
		if (extTo && extTo !== localTo) setLocalTo(extTo);
	}, [toDate]);
	const handleFromChange = useCallback((e) => {
		const dateStr = e.target.value;
		if (!dateStr) return;
		let effectiveTo = localTo;
		if (effectiveTo && dateStr > effectiveTo) {
			effectiveTo = dateStr;
			setLocalTo(effectiveTo);
		}
		setLocalFrom(dateStr);
		const fromISO = toStartOfDayISO(dateStr);
		const toISO = toEndOfDayISO(effectiveTo || dateStr);
		if (fromISO && toISO) onChange(fromISO, toISO);
	}, [localTo, onChange]);
	const handleToChange = useCallback((e) => {
		const dateStr = e.target.value;
		if (!dateStr) return;
		let effectiveFrom = localFrom;
		if (effectiveFrom && dateStr < effectiveFrom) {
			effectiveFrom = dateStr;
			setLocalFrom(effectiveFrom);
		}
		setLocalTo(dateStr);
		const fromISO = toStartOfDayISO(effectiveFrom || dateStr);
		const toISO = toEndOfDayISO(dateStr);
		if (fromISO && toISO) onChange(fromISO, toISO);
	}, [localFrom, onChange]);
	return /* @__PURE__ */ jsxs("div", {
		className,
		children: [label && /* @__PURE__ */ jsx("label", {
			className: "block text-sm font-medium text-gray-700 mb-2",
			children: label
		}), /* @__PURE__ */ jsxs("div", {
			className: "inline-flex items-center border border-gray-300 rounded-md overflow-hidden focus-within:ring-2 focus-within:ring-blue-500 focus-within:border-blue-500",
			children: [
				/* @__PURE__ */ jsx("input", {
					type: "date",
					value: localFrom,
					onChange: handleFromChange,
					className: "px-3 py-2 text-sm border-none outline-none bg-white"
				}),
				/* @__PURE__ */ jsx("span", {
					className: "px-2 text-sm text-gray-400 bg-gray-50 self-stretch flex items-center border-x border-gray-300",
					children: "→"
				}),
				/* @__PURE__ */ jsx("input", {
					type: "date",
					value: localTo,
					onChange: handleToChange,
					className: "px-3 py-2 text-sm border-none outline-none bg-white"
				})
			]
		})]
	});
}
//#endregion
//#region editors/hooks/useSnapshotReportDocument.ts
function useSnapshotReportDocument(documentId) {
	return useDocumentOfType(documentId, "powerhouse/snapshot-report");
}
function useSelectedSnapshotReportDocument() {
	return useSnapshotReportDocument(useSelectedDocumentId());
}
//#endregion
//#region editors/snapshot-report-editor/components/AddReportToRemoteDrive.tsx
function useAddReportToRemoteDrive(ownerIdOverride) {
	const [selectedDocument] = useSelectedSnapshotReportDocument();
	const drives = useDrives();
	const ownerId = ownerIdOverride ?? selectedDocument?.state?.global?.ownerIds?.[0] ?? "";
	return {
		ownerDriveId: useMemo(() => {
			if (!drives || !ownerId) return void 0;
			return drives.find((drive) => {
				if (drive.header.documentType !== "powerhouse/document-drive" || drive.header.meta?.preferredEditor !== "builder-team-admin") return false;
				return (drive.state.global.nodes ?? []).some((node) => node.kind === "file" && "documentType" in node && node.documentType === "powerhouse/builder-profile" && node.id === ownerId);
			});
		}, [drives, ownerId])?.header.id,
		ownerId,
		selectedDocument
	};
}
function useOwnerDriveActions(ownerDriveId, selectedDocument) {
	const [driveDocument, dispatch] = useDriveById(ownerDriveId);
	const driveDocumentId = driveDocument?.header?.id;
	const isDriveAligned = Boolean(ownerDriveId && driveDocumentId === ownerDriveId);
	const snapshotReportFolderId = useMemo(() => {
		if (!isDriveAligned) return void 0;
		return driveDocument?.state?.global?.nodes?.find((node) => node.kind === "folder" && node.name === "Snapshot Reports")?.id;
	}, [driveDocument, isDriveAligned]);
	const snapshotReportNodeIds = useMemo(() => {
		if (!isDriveAligned || !driveDocument?.state?.global?.nodes) return [];
		return driveDocument.state.global.nodes.filter((node) => node.kind === "file" && "documentType" in node && node.documentType === "powerhouse/snapshot-report").map((node) => node.id);
	}, [driveDocument, isDriveAligned]);
	const canAddReportToOwnerDrive = Boolean(isDriveAligned && selectedDocument?.header?.id);
	const addReportToOwnerDrive = async () => {
		if (!dispatch || !isDriveAligned || !canAddReportToOwnerDrive || !selectedDocument?.header?.id) return false;
		let targetFolderId = snapshotReportFolderId;
		if (!targetFolderId) targetFolderId = (await addFolder(ownerDriveId, "Snapshot Reports"))?.id;
		if (!targetFolderId) return false;
		dispatch(addFile({
			name: selectedDocument.header.name,
			documentType: "powerhouse/snapshot-report",
			id: selectedDocument.header.id,
			parentFolder: targetFolderId
		}));
		return true;
	};
	return {
		addReportToOwnerDrive,
		canAddReportToOwnerDrive,
		snapshotReportNodeIds,
		driveDocumentId
	};
}
//#endregion
//#region editors/snapshot-report-editor/components/SetOwner.tsx
function SetOwner({ ownerIds, dispatch }) {
	const drives = useDrives();
	const [query, setQuery] = useState("");
	const [isPickerOpen, setIsPickerOpen] = useState(false);
	const pickerRef = useRef(null);
	const getDocuments = useGetDocuments();
	const localProfileNodes = useMemo(() => {
		if (!drives) return [];
		return drives.filter((drive) => drive.header.documentType === "powerhouse/document-drive" && drive.header.meta?.preferredEditor === "builder-team-admin").flatMap((drive) => (drive.state.global.nodes ?? []).filter((node) => node.kind === "file" && "documentType" in node && node.documentType === "powerhouse/builder-profile").map((node) => ({
			id: node.id,
			name: node.name || "Untitled builder",
			driveId: drive.header.id
		})));
	}, [drives]);
	const localProfilePhids = useMemo(() => localProfileNodes.map((node) => node.id), [localProfileNodes]);
	const [localProfileDocuments, setLocalProfileDocuments] = useState([]);
	useEffect(() => {
		if (localProfilePhids.length === 0) {
			setLocalProfileDocuments([]);
			return;
		}
		getDocuments(localProfilePhids).then((docs) => {
			setLocalProfileDocuments(docs);
		}).catch((error) => {
			console.error("Failed to fetch builder profile documents:", error);
			setLocalProfileDocuments([]);
		});
	}, [localProfilePhids, getDocuments]);
	const localProfileStateMap = useMemo(() => {
		const map = /* @__PURE__ */ new Map();
		for (const doc of localProfileDocuments) {
			const state = doc.state?.global;
			if (state) map.set(doc.header.id, state);
		}
		return map;
	}, [localProfileDocuments]);
	const builderProfiles = useMemo(() => {
		return localProfileNodes.map((node) => {
			const state = localProfileStateMap.get(node.id);
			return {
				id: node.id,
				name: state?.name || node.name,
				driveId: node.driveId
			};
		});
	}, [localProfileNodes, localProfileStateMap]);
	const ownerIdSet = new Set(ownerIds);
	const availableProfiles = builderProfiles.filter((profile) => !ownerIdSet.has(profile.id));
	const normalizedQuery = query.trim().toLowerCase();
	const filteredProfiles = normalizedQuery ? availableProfiles.filter((profile) => profile.name.toLowerCase().includes(normalizedQuery)) : availableProfiles.slice(0, 5);
	const handleSelect = (profile) => {
		dispatch(addOwnerId({ ownerId: profile.id }));
		setQuery("");
		setIsPickerOpen(false);
	};
	const handleManualSelect = (value) => {
		const trimmed = value.trim();
		if (!trimmed || ownerIdSet.has(trimmed)) return;
		dispatch(addOwnerId({ ownerId: trimmed }));
		setQuery("");
		setIsPickerOpen(false);
	};
	const handleRemoveOwner = (ownerId) => {
		dispatch(removeOwnerId({ ownerId }));
	};
	useEffect(() => {
		if (!isPickerOpen) return;
		const handleClickOutside = (event) => {
			if (pickerRef.current && event.target instanceof Node && !pickerRef.current.contains(event.target)) setIsPickerOpen(false);
		};
		document.addEventListener("mousedown", handleClickOutside);
		return () => document.removeEventListener("mousedown", handleClickOutside);
	}, [isPickerOpen]);
	return /* @__PURE__ */ jsxs("div", {
		className: "space-y-3",
		children: [ownerIds.length > 0 && /* @__PURE__ */ jsx("div", {
			className: "space-y-2",
			children: ownerIds.map((ownerId) => /* @__PURE__ */ jsx(OwnerCard, {
				ownerId,
				builderProfiles,
				onRemove: () => handleRemoveOwner(ownerId)
			}, ownerId))
		}), /* @__PURE__ */ jsxs("div", {
			className: "relative",
			ref: pickerRef,
			children: [/* @__PURE__ */ jsx("div", {
				className: "flex items-center gap-2",
				children: /* @__PURE__ */ jsx("input", {
					type: "text",
					value: query,
					onChange: (event) => setQuery(event.target.value),
					onFocus: () => setIsPickerOpen(true),
					placeholder: ownerIds.length === 0 ? "Search builder name to add team" : "Add another team...",
					className: "flex-1 min-w-[280px] rounded-md border border-gray-300 bg-white px-3 py-2 text-sm text-gray-900 shadow-sm focus:border-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-200 dark:border-gray-700 dark:bg-gray-900 dark:text-gray-100 dark:focus:border-gray-400 dark:focus:ring-gray-800"
				})
			}), isPickerOpen && /* @__PURE__ */ jsx("div", {
				className: "absolute z-10 mt-2 w-full rounded-md border border-gray-200 bg-white shadow-lg dark:border-gray-700 dark:bg-gray-900",
				children: filteredProfiles.length > 0 ? filteredProfiles.map((profile) => /* @__PURE__ */ jsxs("button", {
					type: "button",
					onClick: () => handleSelect(profile),
					className: "flex w-full flex-col px-3 py-2 text-left text-sm text-gray-900 hover:bg-gray-50 dark:text-gray-100 dark:hover:bg-gray-800",
					children: [/* @__PURE__ */ jsx("span", {
						className: "font-medium",
						children: profile.name
					}), /* @__PURE__ */ jsx("span", {
						className: "text-xs text-gray-500 dark:text-gray-400",
						children: profile.id
					})]
				}, `${profile.driveId}-${profile.id}`)) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("div", {
					className: "px-3 py-2 text-sm text-gray-500 dark:text-gray-400",
					children: normalizedQuery ? "No matching teams" : "No more teams available"
				}), normalizedQuery && !ownerIdSet.has(normalizedQuery) && /* @__PURE__ */ jsxs("button", {
					type: "button",
					onClick: () => handleManualSelect(query),
					className: "flex w-full flex-col px-3 py-2 text-left text-sm text-gray-900 hover:bg-gray-50 dark:text-gray-100 dark:hover:bg-gray-800",
					children: [/* @__PURE__ */ jsx("span", {
						className: "font-medium",
						children: "Use this ID"
					}), /* @__PURE__ */ jsx("span", {
						className: "text-xs text-gray-500 dark:text-gray-400",
						children: query
					})]
				})] })
			})]
		})]
	});
}
function OwnerCard({ ownerId, builderProfiles, onRemove }) {
	const profile = builderProfiles.find((p) => p.id === ownerId);
	const { ownerDriveId, selectedDocument } = useAddReportToRemoteDrive(ownerId);
	const ownerDriveMissing = !!ownerId && !ownerDriveId;
	return /* @__PURE__ */ jsxs("div", {
		className: "rounded-md border border-gray-200 bg-white px-3 py-2 shadow-sm dark:border-gray-700 dark:bg-gray-900",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "flex items-start justify-between gap-2",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "flex-1 min-w-0",
				children: [/* @__PURE__ */ jsx("div", {
					className: "text-sm font-semibold text-gray-900 dark:text-gray-100",
					children: profile?.name || "Unknown team"
				}), /* @__PURE__ */ jsx("div", {
					className: "mt-1 text-xs font-mono text-gray-500 dark:text-gray-400 truncate",
					children: ownerId
				})]
			}), /* @__PURE__ */ jsx("button", {
				type: "button",
				onClick: onRemove,
				className: "p-1 text-gray-400 hover:text-red-500 dark:text-gray-500 dark:hover:text-red-400",
				title: "Remove team",
				children: /* @__PURE__ */ jsx("svg", {
					className: "w-4 h-4",
					fill: "none",
					stroke: "currentColor",
					viewBox: "0 0 24 24",
					children: /* @__PURE__ */ jsx("path", {
						strokeLinecap: "round",
						strokeLinejoin: "round",
						strokeWidth: 2,
						d: "M6 18L18 6M6 6l12 12"
					})
				})
			})]
		}), /* @__PURE__ */ jsx("div", {
			className: "mt-2 flex flex-wrap items-center gap-3",
			children: ownerDriveMissing ? /* @__PURE__ */ jsx("span", {
				className: "text-xs font-medium text-amber-600 dark:text-amber-400",
				children: "Team Drive Not Found"
			}) : ownerDriveId ? /* @__PURE__ */ jsx(OwnerDriveActions, {
				ownerDriveId,
				selectedDocument,
				ownerName: profile?.name || "team"
			}) : null
		})]
	});
}
function OwnerDriveActions({ ownerDriveId, selectedDocument, ownerName }) {
	const { addReportToOwnerDrive, canAddReportToOwnerDrive, driveDocumentId, snapshotReportNodeIds } = useOwnerDriveActions(ownerDriveId, selectedDocument);
	const [addStatus, setAddStatus] = useState("idle");
	const selectedDocumentId = selectedDocument?.header?.id || "";
	const isAlreadyAdded = !!selectedDocumentId && driveDocumentId === ownerDriveId && snapshotReportNodeIds.includes(selectedDocumentId);
	useEffect(() => {
		if (isAlreadyAdded) {
			setAddStatus("added");
			return;
		}
		setAddStatus("idle");
	}, [
		isAlreadyAdded,
		selectedDocumentId,
		snapshotReportNodeIds,
		ownerDriveId,
		driveDocumentId
	]);
	const handleAddReport = useCallback(() => {
		setAddStatus("adding");
		addReportToOwnerDrive().then((didAdd) => {
			if (!didAdd) setAddStatus("idle");
		});
	}, [addReportToOwnerDrive]);
	if (addStatus === "added") return /* @__PURE__ */ jsxs("span", {
		className: "text-xs font-medium text-green-600 dark:text-green-400",
		children: ["Snapshot Report is added to ", ownerName]
	});
	return /* @__PURE__ */ jsx("button", {
		type: "button",
		onClick: handleAddReport,
		disabled: !canAddReportToOwnerDrive || addStatus !== "idle",
		className: "text-xs font-medium text-blue-600 hover:text-blue-700 disabled:cursor-not-allowed disabled:opacity-50 dark:text-blue-400 dark:hover:text-blue-300",
		children: addStatus === "adding" ? "Adding report..." : `Add Report to ${ownerName}`
	});
}
//#endregion
//#region editors/snapshot-report-editor/utils/balanceCalculations.ts
/**
* Calculate the effect of a transaction on balance based on account type
*
* - Internal accounts: Standard balance (INFLOW +, OUTFLOW -)
* - Source accounts: Track "cumulative provided" (OUTFLOW = funds sent to team = positive)
* - Destination accounts: Track "cumulative received" (INFLOW = funds received from team = positive)
* - External accounts: Net flows with team (standard balance)
*/
function getTransactionEffect(direction, amountValue, accountType) {
	if (accountType === "Source") return direction === "OUTFLOW" ? amountValue : -amountValue;
	if (accountType === "Destination") return direction === "INFLOW" ? amountValue : -amountValue;
	return direction === "INFLOW" ? amountValue : -amountValue;
}
/**
* Calculate opening and closing balances for all tokens from transactions
* @param transactions - All transactions for the account
* @param startDate - Period start date (ISO string)
* @param endDate - Period end date (ISO string)
* @param accountType - Optional account type for type-specific balance logic
* @param existingStartingBalances - Optional existing starting balances to preserve tokens with no transactions
* @returns Map of token to balance information
*/
function calculateBalances(transactions, startDate, endDate, accountType, existingStartingBalances) {
	const balances = /* @__PURE__ */ new Map();
	const start = new Date(startDate);
	const end = new Date(endDate);
	if (existingStartingBalances && existingStartingBalances.length > 0) existingStartingBalances.forEach((startingBalance) => {
		const token = startingBalance.token;
		if (!token) return;
		if (!balances.has(token)) {
			let openingValue = "0";
			let unit = token;
			if (startingBalance.amount && typeof startingBalance.amount === "object") {
				if (startingBalance.amount.value !== void 0 && startingBalance.amount.value !== null) openingValue = String(startingBalance.amount.value);
				if (startingBalance.amount.unit) unit = String(startingBalance.amount.unit);
			}
			balances.set(token, {
				token,
				opening: {
					value: openingValue,
					unit
				},
				closing: {
					value: "0",
					unit
				}
			});
		}
	});
	transactions.forEach((tx) => {
		const txDate = new Date(tx.datetime);
		const token = tx.token;
		if (!balances.has(token)) balances.set(token, {
			token,
			opening: {
				value: "0",
				unit: token
			},
			closing: {
				value: "0",
				unit: token
			}
		});
		const balance = balances.get(token);
		let amountStr;
		const txAmount = tx.amount;
		if (typeof txAmount === "object" && txAmount?.value !== void 0) amountStr = txAmount.value;
		else if (typeof txAmount === "string") amountStr = txAmount.split(" ")[0] || "0";
		else amountStr = "0";
		const amountValue = parseFloat(amountStr);
		const effect = getTransactionEffect(tx.direction, amountValue, accountType);
		if (txDate < start) {
			const currentOpening = parseFloat(balance.opening.value || "0");
			balance.opening.value = (currentOpening + effect).toString();
		}
		if (txDate >= start && txDate <= end) {
			const currentClosing = parseFloat(balance.closing.value || "0");
			balance.closing.value = (currentClosing + effect).toString();
		}
	});
	const fixPrecision = (value) => {
		if (Math.abs(value) < 1e-10) return 0;
		return value;
	};
	balances.forEach((balance) => {
		const openingValue = parseFloat(balance.opening.value || "0");
		const periodChange = parseFloat(balance.closing.value || "0");
		const closingValue = openingValue + periodChange;
		balance.opening.value = fixPrecision(openingValue).toString();
		balance.closing.value = fixPrecision(closingValue).toString();
		if (Math.abs(openingValue) > 1e-10 || Math.abs(closingValue) > 1e-10) console.log("[calculateBalances] Finalized balance:", {
			token: balance.token,
			opening: balance.opening.value,
			closing: balance.closing.value,
			periodChange
		});
	});
	return balances;
}
/**
* Format balance amount for display
*/
function formatBalance(amount) {
	if (typeof amount === "object" && amount?.value !== void 0) return `${parseFloat(amount.value).toFixed(6)} ${amount.unit || ""}`.trim();
	return "0";
}
//#endregion
//#region editors/snapshot-report-editor/hooks/useSyncSnapshotAccount.ts
/**
* Hook for syncing snapshot accounts with account transactions documents
* Similar to useSyncWallet in expense-report
*/
/**
* Calculate starting balances for non-Internal accounts from Internal account transactions
* Only includes transactions where the counterparty is a non-Internal account type
*/
function calculateNonInternalStartingBalances(allTransactions, nonInternalAccounts, internalAccountAddresses, startDate) {
	const start = new Date(startDate);
	const result = /* @__PURE__ */ new Map();
	for (const account of nonInternalAccounts) {
		const addressLower = account.accountAddress.toLowerCase();
		const tokenBalances = /* @__PURE__ */ new Map();
		for (const tx of allTransactions) {
			const counterPartyLower = tx.counterParty?.toLowerCase();
			if (!counterPartyLower || counterPartyLower !== addressLower || internalAccountAddresses.has(counterPartyLower)) continue;
			if (new Date(tx.datetime) >= start) continue;
			const token = tx.details?.token || tx.token || "";
			const amountObj = tx.amount;
			const amountValue = parseFloat(typeof amountObj === "object" ? amountObj.value || "0" : String(amountObj).split(" ")[0]);
			const invertedDirection = tx.direction === "OUTFLOW" ? "INFLOW" : "OUTFLOW";
			const effect = account.type === "Source" ? invertedDirection === "OUTFLOW" ? amountValue : -amountValue : invertedDirection === "INFLOW" ? amountValue : -amountValue;
			tokenBalances.set(token, (tokenBalances.get(token) || 0) + effect);
		}
		const balances = /* @__PURE__ */ new Map();
		tokenBalances.forEach((value, token) => {
			if (Math.abs(value) > 1e-10) balances.set(token, {
				value: value.toString(),
				unit: token
			});
		});
		result.set(account.id, balances);
	}
	return result;
}
function useSyncSnapshotAccount() {
	const documents = useDocumentsInSelectedDrive();
	const [selectedDrive] = useSelectedDrive();
	const getDocument = useGetDocument();
	const syncAccount = async (snapshotAccount, accountEntry, accountsDocumentId, startDate, endDate, dispatch, allSnapshotAccounts = [], snapshotDocumentId, accountTransactionsIdMap) => {
		if (!documents || !startDate || !endDate) return {
			success: false,
			message: "Missing required data (documents, startDate, or endDate)"
		};
		try {
			if (snapshotAccount.type !== "Internal") return await syncNonInternalAccount(snapshotAccount, startDate, endDate, dispatch, allSnapshotAccounts, snapshotDocumentId, accountTransactionsIdMap);
			let accountTransactionsDocId = snapshotAccount.accountTransactionsId || accountEntry?.accountTransactionsId;
			if (!accountTransactionsDocId && accountEntry) {
				const existingDoc = documents?.find((doc) => {
					if (doc.header.documentType !== "powerhouse/account-transactions") return false;
					return (doc.state?.global)?.account?.account?.toLowerCase() === accountEntry.account.toLowerCase();
				});
				if (existingDoc) {
					accountTransactionsDocId = existingDoc.header.id;
					console.log("[useSyncSnapshotAccount] Found existing account transactions document:", accountTransactionsDocId);
				} else {
					const driveId = selectedDrive?.header?.id;
					if (!driveId) return {
						success: false,
						message: "No drive selected"
					};
					const result = await accountTransactionsService.createAccountTransactionsDocument(accountEntry, accountsDocumentId || "", driveId);
					if (!result.success || !result.documentId) return {
						success: false,
						message: result.message || "Failed to create account transactions document"
					};
					accountTransactionsDocId = result.documentId;
				}
			}
			if (!accountTransactionsDocId) return {
				success: false,
				message: "No account transactions document available"
			};
			let txDoc;
			try {
				txDoc = await getDocument(accountTransactionsDocId);
			} catch {
				txDoc = void 0;
			}
			if (!txDoc?.state?.global?.transactions) return {
				success: false,
				message: "Account transactions document not found or has no transactions"
			};
			const allTransactions = txDoc.state.global.transactions;
			const start = new Date(startDate);
			const end = new Date(endDate);
			const periodTransactions = allTransactions.filter((tx) => {
				if (!tx?.datetime) return false;
				const txDate = new Date(tx.datetime);
				if (isNaN(txDate.getTime())) return false;
				return txDate >= start && txDate <= end;
			});
			const existingTransactionIds = new Set(snapshotAccount.transactions.map((tx) => tx.transactionId));
			const newTransactionIds = new Set(periodTransactions.map((tx) => tx.id));
			const hasTransactionChanges = existingTransactionIds.size !== newTransactionIds.size || [...existingTransactionIds].some((id) => !newTransactionIds.has(id)) || [...newTransactionIds].some((id) => !existingTransactionIds.has(id));
			const hasTransactions = periodTransactions.length > 0;
			const hasStartingBalances = snapshotAccount.startingBalances.length > 0;
			const hasEndingBalances = snapshotAccount.endingBalances.length > 0;
			if (!(hasTransactionChanges || hasTransactions && (!hasStartingBalances || !hasEndingBalances))) return {
				success: true,
				message: "No changes detected - already in sync",
				transactionsAdded: snapshotAccount.transactions.length,
				documentId: accountTransactionsDocId
			};
			const balances = calculateBalances(allTransactions.map((tx) => {
				const token = tx.details?.token || (typeof tx.amount === "object" && tx.amount?.unit ? tx.amount.unit : typeof tx.amount === "string" ? tx.amount.split(" ")[1] || "" : "");
				return {
					id: String(tx.id),
					transactionId: String(tx.id),
					counterParty: tx.counterParty || null,
					amount: tx.amount,
					datetime: tx.datetime,
					txHash: tx.details?.txHash || "",
					token,
					blockNumber: tx.details?.blockNumber ?? null,
					direction: tx.direction,
					flowType: null,
					counterPartyAccountId: null
				};
			}), startDate, endDate, snapshotAccount.type, snapshotAccount.startingBalances.map((b) => ({
				token: b.token,
				amount: b.amount
			})));
			const allActions = [];
			snapshotAccount.transactions.forEach((tx) => {
				allActions.push(transactionsActions.removeTransaction({ id: tx.id }));
			});
			for (const tx of periodTransactions) {
				const { flowType, counterPartyAccountId } = calculateTransactionFlowInfo(tx.direction, snapshotAccount.type, tx.counterParty, allSnapshotAccounts.length > 0 ? allSnapshotAccounts : [snapshotAccount]);
				allActions.push(transactionsActions.addTransaction({
					accountId: snapshotAccount.id,
					id: generateId(),
					transactionId: tx.id,
					counterParty: tx.counterParty || void 0,
					amount: tx.amount,
					datetime: tx.datetime,
					txHash: tx.details?.txHash || "",
					token: tx.details?.token || "",
					blockNumber: tx.details?.blockNumber || void 0,
					direction: tx.direction,
					flowType,
					counterPartyAccountId: counterPartyAccountId || void 0
				}));
			}
			snapshotAccount.startingBalances.forEach((b) => {
				allActions.push(balancesActions.removeStartingBalance({
					accountId: snapshotAccount.id,
					balanceId: b.id
				}));
			});
			balances.forEach((balance) => {
				allActions.push(balancesActions.setStartingBalance({
					accountId: snapshotAccount.id,
					balanceId: generateId(),
					token: balance.token,
					amount: balance.opening
				}));
			});
			snapshotAccount.endingBalances.forEach((b) => {
				allActions.push(balancesActions.removeEndingBalance({
					accountId: snapshotAccount.id,
					balanceId: b.id
				}));
			});
			balances.forEach((balance) => {
				allActions.push(balancesActions.setEndingBalance({
					accountId: snapshotAccount.id,
					balanceId: generateId(),
					token: balance.token,
					amount: balance.closing
				}));
			});
			const nonInternalAccounts = allSnapshotAccounts.filter((a) => a.type !== "Internal" && a.id !== snapshotAccount.id);
			if (nonInternalAccounts.length > 0) calculateNonInternalStartingBalances(allTransactions, nonInternalAccounts, new Set(allSnapshotAccounts.filter((a) => a.type === "Internal").map((a) => a.accountAddress.toLowerCase())), startDate).forEach((tokenBalances, accountId) => {
				const account = allSnapshotAccounts.find((a) => a.id === accountId);
				if (!account) return;
				account.startingBalances.forEach((b) => {
					allActions.push(balancesActions.removeStartingBalance({
						accountId,
						balanceId: b.id
					}));
				});
				tokenBalances.forEach((amount, token) => {
					allActions.push(balancesActions.setStartingBalance({
						accountId,
						balanceId: generateId(),
						token,
						amount
					}));
				});
			});
			let updatedSnapshotDoc;
			if (snapshotDocumentId && allActions.length > 0) updatedSnapshotDoc = await dispatchActions(allActions, snapshotDocumentId);
			else allActions.forEach((action) => dispatch(action));
			return {
				success: true,
				message: `Synced ${periodTransactions.length} transactions and updated balances`,
				transactionsAdded: periodTransactions.length,
				documentId: accountTransactionsDocId,
				updatedSnapshotDoc
			};
		} catch (error) {
			console.error("[useSyncSnapshotAccount] Error syncing account:", error);
			return {
				success: false,
				message: `Error: ${error instanceof Error ? error.message : "Unknown error"}`
			};
		}
	};
	/**
	* Sync a non-Internal account by deriving transactions from Internal accounts
	* Uses FULL transaction history from AccountTransactions documents (not just snapshot transactions)
	* to correctly calculate opening balances from pre-period transactions
	*/
	const syncNonInternalAccount = async (snapshotAccount, startDate, endDate, dispatch, allSnapshotAccounts, snapshotDocumentId, accountTransactionsIdMap) => {
		try {
			const internalAccounts = allSnapshotAccounts.filter((acc) => acc.type === "Internal");
			if (internalAccounts.length === 0) return {
				success: false,
				message: "No Internal accounts found. Import Internal accounts first to derive transactions."
			};
			const accountAddressLower = snapshotAccount.accountAddress.toLowerCase();
			const allDerivedTransactions = [];
			const internalAccountAddresses = new Set(internalAccounts.map((acc) => acc.accountAddress.toLowerCase()));
			for (const internalAccount of internalAccounts) {
				const accountTxDocId = accountTransactionsIdMap?.get(internalAccount.id) || internalAccount.accountTransactionsId;
				if (!accountTxDocId) continue;
				let txDoc;
				try {
					txDoc = await getDocument(accountTxDocId);
				} catch {
					txDoc = void 0;
				}
				if (!txDoc?.state?.global?.transactions) continue;
				const allTxFromDoc = txDoc.state.global.transactions;
				for (const tx of allTxFromDoc) {
					const counterPartyLower = tx.counterParty?.toLowerCase();
					if (counterPartyLower === accountAddressLower && !internalAccountAddresses.has(counterPartyLower)) {
						const invertedDirection = tx.direction === "INFLOW" ? "OUTFLOW" : "INFLOW";
						const flowType = calculateTransactionFlowInfo(invertedDirection, snapshotAccount.type, internalAccount.accountAddress, allSnapshotAccounts).flowType;
						const txAmount = tx.amount;
						let amount;
						if (typeof txAmount === "object" && txAmount.value !== void 0) amount = {
							value: txAmount.value,
							unit: txAmount.unit || tx.details?.token || ""
						};
						else if (typeof txAmount === "string") amount = {
							value: txAmount.split(" ")[0] || "0",
							unit: tx.details?.token || ""
						};
						else amount = {
							value: "0",
							unit: tx.details?.token || ""
						};
						allDerivedTransactions.push({
							id: generateId(),
							transactionId: tx.id,
							counterParty: internalAccount.accountAddress,
							counterPartyAccountId: internalAccount.id,
							amount,
							datetime: tx.datetime,
							txHash: tx.details?.txHash || "",
							token: tx.details?.token || amount.unit,
							blockNumber: tx.details?.blockNumber ?? null,
							direction: invertedDirection,
							flowType
						});
					}
				}
			}
			allDerivedTransactions.sort((a, b) => new Date(a.datetime).getTime() - new Date(b.datetime).getTime());
			const start = new Date(startDate);
			const end = new Date(endDate);
			const periodTransactions = allDerivedTransactions.filter((tx) => {
				const txDate = new Date(tx.datetime);
				return txDate >= start && txDate <= end;
			});
			const existingTransactionIds = new Set(snapshotAccount.transactions.map((tx) => tx.transactionId));
			const newTransactionIds = new Set(periodTransactions.map((tx) => tx.transactionId));
			const hasTransactionChanges = existingTransactionIds.size !== newTransactionIds.size || [...existingTransactionIds].some((id) => !newTransactionIds.has(id)) || [...newTransactionIds].some((id) => !existingTransactionIds.has(id));
			const hasStartingBalances = snapshotAccount.startingBalances.length > 0;
			const hasEndingBalances = snapshotAccount.endingBalances.length > 0;
			if (!(hasTransactionChanges || hasStartingBalances && !hasEndingBalances)) return {
				success: true,
				message: "No changes detected - already in sync",
				transactionsAdded: snapshotAccount.transactions.length
			};
			const balances = calculateBalances(allDerivedTransactions.map((tx) => ({
				id: tx.id,
				transactionId: tx.transactionId,
				counterParty: tx.counterParty,
				amount: tx.amount,
				datetime: tx.datetime,
				txHash: tx.txHash,
				token: tx.token,
				blockNumber: tx.blockNumber,
				direction: tx.direction,
				flowType: tx.flowType,
				counterPartyAccountId: tx.counterPartyAccountId
			})), startDate, endDate, snapshotAccount.type, snapshotAccount.startingBalances.map((b) => ({
				token: b.token,
				amount: b.amount
			})));
			const allActions = [];
			snapshotAccount.transactions.forEach((tx) => {
				allActions.push(transactionsActions.removeTransaction({ id: tx.id }));
			});
			for (const tx of periodTransactions) allActions.push(transactionsActions.addTransaction({
				accountId: snapshotAccount.id,
				id: tx.id,
				transactionId: tx.transactionId,
				counterParty: tx.counterParty,
				amount: tx.amount,
				datetime: tx.datetime,
				txHash: tx.txHash,
				token: tx.token,
				blockNumber: tx.blockNumber ?? void 0,
				direction: tx.direction,
				flowType: tx.flowType,
				counterPartyAccountId: tx.counterPartyAccountId
			}));
			snapshotAccount.startingBalances.forEach((b) => {
				allActions.push(balancesActions.removeStartingBalance({
					accountId: snapshotAccount.id,
					balanceId: b.id
				}));
			});
			balances.forEach((balance) => {
				allActions.push(balancesActions.setStartingBalance({
					accountId: snapshotAccount.id,
					balanceId: generateId(),
					token: balance.token,
					amount: balance.opening
				}));
			});
			snapshotAccount.endingBalances.forEach((b) => {
				allActions.push(balancesActions.removeEndingBalance({
					accountId: snapshotAccount.id,
					balanceId: b.id
				}));
			});
			const balanceTokens = new Set(Array.from(balances.keys()));
			const startingBalanceTokens = new Set(snapshotAccount.startingBalances.map((b) => b.token));
			console.log("[syncNonInternalAccount] Adding ending balances:", {
				accountId: snapshotAccount.id,
				accountName: snapshotAccount.accountName,
				balancesInMap: Array.from(balances.values()).map((b) => ({
					token: b.token,
					opening: b.opening.value,
					closing: b.closing.value
				})),
				startingBalanceTokens: Array.from(startingBalanceTokens),
				balanceTokens: Array.from(balanceTokens)
			});
			balances.forEach((balance) => {
				const closingAmount = balance.closing;
				console.log("[syncNonInternalAccount] Adding ending balance:", {
					token: balance.token,
					closingAmount
				});
				allActions.push(balancesActions.setEndingBalance({
					accountId: snapshotAccount.id,
					balanceId: generateId(),
					token: balance.token,
					amount: closingAmount
				}));
			});
			startingBalanceTokens.forEach((token) => {
				if (!balanceTokens.has(token)) console.warn(`[syncNonInternalAccount] Starting balance token ${token} not found in calculated balances map!`);
			});
			let updatedSnapshotDoc;
			if (snapshotDocumentId && allActions.length > 0) {
				console.log("[syncNonInternalAccount] Dispatching actions:", {
					accountId: snapshotAccount.id,
					totalActions: allActions.length,
					endingBalanceActions: allActions.filter((a) => a.type === "SET_ENDING_BALANCE").length
				});
				updatedSnapshotDoc = await dispatchActions(allActions, snapshotDocumentId);
			} else allActions.forEach((action) => dispatch(action));
			return {
				success: true,
				message: `Derived ${periodTransactions.length} transactions from Internal accounts`,
				transactionsAdded: periodTransactions.length,
				updatedSnapshotDoc
			};
		} catch (error) {
			console.error("[useSyncSnapshotAccount] Error syncing non-Internal account:", error);
			return {
				success: false,
				message: `Error: ${error instanceof Error ? error.message : "Unknown error"}`
			};
		}
	};
	return { syncAccount };
}
//#endregion
//#region editors/snapshot-report-editor/editor.tsx
function generateMonthOptions() {
	const options = [];
	const startDate = new Date(2025, 0, 1);
	const currentDate = /* @__PURE__ */ new Date();
	const date = new Date(startDate);
	while (date <= currentDate) {
		const year = date.getFullYear();
		const month = date.getMonth();
		const label = `${date.toLocaleDateString("en-US", { month: "long" })} ${year}`;
		const value = `${year}-${String(month + 1).padStart(2, "0")}`;
		options.push({
			label,
			value
		});
		date.setMonth(date.getMonth() + 1);
	}
	return options.reverse();
}
function getMonthDateRange(yearMonth) {
	const [year, month] = yearMonth.split("-").map(Number);
	const periodStart = new Date(Date.UTC(year, month - 1, 1, 0, 0, 0, 0)).toISOString();
	const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
	return {
		periodStart,
		periodEnd: new Date(Date.UTC(year, month - 1, lastDay, 23, 59, 59, 999)).toISOString()
	};
}
function Editor() {
	const [document, dispatch] = useSelectedSnapshotReportDocument();
	const documentsInDrive = useDocumentsInSelectedDrive();
	const [isAccountPickerOpen, setIsAccountPickerOpen] = useState(false);
	const [selectedAccountIds, setSelectedAccountIds] = useState(/* @__PURE__ */ new Set());
	const [expandedAccounts, setExpandedAccounts] = useState(/* @__PURE__ */ new Set());
	const [syncingAccounts, setSyncingAccounts] = useState(/* @__PURE__ */ new Set());
	const [isSyncingAll, setIsSyncingAll] = useState(false);
	const { syncAccount } = useSyncSnapshotAccount();
	if (!document) return /* @__PURE__ */ jsx("div", { children: "Loading..." });
	const { reportName, startDate, endDate, snapshotAccounts, accountsDocumentId, ownerIds, reportPeriodStart } = document.state.global;
	const accountsDocuments = documentsInDrive ? documentsInDrive.filter((doc) => doc.header.documentType === "powerhouse/accounts") : [];
	const selectedAccountsDoc = accountsDocuments.find((doc) => doc.header.id === accountsDocumentId);
	const availableAccounts = selectedAccountsDoc ? selectedAccountsDoc.state.global?.accounts || [] : [];
	const existingAccountIds = new Set(snapshotAccounts.map((acc) => acc.accountId));
	const accountEntryMap = new Map(availableAccounts.map((acc) => [acc.id, acc]));
	const [selectedPeriod, setSelectedPeriod] = useState(() => {
		if (reportPeriodStart) {
			const date = new Date(reportPeriodStart);
			return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
		}
		const now = /* @__PURE__ */ new Date();
		return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, "0")}`;
	});
	const savedPeriod = useMemo(() => {
		if (reportPeriodStart) {
			const date = new Date(reportPeriodStart);
			return `${date.getUTCFullYear()}-${String(date.getUTCMonth() + 1).padStart(2, "0")}`;
		}
		return "";
	}, [reportPeriodStart]);
	const [isEditingPeriod, setIsEditingPeriod] = useState(!savedPeriod);
	const isPeriodChanged = selectedPeriod !== savedPeriod;
	const suggestedStartDate = useMemo(() => {
		if (!documentsInDrive || !reportPeriodStart) return null;
		const currentPeriodStart = new Date(reportPeriodStart);
		if (isNaN(currentPeriodStart.getTime())) return null;
		const otherSnapshots = documentsInDrive.filter((doc) => doc.header.documentType === "powerhouse/snapshot-report" && doc.header.id !== document.header.id);
		let previousSnapshot = null;
		let closestDistance = Infinity;
		for (const snap of otherSnapshots) {
			const state = snap.state;
			const rps = state?.global?.reportPeriodStart;
			if (!rps) continue;
			const rpDate = new Date(rps);
			if (isNaN(rpDate.getTime())) continue;
			const diff = currentPeriodStart.getTime() - rpDate.getTime();
			if (diff > 0 && diff < closestDistance) {
				closestDistance = diff;
				previousSnapshot = {
					endDate: state?.global?.endDate || null,
					reportPeriodStart: rps
				};
			}
		}
		if (!previousSnapshot?.endDate) return null;
		const prevEnd = new Date(previousSnapshot.endDate);
		if (isNaN(prevEnd.getTime())) return null;
		const suggested = new Date(prevEnd);
		suggested.setUTCDate(suggested.getUTCDate() + 1);
		suggested.setUTCHours(0, 0, 0, 0);
		return suggested;
	}, [
		documentsInDrive,
		reportPeriodStart,
		document.header.id
	]);
	const suggestedEndDate = useMemo(() => {
		if (!documentsInDrive || !reportPeriodStart) return null;
		const currentPeriodStart = new Date(reportPeriodStart);
		if (isNaN(currentPeriodStart.getTime())) return null;
		const otherSnapshots = documentsInDrive.filter((doc) => doc.header.documentType === "powerhouse/snapshot-report" && doc.header.id !== document.header.id);
		let nextSnapshot = null;
		let closestDistance = Infinity;
		for (const snap of otherSnapshots) {
			const state = snap.state;
			const rps = state?.global?.reportPeriodStart;
			if (!rps) continue;
			const rpDate = new Date(rps);
			if (isNaN(rpDate.getTime())) continue;
			const diff = rpDate.getTime() - currentPeriodStart.getTime();
			if (diff > 0 && diff < closestDistance) {
				closestDistance = diff;
				nextSnapshot = {
					startDate: state?.global?.startDate || null,
					reportPeriodStart: rps
				};
			}
		}
		if (!nextSnapshot?.startDate) return null;
		const nextStart = new Date(nextSnapshot.startDate);
		if (isNaN(nextStart.getTime())) return null;
		const suggested = new Date(nextStart);
		suggested.setUTCDate(suggested.getUTCDate() - 1);
		suggested.setUTCHours(23, 59, 59, 999);
		return suggested;
	}, [
		documentsInDrive,
		reportPeriodStart,
		document.header.id
	]);
	const handleSnapshotPeriodChange = useCallback((newFromDate, newToDate) => {
		dispatch?.(setReportConfig({
			startDate: newFromDate,
			endDate: newToDate,
			reportName: reportName || void 0,
			accountsDocumentId: accountsDocumentId || void 0
		}));
	}, [
		dispatch,
		reportName,
		accountsDocumentId
	]);
	const handleApplySuggestedStartDate = useCallback(() => {
		if (!suggestedStartDate) return;
		handleSnapshotPeriodChange(suggestedStartDate.toISOString(), endDate || "");
	}, [
		suggestedStartDate,
		endDate,
		handleSnapshotPeriodChange
	]);
	const handleApplySuggestedEndDate = useCallback(() => {
		if (!suggestedEndDate) return;
		handleSnapshotPeriodChange(startDate || "", suggestedEndDate.toISOString());
	}, [
		suggestedEndDate,
		startDate,
		handleSnapshotPeriodChange
	]);
	useEffect(() => {
		if (savedPeriod && savedPeriod !== selectedPeriod) setSelectedPeriod(savedPeriod);
	}, [savedPeriod]);
	const handlePeriodChange = (value) => {
		setSelectedPeriod(value);
	};
	const handleConfirmPeriod = () => {
		const { periodStart, periodEnd } = getMonthDateRange(selectedPeriod);
		const [year, month] = selectedPeriod.split("-").map(Number);
		const monthLabel = `${[
			"January",
			"February",
			"March",
			"April",
			"May",
			"June",
			"July",
			"August",
			"September",
			"October",
			"November",
			"December"
		][month - 1]} ${year}`;
		dispatch?.(setPeriodStart({ periodStart }));
		dispatch?.(setPeriodEnd({ periodEnd }));
		dispatch?.(setName(`${monthLabel} - Snapshot Report`));
		setIsEditingPeriod(false);
	};
	const handleEditPeriod = () => {
		setIsEditingPeriod(true);
	};
	const monthOptions = useMemo(() => generateMonthOptions(), []);
	const periodDisplayLabel = useMemo(() => {
		const option = monthOptions.find((opt) => opt.value === selectedPeriod);
		return option ? option.label : selectedPeriod;
	}, [selectedPeriod, monthOptions]);
	const handleSyncAccount = async (snapshotAccount) => {
		if (!startDate || !endDate) {
			alert("Please set the Snapshot Period (start and end dates) before syncing");
			return;
		}
		setSyncingAccounts((prev) => new Set(prev).add(snapshotAccount.id));
		try {
			const accountEntry = accountEntryMap.get(snapshotAccount.accountId);
			const result = await syncAccount(snapshotAccount, accountEntry, accountsDocumentId || void 0, startDate, endDate, dispatch, snapshotAccounts, document?.header?.id);
			if (result.success) {
				if (result.documentId && accountEntry && accountsDocumentId) await dispatchActions([actions.updateAccount({
					id: accountEntry.id,
					accountTransactionsId: result.documentId
				})], accountsDocumentId);
			} else alert(`Sync failed: ${result.message}`);
		} catch (error) {
			console.error("Error syncing account:", error);
			alert(`Error: ${error instanceof Error ? error.message : "Unknown error"}`);
		} finally {
			setSyncingAccounts((prev) => {
				const newSet = new Set(prev);
				newSet.delete(snapshotAccount.id);
				return newSet;
			});
		}
	};
	const handleSyncAll = async () => {
		if (!startDate || !endDate) {
			alert("Please set the Snapshot Period (start and end dates) before syncing");
			return;
		}
		setIsSyncingAll(true);
		const accountUpdates = [];
		const totalAccounts = snapshotAccounts.length;
		let syncedCount = 0;
		let failedCount = 0;
		toast$1(`Syncing ${totalAccounts} accounts...`, { type: "connect-loading" });
		try {
			const internalAccounts = snapshotAccounts.filter((a) => a.type === "Internal");
			const accountTransactionsIdMap = /* @__PURE__ */ new Map();
			let latestSnapshotDoc;
			for (const account of internalAccounts) {
				const accountEntry = accountEntryMap.get(account.accountId);
				setSyncingAccounts((prev) => new Set(prev).add(account.id));
				try {
					const result = await syncAccount(account, accountEntry, accountsDocumentId || void 0, startDate, endDate, dispatch, snapshotAccounts, document?.header?.id);
					if (result.documentId) {
						accountTransactionsIdMap.set(account.id, result.documentId);
						if (accountEntry) accountUpdates.push({
							id: accountEntry.id,
							accountTransactionsId: result.documentId
						});
					}
					if (result.updatedSnapshotDoc) latestSnapshotDoc = result.updatedSnapshotDoc;
					if (result.success) syncedCount++;
					else failedCount++;
				} finally {
					setSyncingAccounts((prev) => {
						const newSet = new Set(prev);
						newSet.delete(account.id);
						return newSet;
					});
				}
			}
			const freshSnapshotAccounts = latestSnapshotDoc?.state?.global?.snapshotAccounts ?? snapshotAccounts;
			const freshNonInternalAccounts = freshSnapshotAccounts.filter((a) => a.type !== "Internal");
			for (const account of freshNonInternalAccounts) {
				const accountEntry = accountEntryMap.get(account.accountId);
				setSyncingAccounts((prev) => new Set(prev).add(account.id));
				try {
					if ((await syncAccount(account, accountEntry, accountsDocumentId || void 0, startDate, endDate, dispatch, freshSnapshotAccounts, document?.header?.id, accountTransactionsIdMap)).success) syncedCount++;
					else failedCount++;
				} finally {
					setSyncingAccounts((prev) => {
						const newSet = new Set(prev);
						newSet.delete(account.id);
						return newSet;
					});
				}
			}
			if (accountUpdates.length > 0 && accountsDocumentId) await dispatchActions(accountUpdates.map((u) => actions.updateAccount(u)), accountsDocumentId);
			if (failedCount === 0) toast$1(`Synced ${syncedCount} account${syncedCount !== 1 ? "s" : ""} successfully`, { type: "success" });
			else toast$1(`Synced ${syncedCount}/${totalAccounts} accounts. ${failedCount} failed.`, { type: "warning" });
		} catch (error) {
			toast$1(`Sync failed: ${error instanceof Error ? error.message : "Unknown error"}`, { type: "error" });
		} finally {
			setIsSyncingAll(false);
		}
	};
	const handleSetReportName = (name) => {
		dispatch?.(setReportConfig({
			reportName: name,
			startDate: startDate || void 0,
			endDate: endDate || void 0,
			accountsDocumentId: void 0
		}));
	};
	const handleToggleAccountExpansion = (accountId) => {
		setExpandedAccounts((prev) => {
			const newSet = new Set(prev);
			if (newSet.has(accountId)) newSet.delete(accountId);
			else newSet.add(accountId);
			return newSet;
		});
	};
	const handleOpenAccountPicker = () => {
		if (!accountsDocumentId) {
			alert("Please select an Accounts document first");
			return;
		}
		setIsAccountPickerOpen(true);
		setSelectedAccountIds(/* @__PURE__ */ new Set());
	};
	const handleToggleAccount = (accountId) => {
		const newSelection = new Set(selectedAccountIds);
		if (newSelection.has(accountId)) newSelection.delete(accountId);
		else newSelection.add(accountId);
		setSelectedAccountIds(newSelection);
	};
	const handleSelectAllAccounts = () => {
		setSelectedAccountIds(new Set(availableAccounts.filter((account) => !existingAccountIds.has(account.id)).map((account) => account.id)));
	};
	const handleImportAccounts = async () => {
		if (!documentsInDrive || !startDate || !endDate) {
			alert("Please set the report period (start and end dates) before importing accounts");
			return;
		}
		const start = new Date(startDate);
		const end = new Date(endDate);
		const newlyImportedAccounts = [];
		const allAccountsForLookup = [...snapshotAccounts, ...Array.from(selectedAccountIds).map((accountId) => {
			const account = availableAccounts.find((acc) => acc.id === accountId);
			if (account && !existingAccountIds.has(accountId) && account.type) return {
				id: generateId(),
				accountId: account.id,
				accountAddress: account.account,
				accountName: account.name,
				type: account.type,
				accountTransactionsId: account.accountTransactionsId || null,
				startingBalances: [],
				endingBalances: [],
				transactions: []
			};
			return null;
		}).filter(Boolean)];
		for (const accountId of selectedAccountIds) {
			const account = availableAccounts.find((acc) => acc.id === accountId);
			if (account && !existingAccountIds.has(accountId)) {
				if (!account.type) {
					alert(`Account "${account.name}" does not have a type set. Please update the account first.`);
					continue;
				}
				const snapshotAccountId = generateId();
				dispatch?.(addSnapshotAccount({
					id: snapshotAccountId,
					accountId: account.id,
					accountAddress: account.account,
					accountName: account.name,
					type: account.type,
					accountTransactionsId: account.accountTransactionsId || void 0
				}));
				newlyImportedAccounts.push({
					snapshotAccountId,
					accountAddress: account.account,
					accountType: account.type,
					accountTransactionsId: account.accountTransactionsId
				});
				if (account.type === "Internal" && account.accountTransactionsId) {
					const txDoc = documentsInDrive.find((doc) => doc.header.id === account.accountTransactionsId && doc.header.documentType === "powerhouse/account-transactions");
					if (txDoc?.state?.global?.transactions) {
						const filteredTransactions = txDoc.state.global.transactions.filter((tx) => {
							if (!tx?.datetime) return false;
							const txDate = new Date(tx.datetime);
							if (isNaN(txDate.getTime())) return false;
							return txDate >= start && txDate <= end;
						});
						for (const tx of filteredTransactions) {
							const { flowType, counterPartyAccountId } = calculateTransactionFlowInfo(tx.direction, account.type, tx.counterParty, allAccountsForLookup);
							dispatch?.(addTransaction({
								accountId: snapshotAccountId,
								id: generateId(),
								transactionId: tx.id,
								counterParty: tx.counterParty || void 0,
								amount: tx.amount,
								datetime: tx.datetime,
								txHash: tx.details?.txHash || "",
								token: tx.details?.token || "",
								blockNumber: tx.details?.blockNumber || void 0,
								direction: tx.direction,
								flowType,
								counterPartyAccountId: counterPartyAccountId || void 0
							}));
						}
					}
				}
			}
		}
		setIsAccountPickerOpen(false);
		setSelectedAccountIds(/* @__PURE__ */ new Set());
	};
	const parentFolder = useParentFolderForSelectedNode();
	function handleClose() {
		setSelectedNode(parentFolder?.id);
	}
	return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(DocumentToolbar, {
		document,
		onClose: handleClose
	}), /* @__PURE__ */ jsxs("div", {
		className: "p-6 max-w-7xl mx-auto",
		children: [
			/* @__PURE__ */ jsx("h1", {
				className: "text-3xl font-bold mb-6",
				children: "Snapshot Report"
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "bg-white rounded-lg shadow p-6 mb-6",
				children: [/* @__PURE__ */ jsx("h2", {
					className: "text-xl font-semibold mb-4",
					children: "Report Configuration"
				}), /* @__PURE__ */ jsxs("div", {
					className: "space-y-4",
					children: [
						/* @__PURE__ */ jsxs("div", {
							className: "grid grid-cols-1 md:grid-cols-2 gap-4",
							children: [
								/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("label", {
									className: "block text-sm font-medium text-gray-700 mb-2",
									children: "Report Name"
								}), /* @__PURE__ */ jsx("input", {
									type: "text",
									value: reportName || "",
									onChange: (e) => handleSetReportName(e.target.value),
									className: "w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",
									placeholder: "Q4 2024 Treasury Report"
								})] }),
								/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("label", {
									className: "block text-sm font-medium text-gray-700 mb-2",
									children: "Teams"
								}), /* @__PURE__ */ jsx(SetOwner, {
									ownerIds: ownerIds ?? [],
									dispatch
								})] }),
								/* @__PURE__ */ jsxs("div", { children: [
									/* @__PURE__ */ jsx("label", {
										className: "block text-sm font-medium text-gray-700 mb-2",
										children: "Accounts Document"
									}),
									/* @__PURE__ */ jsxs("select", {
										value: accountsDocumentId || "",
										onChange: (e) => dispatch?.(setReportConfig({
											accountsDocumentId: e.target.value || void 0,
											reportName: reportName || void 0,
											startDate: startDate || void 0,
											endDate: endDate || void 0
										})),
										className: "w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500",
										children: [/* @__PURE__ */ jsx("option", {
											value: "",
											children: "Select an Accounts document..."
										}), accountsDocuments.map((doc) => /* @__PURE__ */ jsx("option", {
											value: doc.header.id,
											children: doc.header.name || `Accounts (${doc.header.id.slice(0, 8)}...)`
										}, doc.header.id))]
									}),
									selectedAccountsDoc && /* @__PURE__ */ jsxs("p", {
										className: "text-xs text-gray-500 mt-1",
										children: [
											selectedAccountsDoc.state.global?.accounts?.length || 0,
											" ",
											"accounts available"
										]
									})
								] })
							]
						}),
						/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("label", {
							className: "block text-sm font-medium text-gray-700 mb-2",
							children: "Reporting Period"
						}), isEditingPeriod ? /* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-2",
							children: [/* @__PURE__ */ jsx(Select, {
								options: monthOptions,
								value: selectedPeriod,
								onChange: (value) => handlePeriodChange(value),
								className: "min-w-[180px]"
							}), isPeriodChanged && /* @__PURE__ */ jsx(Button, {
								variant: "default",
								onClick: handleConfirmPeriod,
								className: "text-sm",
								children: "Set Period"
							})]
						}) : /* @__PURE__ */ jsxs("div", {
							className: "flex items-center gap-2",
							children: [/* @__PURE__ */ jsx("span", {
								className: "text-lg font-bold text-gray-900",
								children: periodDisplayLabel
							}), /* @__PURE__ */ jsx(Button, {
								variant: "ghost",
								onClick: handleEditPeriod,
								className: "text-sm",
								children: "Change"
							})]
						})] }),
						/* @__PURE__ */ jsxs("div", { children: [
							/* @__PURE__ */ jsx(DateRangePicker, {
								label: "Snapshot Period",
								fromDate: startDate || "",
								toDate: endDate || "",
								onChange: handleSnapshotPeriodChange
							}),
							suggestedStartDate && (!startDate || startDate.split("T")[0] !== suggestedStartDate.toISOString().split("T")[0]) && /* @__PURE__ */ jsxs("div", {
								className: "mt-2 flex items-center gap-2 p-2 bg-indigo-50 border border-indigo-200 rounded-md",
								children: [/* @__PURE__ */ jsxs("span", {
									className: "text-xs text-indigo-700 flex-1",
									children: [
										"Previous snapshot period ends",
										" ",
										(/* @__PURE__ */ new Date(suggestedStartDate.getTime() - 864e5)).toLocaleDateString("en-US", {
											month: "short",
											day: "numeric",
											timeZone: "UTC"
										}),
										". Start from",
										" ",
										/* @__PURE__ */ jsx("strong", { children: suggestedStartDate.toLocaleDateString("en-US", {
											month: "short",
											day: "numeric",
											timeZone: "UTC"
										}) }),
										" ",
										"to avoid gaps."
									]
								}), /* @__PURE__ */ jsx("button", {
									onClick: handleApplySuggestedStartDate,
									className: "px-2 py-1 text-xs font-medium text-indigo-700 bg-indigo-100 hover:bg-indigo-200 rounded transition-colors whitespace-nowrap",
									children: "Apply"
								})]
							}),
							suggestedEndDate && endDate && new Date(endDate) >= suggestedEndDate && /* @__PURE__ */ jsxs("div", {
								className: "mt-2 flex items-center gap-2 p-2 bg-amber-50 border border-amber-200 rounded-md",
								children: [/* @__PURE__ */ jsxs("span", {
									className: "text-xs text-amber-700 flex-1",
									children: [
										"Next snapshot period starts",
										" ",
										new Date(suggestedEndDate.getTime() + 864e5).toLocaleDateString("en-US", {
											month: "short",
											day: "numeric",
											timeZone: "UTC"
										}),
										". End by",
										" ",
										/* @__PURE__ */ jsx("strong", { children: suggestedEndDate.toLocaleDateString("en-US", {
											month: "short",
											day: "numeric",
											timeZone: "UTC"
										}) }),
										" ",
										"to avoid overlap."
									]
								}), /* @__PURE__ */ jsx("button", {
									onClick: handleApplySuggestedEndDate,
									className: "px-2 py-1 text-xs font-medium text-amber-700 bg-amber-100 hover:bg-amber-200 rounded transition-colors whitespace-nowrap",
									children: "Apply"
								})]
							})
						] })
					]
				})]
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "bg-white rounded-lg shadow p-6",
				children: [/* @__PURE__ */ jsxs("div", {
					className: "flex justify-between items-center mb-4",
					children: [/* @__PURE__ */ jsx("h2", {
						className: "text-xl font-semibold",
						children: "Snapshot Accounts"
					}), /* @__PURE__ */ jsxs("div", {
						className: "flex gap-2",
						children: [snapshotAccounts.length > 0 && /* @__PURE__ */ jsxs("button", {
							onClick: handleSyncAll,
							disabled: isSyncingAll || !startDate || !endDate,
							className: "px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:bg-gray-400 disabled:cursor-not-allowed flex items-center gap-2",
							children: [/* @__PURE__ */ jsx(RefreshCw, { className: `w-4 h-4 ${isSyncingAll ? "animate-spin" : ""}` }), "Sync All"]
						}), /* @__PURE__ */ jsx("button", {
							onClick: handleOpenAccountPicker,
							disabled: !accountsDocumentId,
							className: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-400 disabled:cursor-not-allowed",
							children: "Add Account"
						})]
					})]
				}), snapshotAccounts.length === 0 ? /* @__PURE__ */ jsxs("div", {
					className: "text-center py-12 text-gray-500",
					children: [/* @__PURE__ */ jsx("p", { children: "No accounts added yet" }), /* @__PURE__ */ jsx("p", {
						className: "text-sm mt-2",
						children: "Click \"Add Account\" to select accounts for this snapshot"
					})]
				}) : /* @__PURE__ */ jsx("div", {
					className: "space-y-6",
					children: [
						{
							type: "Source",
							label: "Source",
							borderClass: "border-emerald-300",
							badgeClass: "bg-emerald-100 text-emerald-800"
						},
						{
							type: "Internal",
							label: "Internal",
							borderClass: "border-blue-300",
							badgeClass: "bg-blue-100 text-blue-800"
						},
						{
							type: "Destination",
							label: "Destination",
							borderClass: "border-amber-300",
							badgeClass: "bg-amber-100 text-amber-800"
						},
						{
							type: "External",
							label: "External",
							borderClass: "border-gray-300",
							badgeClass: "bg-gray-100 text-gray-800"
						}
					].map(({ type, label, borderClass, badgeClass }) => {
						const accountsOfType = snapshotAccounts.filter((a) => a.type === type);
						if (accountsOfType.length === 0) return null;
						return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("div", {
							className: `flex items-center gap-2 mb-3 pb-2 border-b-2 ${borderClass}`,
							children: [/* @__PURE__ */ jsx("span", {
								className: `px-2 py-0.5 text-xs font-semibold rounded ${badgeClass}`,
								children: label
							}), /* @__PURE__ */ jsxs("span", {
								className: "text-sm text-gray-500",
								children: [
									accountsOfType.length,
									" account",
									accountsOfType.length !== 1 ? "s" : ""
								]
							})]
						}), /* @__PURE__ */ jsx("div", {
							className: "space-y-4",
							children: accountsOfType.map((account) => /* @__PURE__ */ jsxs("div", {
								className: "border border-gray-200 rounded-lg overflow-hidden",
								children: [/* @__PURE__ */ jsxs("div", {
									className: "p-4",
									children: [
										/* @__PURE__ */ jsxs("div", {
											className: "flex justify-between items-start",
											children: [/* @__PURE__ */ jsxs("div", {
												className: "flex-1",
												children: [
													/* @__PURE__ */ jsxs("div", {
														className: "flex items-center gap-2 mb-2",
														children: [/* @__PURE__ */ jsx("h3", {
															className: "font-semibold",
															children: account.accountName
														}), /* @__PURE__ */ jsx("button", {
															onClick: () => handleSyncAccount(account),
															disabled: syncingAccounts.has(account.id) || !startDate || !endDate,
															className: "p-1.5 rounded-md hover:bg-gray-100 disabled:opacity-50 disabled:cursor-not-allowed",
															title: "Sync account transactions and balances",
															children: /* @__PURE__ */ jsx(RefreshCw, { className: `w-4 h-4 ${syncingAccounts.has(account.id) ? "animate-spin text-blue-600" : "text-gray-600"}` })
														})]
													}),
													/* @__PURE__ */ jsx("p", {
														className: "text-sm text-gray-600",
														children: account.accountAddress
													}),
													/* @__PURE__ */ jsx("span", {
														className: `inline-block mt-2 px-3 py-1 text-xs font-medium rounded-full ${account.type === "Source" ? "bg-emerald-100 text-emerald-800" : account.type === "Internal" ? "bg-blue-100 text-blue-800" : account.type === "Destination" ? "bg-amber-100 text-amber-800" : "bg-gray-100 text-gray-800"}`,
														children: account.type
													})
												]
											}), /* @__PURE__ */ jsxs("div", {
												className: "text-right",
												children: [/* @__PURE__ */ jsxs("p", {
													className: "text-sm text-gray-600",
													children: ["Transactions: ", account.transactions.length]
												}), /* @__PURE__ */ jsxs("p", {
													className: "text-sm text-gray-600",
													children: ["Tokens: ", account.startingBalances.length]
												})]
											})]
										}),
										(() => {
											const isNonZero = (amount) => {
												return parseFloat(amount?.value || "0") !== 0;
											};
											const nonZeroStarting = account.startingBalances.filter((b) => {
												const endingBalance = account.endingBalances.find((eb) => eb.token === b.token);
												return isNonZero(b.amount) || endingBalance && isNonZero(endingBalance.amount);
											});
											const endingOnlyBalances = account.endingBalances.filter((eb) => !account.startingBalances.some((sb) => sb.token === eb.token) && isNonZero(eb.amount));
											if (!(nonZeroStarting.length > 0 || endingOnlyBalances.length > 0)) return null;
											return /* @__PURE__ */ jsxs("div", {
												className: "mt-4 pt-4 border-t border-gray-200",
												children: [/* @__PURE__ */ jsx("h4", {
													className: "text-sm font-semibold text-gray-700 mb-2",
													children: "Balances"
												}), /* @__PURE__ */ jsxs("div", {
													className: "grid grid-cols-1 md:grid-cols-2 gap-3",
													children: [nonZeroStarting.map((balance) => {
														const endingBalance = account.endingBalances.find((eb) => eb.token === balance.token);
														return /* @__PURE__ */ jsxs("div", {
															className: "bg-gray-50 rounded p-2 text-sm",
															children: [/* @__PURE__ */ jsx("div", {
																className: "font-medium text-gray-700 mb-1",
																children: balance.token
															}), /* @__PURE__ */ jsxs("div", {
																className: "text-xs text-gray-600 space-y-1",
																style: { fontVariantNumeric: "tabular-nums" },
																children: [/* @__PURE__ */ jsxs("div", { children: [
																	"Opening:",
																	" ",
																	/* @__PURE__ */ jsx("span", {
																		className: "font-medium",
																		children: formatBalance(balance.amount)
																	})
																] }), endingBalance && /* @__PURE__ */ jsxs("div", { children: [
																	"Closing:",
																	" ",
																	/* @__PURE__ */ jsx("span", {
																		className: "font-medium",
																		children: formatBalance(endingBalance.amount)
																	})
																] })]
															})]
														}, balance.id);
													}), endingOnlyBalances.map((balance) => /* @__PURE__ */ jsxs("div", {
														className: "bg-gray-50 rounded p-2 text-sm",
														children: [/* @__PURE__ */ jsx("div", {
															className: "font-medium text-gray-700 mb-1",
															children: balance.token
														}), /* @__PURE__ */ jsxs("div", {
															className: "text-xs text-gray-600 space-y-1",
															style: { fontVariantNumeric: "tabular-nums" },
															children: [/* @__PURE__ */ jsxs("div", { children: [
																"Opening:",
																" ",
																/* @__PURE__ */ jsxs("span", {
																	className: "font-medium",
																	children: ["0.000000 ", balance.token]
																})
															] }), /* @__PURE__ */ jsxs("div", { children: [
																"Closing:",
																" ",
																/* @__PURE__ */ jsx("span", {
																	className: "font-medium",
																	children: formatBalance(balance.amount)
																})
															] })]
														})]
													}, balance.id))]
												})]
											});
										})(),
										account.transactions.length > 0 && /* @__PURE__ */ jsx("button", {
											onClick: () => handleToggleAccountExpansion(account.id),
											className: "mt-3 flex items-center gap-2 text-sm text-blue-600 hover:text-blue-800",
											children: expandedAccounts.has(account.id) ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(ChevronUp, { className: "w-4 h-4" }), /* @__PURE__ */ jsx("span", { children: "Hide Transactions" })] }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx(ChevronDown, { className: "w-4 h-4" }), /* @__PURE__ */ jsx("span", { children: "Show Transactions" })] })
										})
									]
								}), expandedAccounts.has(account.id) && account.transactions.length > 0 && /* @__PURE__ */ jsx("div", {
									className: "border-t border-gray-200 bg-gray-50",
									children: /* @__PURE__ */ jsxs("div", {
										className: "p-4",
										children: [/* @__PURE__ */ jsxs("h4", {
											className: "text-sm font-semibold text-gray-700 mb-3",
											children: [
												"Transactions (",
												account.transactions.length,
												")"
											]
										}), /* @__PURE__ */ jsx("div", {
											className: "space-y-2",
											children: [...account.transactions].sort((a, b) => new Date(b.datetime).getTime() - new Date(a.datetime).getTime()).map((tx) => /* @__PURE__ */ jsx("div", {
												className: "bg-white border border-gray-200 rounded p-3 text-sm",
												children: /* @__PURE__ */ jsxs("div", {
													className: "grid grid-cols-2 gap-2",
													children: [
														/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
															className: "text-gray-500",
															children: "Direction:"
														}), /* @__PURE__ */ jsx("span", {
															className: `ml-2 font-medium ${tx.direction === "INFLOW" ? "text-green-600" : "text-red-600"}`,
															children: tx.direction
														})] }),
														/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
															className: "text-gray-500",
															children: "Amount:"
														}), /* @__PURE__ */ jsx("span", {
															className: "ml-2 font-medium",
															children: typeof tx.amount === "object" && tx.amount?.value !== void 0 ? `${tx.amount.value} ${tx.amount.unit || tx.token}` : `${tx.amount} ${tx.token}`
														})] }),
														/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
															className: "text-gray-500",
															children: "Date:"
														}), /* @__PURE__ */ jsx("span", {
															className: "ml-2",
															children: new Date(tx.datetime).toLocaleDateString()
														})] }),
														/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
															className: "text-gray-500",
															children: "Time:"
														}), /* @__PURE__ */ jsx("span", {
															className: "ml-2",
															children: new Date(tx.datetime).toLocaleTimeString()
														})] }),
														tx.counterParty && /* @__PURE__ */ jsxs("div", {
															className: "col-span-2",
															children: [/* @__PURE__ */ jsx("span", {
																className: "text-gray-500",
																children: "Counter Party:"
															}), /* @__PURE__ */ jsx("span", {
																className: "ml-2 font-mono text-xs",
																children: tx.counterParty
															})]
														}),
														tx.flowType && /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("span", {
															className: "text-gray-500",
															children: "Flow Type:"
														}), /* @__PURE__ */ jsx("span", {
															className: `ml-2 px-2 py-0.5 rounded text-xs font-medium ${tx.flowType === "TopUp" ? "bg-green-100 text-green-800" : tx.flowType === "Return" ? "bg-orange-100 text-orange-800" : tx.flowType === "Internal" ? "bg-purple-100 text-purple-800" : tx.flowType === "Swap" ? "bg-blue-100 text-blue-800" : "bg-red-100 text-red-800"}`,
															children: tx.flowType
														})] }),
														/* @__PURE__ */ jsxs("div", {
															className: "col-span-2",
															children: [/* @__PURE__ */ jsx("span", {
																className: "text-gray-500",
																children: "Tx Hash:"
															}), /* @__PURE__ */ jsxs("a", {
																href: `https://etherscan.io/tx/${tx.txHash}`,
																target: "_blank",
																rel: "noopener noreferrer",
																className: "ml-2 text-blue-600 hover:underline font-mono text-xs",
																children: [
																	tx.txHash.substring(0, 10),
																	"...",
																	tx.txHash.substring(tx.txHash.length - 8)
																]
															})]
														})
													]
												})
											}, tx.id))
										})]
									})
								})]
							}, account.id))
						})] }, type);
					})
				})]
			}),
			isAccountPickerOpen && /* @__PURE__ */ jsx("div", {
				className: "fixed inset-0 z-50 flex items-start justify-center pt-8 backdrop-blur-sm",
				children: /* @__PURE__ */ jsxs("div", {
					className: "bg-white rounded-lg shadow-xl max-w-2xl w-full mx-4 max-h-[85vh] flex flex-col border border-gray-200",
					children: [
						/* @__PURE__ */ jsx("div", {
							className: "p-6 border-b",
							children: /* @__PURE__ */ jsxs("div", {
								className: "flex items-center justify-between",
								children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h3", {
									className: "text-xl font-semibold",
									children: "Select Accounts to Import"
								}), /* @__PURE__ */ jsx("p", {
									className: "text-sm text-gray-600 mt-1",
									children: "Choose accounts from the selected Accounts document"
								})] }), availableAccounts.some((account) => !existingAccountIds.has(account.id)) && /* @__PURE__ */ jsx("button", {
									onClick: handleSelectAllAccounts,
									className: "px-3 py-1.5 text-sm bg-blue-600 text-white rounded-md hover:bg-blue-700 transition-colors",
									children: "Add All Accounts"
								})]
							})
						}),
						/* @__PURE__ */ jsx("div", {
							className: "p-6 overflow-y-auto flex-1",
							children: availableAccounts.length === 0 ? /* @__PURE__ */ jsx("div", {
								className: "text-center py-8 text-gray-500",
								children: "No accounts available in the selected document"
							}) : /* @__PURE__ */ jsx("div", {
								className: "space-y-2",
								children: availableAccounts.map((account) => {
									const isAlreadyAdded = existingAccountIds.has(account.id);
									const isSelected = selectedAccountIds.has(account.id);
									return /* @__PURE__ */ jsx("div", {
										onClick: () => !isAlreadyAdded && handleToggleAccount(account.id),
										className: `p-4 border rounded-lg cursor-pointer transition-colors ${isAlreadyAdded ? "bg-gray-100 cursor-not-allowed opacity-50" : isSelected ? "bg-blue-50 border-blue-500" : "hover:bg-gray-50"}`,
										children: /* @__PURE__ */ jsxs("div", {
											className: "flex items-start justify-between",
											children: [/* @__PURE__ */ jsxs("div", {
												className: "flex items-start gap-3",
												children: [/* @__PURE__ */ jsx("input", {
													type: "checkbox",
													checked: isSelected,
													disabled: isAlreadyAdded,
													onChange: () => {},
													className: "mt-1"
												}), /* @__PURE__ */ jsxs("div", { children: [
													/* @__PURE__ */ jsx("h4", {
														className: "font-medium",
														children: account.name
													}),
													/* @__PURE__ */ jsx("p", {
														className: "text-sm text-gray-600",
														children: account.account
													}),
													/* @__PURE__ */ jsx("span", {
														className: `inline-block mt-2 px-2 py-1 text-xs rounded ${account.type === "Source" ? "bg-emerald-100 text-emerald-800" : account.type === "Internal" ? "bg-blue-100 text-blue-800" : account.type === "Destination" ? "bg-amber-100 text-amber-800" : "bg-gray-100 text-gray-700"}`,
														children: account.type || "External"
													})
												] })]
											}), isAlreadyAdded && /* @__PURE__ */ jsx("span", {
												className: "text-xs text-gray-500",
												children: "Already added"
											})]
										})
									}, account.id);
								})
							})
						}),
						/* @__PURE__ */ jsxs("div", {
							className: "p-6 border-t flex justify-end gap-3",
							children: [/* @__PURE__ */ jsx("button", {
								onClick: () => {
									setIsAccountPickerOpen(false);
									setSelectedAccountIds(/* @__PURE__ */ new Set());
								},
								className: "px-4 py-2 border border-gray-300 rounded-md hover:bg-gray-50",
								children: "Cancel"
							}), /* @__PURE__ */ jsxs("button", {
								onClick: handleImportAccounts,
								disabled: selectedAccountIds.size === 0,
								className: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:bg-gray-400 disabled:cursor-not-allowed",
								children: [
									"Import",
									" ",
									selectedAccountIds.size > 0 ? `(${selectedAccountIds.size})` : ""
								]
							})]
						})
					]
				})
			})
		]
	})] });
}
//#endregion
export { Editor as default };

//# sourceMappingURL=editor-BIGCWVOd.js.map