import "./chunk-olfrzTEO.js";
import { b as generateId } from "./dist-uUUuTqM0.js";
import { a as addTransaction, c as updateTransaction, d as setAccount, s as deleteTransaction } from "./creators-1UUtt16O.js";
import { m as actions } from "./module-DJjNH-7f.js";
import { m as actions$1 } from "./module-jjo7KF-t.js";
import "./upgrade-manifest-Cg4wvNM9.js";
import "./upgrade-manifest-9amdVX9Z.js";
import { D as useParentFolderForSelectedNode, c as setSelectedNode, g as useDocumentsInSelectedDrive, h as useDocumentOfType, j as useSelectedDrive, k as useSelectedDocumentId, r as dispatchActions } from "./dist-mx7YTOSV.js";
import "./chunk-VBDAOXYI-DjbP4DfS.js";
import "./accounts-BPRp-Roc.js";
import "./expense-report-DEf9yTTk.js";
import { x as FormLabel } from "./splitted-input-diff-kvHJ6NHp.js";
import { i as DocumentToolbar } from "./connect-MjNGHHUz-BfDIyhte.js";
import { t as Button } from "./button-DVsyzSgU.js";
import { a as Form } from "./with-field-validation-DGjBGqeq.js";
import { t as SelectField } from "./select-field-CjRsIJOG.js";
import { t as StringField } from "./string-field-C7BDVciE.js";
import { n as deleteNode } from "./document-drive-BEVbKaCi.js";
import { t as alchemyIntegration } from "./alchemyIntegration-DsK1H6XE.js";
import { useState } from "react";
import { Fragment as Fragment$1, jsx, jsxs } from "react/jsx-runtime";
//#region editors/hooks/useAccountTransactionsDocument.ts
function useAccountTransactionsDocument(documentId) {
	return useDocumentOfType(documentId, "powerhouse/account-transactions");
}
function useSelectedAccountTransactionsDocument() {
	return useAccountTransactionsDocument(useSelectedDocumentId());
}
//#endregion
//#region editors/account-transactions-editor/components/TransactionsTable.tsx
function TransactionsTable({ transactions, onEdit, onDelete }) {
	const sortedTransactions = [...transactions].sort((a, b) => {
		const dateA = new Date(a.datetime).getTime();
		return new Date(b.datetime).getTime() - dateA;
	});
	function formatAmount(amount) {
		try {
			if (typeof amount === "object" && amount.value) {
				const num = parseFloat(amount.value);
				return new Intl.NumberFormat("en-US", {
					minimumFractionDigits: 2,
					maximumFractionDigits: 6
				}).format(num);
			} else if (typeof amount === "string") {
				const num = parseFloat(amount);
				return new Intl.NumberFormat("en-US", {
					minimumFractionDigits: 2,
					maximumFractionDigits: 6
				}).format(num);
			}
			return typeof amount === "object" ? JSON.stringify(amount) : String(amount);
		} catch {
			return typeof amount === "object" ? JSON.stringify(amount) : String(amount);
		}
	}
	function formatDate(dateString) {
		try {
			return new Date(dateString).toLocaleDateString("en-US", {
				year: "numeric",
				month: "short",
				day: "numeric",
				hour: "2-digit",
				minute: "2-digit"
			});
		} catch {
			return dateString;
		}
	}
	if (transactions.length === 0) return /* @__PURE__ */ jsxs("div", {
		className: "bg-white rounded-xl border border-gray-200 p-12 text-center",
		children: [
			/* @__PURE__ */ jsx("svg", {
				className: "mx-auto h-12 w-12 text-gray-400",
				fill: "none",
				stroke: "currentColor",
				viewBox: "0 0 24 24",
				children: /* @__PURE__ */ jsx("path", {
					strokeLinecap: "round",
					strokeLinejoin: "round",
					strokeWidth: 2,
					d: "M9 5H7a2 2 0 00-2 2v10a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"
				})
			}),
			/* @__PURE__ */ jsx("h3", {
				className: "mt-4 text-lg font-medium text-gray-900",
				children: "No transactions yet"
			}),
			/* @__PURE__ */ jsx("p", {
				className: "mt-2 text-sm text-gray-600",
				children: "Get started by adding your first transaction"
			})
		]
	});
	return /* @__PURE__ */ jsx("div", {
		className: "bg-white rounded-xl border border-gray-200 overflow-hidden",
		children: /* @__PURE__ */ jsx("div", {
			className: "overflow-x-auto",
			children: /* @__PURE__ */ jsxs("table", {
				className: "min-w-full divide-y divide-gray-200",
				children: [/* @__PURE__ */ jsx("thead", {
					className: "bg-gray-50",
					children: /* @__PURE__ */ jsxs("tr", { children: [
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Date"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Counter Party"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Amount"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Direction"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Token"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Tx Hash"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Period"
						}),
						/* @__PURE__ */ jsx("th", {
							className: "px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider",
							children: "Actions"
						})
					] })
				}), /* @__PURE__ */ jsx("tbody", {
					className: "bg-white divide-y divide-gray-200",
					children: sortedTransactions.map((transaction) => /* @__PURE__ */ jsxs("tr", {
						className: "hover:bg-gray-50",
						children: [
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900",
								children: formatDate(transaction.datetime)
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900",
								children: transaction.counterParty ? /* @__PURE__ */ jsxs("span", {
									className: "font-mono text-xs bg-gray-100 px-2 py-1 rounded",
									children: [
										transaction.counterParty.slice(0, 8),
										"...",
										transaction.counterParty.slice(-6)
									]
								}) : /* @__PURE__ */ jsx("span", {
									className: "text-gray-400",
									children: "—"
								})
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-mono",
								children: formatAmount(transaction.amount)
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900",
								children: /* @__PURE__ */ jsx("span", {
									className: `inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${transaction.direction === "INFLOW" ? "bg-green-100 text-green-800" : "bg-red-100 text-red-800"}`,
									children: transaction.direction === "INFLOW" ? /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("svg", {
										className: "w-3 h-3 mr-1",
										fill: "currentColor",
										viewBox: "0 0 20 20",
										children: /* @__PURE__ */ jsx("path", {
											fillRule: "evenodd",
											d: "M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z",
											clipRule: "evenodd"
										})
									}), "IN"] }) : /* @__PURE__ */ jsxs(Fragment$1, { children: [/* @__PURE__ */ jsx("svg", {
										className: "w-3 h-3 mr-1",
										fill: "currentColor",
										viewBox: "0 0 20 20",
										children: /* @__PURE__ */ jsx("path", {
											fillRule: "evenodd",
											d: "M4 10a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1z",
											clipRule: "evenodd"
										})
									}), "OUT"] })
								})
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900",
								children: /* @__PURE__ */ jsx("span", {
									className: "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800",
									children: transaction.details.token
								})
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900",
								children: transaction.details.txHash ? /* @__PURE__ */ jsxs("a", {
									href: `https://etherscan.io/tx/${transaction.details.txHash}`,
									target: "_blank",
									rel: "noopener noreferrer",
									className: "font-mono text-xs text-blue-600 hover:text-blue-800 underline",
									children: [transaction.details.txHash.slice(0, 10), "..."]
								}) : /* @__PURE__ */ jsx("span", {
									className: "text-gray-400",
									children: "—"
								})
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-sm text-gray-900",
								children: transaction.accountingPeriod
							}),
							/* @__PURE__ */ jsx("td", {
								className: "px-6 py-4 whitespace-nowrap text-right text-sm font-medium",
								children: /* @__PURE__ */ jsxs("div", {
									className: "flex items-center justify-end gap-2",
									children: [/* @__PURE__ */ jsx(Button, {
										onClick: () => onEdit(transaction),
										className: "bg-blue-600 hover:bg-blue-700 text-white px-3 py-1 text-xs",
										children: "Edit"
									}), /* @__PURE__ */ jsx(Button, {
										onClick: () => onDelete(transaction.id),
										className: "bg-red-600 hover:bg-red-700 text-white px-3 py-1 text-xs",
										children: "Delete"
									})]
								})
							})
						]
					}, transaction.id))
				})]
			})
		})
	});
}
//#endregion
//#region editors/account-transactions-editor/components/TransactionForm.tsx
function TransactionForm({ transaction, budgets, onSubmit, onCancel }) {
	const isEditing = !!transaction;
	const defaultValues = transaction ? {
		id: transaction.id,
		counterParty: transaction.counterParty || "",
		amount: typeof transaction.amount === "object" ? transaction.amount.value : transaction.amount,
		datetime: new Date(transaction.datetime).toISOString().slice(0, 16),
		txHash: transaction.details.txHash,
		token: transaction.details.token,
		blockNumber: transaction.details.blockNumber?.toString() || "",
		budget: transaction.budget || "",
		accountingPeriod: transaction.accountingPeriod,
		direction: transaction.direction || "OUTFLOW"
	} : {
		counterParty: "",
		amount: "",
		datetime: (/* @__PURE__ */ new Date()).toISOString().slice(0, 16),
		txHash: "",
		token: "ETH",
		blockNumber: "",
		budget: "",
		accountingPeriod: (/* @__PURE__ */ new Date()).getFullYear().toString(),
		direction: "OUTFLOW"
	};
	function handleSubmit(values) {
		onSubmit({
			...isEditing && { id: values.id },
			counterParty: values.counterParty,
			amount: {
				unit: values.token,
				value: values.amount
			},
			datetime: new Date(values.datetime).toISOString(),
			txHash: values.txHash,
			token: values.token,
			blockNumber: values.blockNumber ? parseInt(values.blockNumber) : void 0,
			budget: values.budget || void 0,
			accountingPeriod: values.accountingPeriod,
			direction: values.direction
		});
	}
	const budgetOptions = [{
		value: "",
		label: "No Budget"
	}, ...budgets.map((budget) => ({
		value: budget.id,
		label: budget.name || `Budget ${budget.id.slice(0, 8)}`
	}))];
	return /* @__PURE__ */ jsx("div", {
		className: "bg-white rounded-xl border border-gray-200 p-6",
		children: /* @__PURE__ */ jsxs(Form, {
			onSubmit: handleSubmit,
			defaultValues,
			className: "space-y-6",
			children: [/* @__PURE__ */ jsxs("div", {
				className: "grid grid-cols-1 md:grid-cols-2 gap-6",
				children: [
					/* @__PURE__ */ jsxs("div", { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							htmlFor: "counterParty",
							required: true,
							children: "Counter Party Address"
						}),
						/* @__PURE__ */ jsx(StringField, {
							name: "counterParty",
							placeholder: "0x...",
							className: "font-mono",
							required: true
						}),
						/* @__PURE__ */ jsx("p", {
							className: "text-xs text-gray-500 mt-1",
							children: "Ethereum address of the transaction counterpart"
						})
					] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "amount",
						required: true,
						children: "Amount"
					}), /* @__PURE__ */ jsx(StringField, {
						name: "amount",
						placeholder: "0.00",
						type: "number",
						step: "any",
						required: true
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "datetime",
						required: true,
						children: "Date & Time"
					}), /* @__PURE__ */ jsx(StringField, {
						name: "datetime",
						type: "datetime-local",
						required: true
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "token",
						required: true,
						children: "Token"
					}), /* @__PURE__ */ jsx(SelectField, {
						name: "token",
						options: [
							{
								value: "ETH",
								label: "ETH"
							},
							{
								value: "USDC",
								label: "USDC"
							},
							{
								value: "USDT",
								label: "USDT"
							},
							{
								value: "DAI",
								label: "DAI"
							},
							{
								value: "WETH",
								label: "WETH"
							}
						],
						required: true
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "direction",
						required: true,
						children: "Direction"
					}), /* @__PURE__ */ jsx(SelectField, {
						name: "direction",
						options: [{
							value: "INFLOW",
							label: "Inflow (IN)"
						}, {
							value: "OUTFLOW",
							label: "Outflow (OUT)"
						}],
						required: true
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "txHash",
						required: true,
						children: "Transaction Hash"
					}), /* @__PURE__ */ jsx(StringField, {
						name: "txHash",
						placeholder: "0x...",
						className: "font-mono",
						required: true
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "blockNumber",
						children: "Block Number (Optional)"
					}), /* @__PURE__ */ jsx(StringField, {
						name: "blockNumber",
						placeholder: "18000000",
						type: "number"
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(FormLabel, {
						htmlFor: "budget",
						children: "Budget (Optional)"
					}), /* @__PURE__ */ jsx(SelectField, {
						name: "budget",
						options: budgetOptions
					})] }),
					/* @__PURE__ */ jsxs("div", { children: [
						/* @__PURE__ */ jsx(FormLabel, {
							htmlFor: "accountingPeriod",
							required: true,
							children: "Accounting Period"
						}),
						/* @__PURE__ */ jsx(StringField, {
							name: "accountingPeriod",
							placeholder: "2024",
							required: true
						}),
						/* @__PURE__ */ jsx("p", {
							className: "text-xs text-gray-500 mt-1",
							children: "Year or period for accounting purposes"
						})
					] })
				]
			}), /* @__PURE__ */ jsxs("div", {
				className: "flex items-center justify-end gap-4 pt-6 border-t border-gray-200",
				children: [/* @__PURE__ */ jsx(Button, {
					type: "button",
					onClick: onCancel,
					className: "bg-gray-300 hover:bg-gray-400 text-gray-700 px-6 py-2",
					children: "Cancel"
				}), /* @__PURE__ */ jsx(Button, {
					type: "submit",
					className: "bg-blue-600 hover:bg-blue-700 text-white px-6 py-2",
					children: isEditing ? "Update Transaction" : "Add Transaction"
				})]
			})]
		})
	});
}
//#endregion
//#region editors/account-transactions-editor/components/AccountSection.tsx
function AccountSection({ account, hasFetchedTransactions, onSetAccount }) {
	const [isEditing, setIsEditing] = useState(false);
	function handleSubmit(values) {
		if (values.address) {
			onSetAccount(values.address, values.name);
			setIsEditing(false);
		}
	}
	const hasAccount = account.account && account.account.trim() !== "";
	const isLocked = hasAccount && hasFetchedTransactions;
	return /* @__PURE__ */ jsxs("div", {
		className: "bg-white rounded-xl border border-gray-200 p-6 mb-8",
		children: [/* @__PURE__ */ jsxs("div", {
			className: "flex items-center justify-between mb-4",
			children: [/* @__PURE__ */ jsx("h2", {
				className: "text-lg font-semibold text-gray-900",
				children: "Account Settings"
			}), hasAccount && !isLocked && !isEditing && /* @__PURE__ */ jsx(Button, {
				onClick: () => setIsEditing(true),
				className: "bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 text-sm",
				children: "Change Account"
			})]
		}), !hasAccount && !isEditing ? /* @__PURE__ */ jsx("div", {
			className: "bg-yellow-50 border border-yellow-200 rounded-lg p-4",
			children: /* @__PURE__ */ jsxs("div", {
				className: "flex items-center",
				children: [
					/* @__PURE__ */ jsx("svg", {
						className: "h-5 w-5 text-yellow-400 mr-3",
						fill: "none",
						stroke: "currentColor",
						viewBox: "0 0 24 24",
						children: /* @__PURE__ */ jsx("path", {
							strokeLinecap: "round",
							strokeLinejoin: "round",
							strokeWidth: 2,
							d: "M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"
						})
					}),
					/* @__PURE__ */ jsxs("div", {
						className: "flex-1",
						children: [/* @__PURE__ */ jsx("h3", {
							className: "text-sm font-medium text-yellow-800",
							children: "No Account Set"
						}), /* @__PURE__ */ jsx("p", {
							className: "text-sm text-yellow-700 mt-1",
							children: "Set an Ethereum address to start tracking transactions for this account."
						})]
					}),
					/* @__PURE__ */ jsx(Button, {
						onClick: () => setIsEditing(true),
						className: "ml-4 bg-yellow-600 hover:bg-yellow-700 text-white px-4 py-2 text-sm",
						children: "Set Account"
					})
				]
			})
		}) : hasAccount && !isEditing ? /* @__PURE__ */ jsx("div", {
			className: "bg-green-50 border border-green-200 rounded-lg p-4",
			children: /* @__PURE__ */ jsxs("div", {
				className: "flex items-center",
				children: [/* @__PURE__ */ jsx("svg", {
					className: "h-5 w-5 text-green-400 mr-3",
					fill: "none",
					stroke: "currentColor",
					viewBox: "0 0 24 24",
					children: /* @__PURE__ */ jsx("path", {
						strokeLinecap: "round",
						strokeLinejoin: "round",
						strokeWidth: 2,
						d: "M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"
					})
				}), /* @__PURE__ */ jsxs("div", {
					className: "flex-1",
					children: [
						/* @__PURE__ */ jsxs("h3", {
							className: "text-sm font-medium text-green-800",
							children: ["Account Configured", isLocked && " (Locked)"]
						}),
						/* @__PURE__ */ jsx("p", {
							className: "text-sm text-green-700 mt-1 font-mono break-all",
							children: account.account
						}),
						account.name && /* @__PURE__ */ jsxs("p", {
							className: "text-sm text-green-600 mt-1",
							children: ["Name: ", account.name]
						}),
						isLocked && /* @__PURE__ */ jsx("p", {
							className: "text-xs text-gray-600 mt-2",
							children: "Account is locked after fetching transactions. Create a new document to use a different account."
						})
					]
				})]
			})
		}) : /* @__PURE__ */ jsxs(Form, {
			onSubmit: handleSubmit,
			defaultValues: {
				address: account.account || "",
				name: account.name || ""
			},
			className: "space-y-4",
			children: [
				isLocked && /* @__PURE__ */ jsx("p", {
					className: "text-sm text-gray-600",
					children: "Account changes are disabled after transactions have been fetched."
				}),
				/* @__PURE__ */ jsxs("div", { children: [
					/* @__PURE__ */ jsx("label", {
						className: "block text-sm font-medium text-gray-700 mb-2",
						children: "Ethereum Address *"
					}),
					/* @__PURE__ */ jsx(StringField, {
						name: "address",
						placeholder: "0x...",
						className: "w-full font-mono",
						required: true,
						disabled: Boolean(isLocked)
					}),
					/* @__PURE__ */ jsx("p", {
						className: "text-xs text-gray-500 mt-1",
						children: "Enter the Ethereum address for this account"
					})
				] }),
				/* @__PURE__ */ jsxs("div", { children: [
					/* @__PURE__ */ jsx("label", {
						className: "block text-sm font-medium text-gray-700 mb-2",
						children: "Account Name (Optional)"
					}),
					/* @__PURE__ */ jsx(StringField, {
						name: "name",
						placeholder: "My Main Wallet",
						className: "w-full",
						disabled: Boolean(isLocked)
					}),
					/* @__PURE__ */ jsx("p", {
						className: "text-xs text-gray-500 mt-1",
						children: "A friendly name for this account"
					})
				] }),
				/* @__PURE__ */ jsxs("div", {
					className: "flex gap-3",
					children: [/* @__PURE__ */ jsx(Button, {
						type: "submit",
						className: "bg-blue-600 hover:bg-blue-700 text-white px-6 py-2",
						disabled: Boolean(isLocked),
						children: "Set Account"
					}), /* @__PURE__ */ jsx(Button, {
						type: "button",
						onClick: () => setIsEditing(false),
						className: "bg-gray-300 hover:bg-gray-400 text-gray-700 px-6 py-2",
						disabled: Boolean(isLocked),
						children: "Cancel"
					})]
				})
			]
		})]
	});
}
//#endregion
//#region editors/account-transactions-editor/editor.tsx
function Editor() {
	const [document, dispatch] = useSelectedAccountTransactionsDocument();
	const parentFolder = useParentFolderForSelectedNode();
	const [selectedDrive] = useSelectedDrive();
	const allDocuments = useDocumentsInSelectedDrive();
	const [viewMode, setViewMode] = useState("list");
	const [editingTransaction, setEditingTransaction] = useState(null);
	const [isLoadingTransactions, setIsLoadingTransactions] = useState(false);
	const [isDeleting, setIsDeleting] = useState(false);
	function handleClose() {
		setSelectedNode(parentFolder?.id);
	}
	function handleAddTransaction(values) {
		dispatch(addTransaction({
			id: generateId(),
			...values
		}));
		setViewMode("list");
	}
	function handleUpdateTransaction(values) {
		if ("id" in values) dispatch(updateTransaction(values));
		setViewMode("list");
		setEditingTransaction(null);
	}
	function handleDeleteTransaction(id) {
		if (window.confirm("Are you sure you want to delete this transaction?")) dispatch(deleteTransaction({ id }));
	}
	function handleEditClick(transaction) {
		setEditingTransaction(transaction);
		setViewMode("edit");
	}
	function handleCancelForm() {
		setViewMode("list");
		setEditingTransaction(null);
	}
	async function handleDeleteDocument() {
		if (!document) return;
		if (!window.confirm("Are you sure you want to delete this account transactions document? This will also remove all references to it from Accounts, Expense Reports, and Snapshot Reports.")) return;
		setIsDeleting(true);
		const documentId = document.header.id;
		try {
			const accountsDocs = allDocuments?.filter((doc) => doc.header.documentType === "powerhouse/accounts") || [];
			for (const accountsDoc of accountsDocs) {
				const accountsToUpdate = (accountsDoc.state?.global?.accounts || []).filter((acc) => acc.accountTransactionsId === documentId);
				if (accountsToUpdate.length > 0) await dispatchActions(accountsToUpdate.map((acc) => actions.updateAccount({
					id: acc.id,
					accountTransactionsId: null
				})), accountsDoc.header.id);
			}
			const expenseReportDocs = allDocuments?.filter((doc) => doc.header.documentType === "powerhouse/expense-report") || [];
			for (const expenseReportDoc of expenseReportDocs) {
				const walletsToUpdate = (expenseReportDoc.state?.global?.wallets || []).filter((wallet) => wallet.accountTransactionsDocumentId === documentId);
				if (walletsToUpdate.length > 0) await dispatchActions(walletsToUpdate.map((wallet) => actions$1.updateWallet({
					address: wallet.wallet,
					accountTransactionsDocumentId: null
				})), expenseReportDoc.header.id);
			}
			if (selectedDrive?.header.id) await dispatchActions([deleteNode({ id: documentId })], selectedDrive.header.id);
			setSelectedNode(parentFolder?.id);
		} catch (error) {
			console.error("Error deleting account transactions document:", error);
			alert(`Failed to delete document: ${error instanceof Error ? error.message : "Unknown error"}`);
		} finally {
			setIsDeleting(false);
		}
	}
	async function handleFetchTransactions() {
		const account = document.state.global.account;
		if (!account?.account) {
			alert("Please set an account address first");
			return;
		}
		const existingTransactions = document.state.global.transactions || [];
		const lastBlockNumber = existingTransactions.reduce((max, tx) => {
			const bn = typeof tx.blockNumber === "number" ? tx.blockNumber : -Infinity;
			return bn > max ? bn : max;
		}, -Infinity);
		const fromBlock = Number.isFinite(lastBlockNumber) && lastBlockNumber >= 0 ? `0x${(lastBlockNumber + 1).toString(16)}` : void 0;
		setIsLoadingTransactions(true);
		try {
			try {
				const result = await alchemyIntegration.getTransactionsFromAlchemy(account.account, fromBlock);
				if (result.success) {
					if (!result.transactions || result.transactions.length === 0) {
						alert("No new transactions found. All transactions are up to date.");
						return;
					}
					new Set(existingTransactions.map((tx) => {
						const txHash = tx.details?.txHash || tx.txHash || "";
						const blockNumber = tx.details?.blockNumber || tx.blockNumber || "";
						const token = tx.details?.token || tx.token || "";
						const counterParty = tx.counterParty || "";
						const amount = tx.amount;
						return `${txHash}-${blockNumber}-${token}-${counterParty}-${typeof amount === "object" && amount?.value && amount?.unit ? `${amount.value}-${amount.unit}` : typeof amount === "string" ? amount : ""}`;
					}));
					let addedCount = 0;
					let skippedCount = 0;
					for (const txData of result.transactions) {
						let amount;
						if (typeof txData.amount === "string") {
							const amountParts = txData.amount.split(" ");
							amount = {
								value: amountParts[0] || "0",
								unit: amountParts[1] || txData.token
							};
						} else if (typeof txData.amount === "object" && txData.amount && "value" in txData.amount && "unit" in txData.amount) amount = txData.amount;
						else amount = {
							value: "0",
							unit: txData.token
						};
						if (!txData.direction) {
							console.error(`[Editor] Skipping transaction with undefined direction:`, txData);
							skippedCount++;
							continue;
						}
						if (!txData.from || !txData.to) {
							console.error(`[Editor] Skipping transaction with undefined from/to:`, {
								hash: txData.txHash,
								from: txData.from,
								to: txData.to,
								direction: txData.direction
							});
							skippedCount++;
							continue;
						}
						dispatch(addTransaction({
							id: generateId(),
							counterParty: txData.counterParty,
							amount,
							datetime: txData.datetime,
							txHash: txData.txHash,
							token: txData.token,
							blockNumber: txData.blockNumber,
							uniqueId: txData.uniqueId || null,
							accountingPeriod: txData.accountingPeriod,
							direction: txData.direction || "OUTFLOW",
							budget: null
						}));
						addedCount++;
					}
					if (addedCount === 0) if (skippedCount > 0) alert(`No new transactions found. All ${skippedCount} transaction(s) already exist in the document.`);
					else alert("No new transactions found. All transactions are up to date.");
					else {
						const message = skippedCount > 0 ? `Successfully added ${addedCount} new transaction(s) from Alchemy (${skippedCount} skipped - already exist or validation errors)` : `Successfully added ${addedCount} new transaction(s) from Alchemy`;
						alert(message);
					}
					return;
				} else throw new Error(result.message || "Failed to fetch transactions from Alchemy");
			} catch (error) {
				const errorMessage = error instanceof Error ? error.message : "Unknown error";
				if (errorMessage.includes("400") || errorMessage.includes("Cannot query field")) {
					alert("The transaction fetching feature requires a reactor restart to work. Please restart the reactor (ph vetra) and try again.");
					return;
				}
				throw error;
			}
		} catch (error) {
			console.error("Error fetching transactions:", error);
			alert(`Error fetching transactions: ${error instanceof Error ? error.message : "Unknown error"}`);
		} finally {
			setIsLoadingTransactions(false);
		}
	}
	return /* @__PURE__ */ jsxs("div", {
		className: "h-screen flex flex-col bg-gray-50",
		children: [
			/* @__PURE__ */ jsx(DocumentToolbar, {
				document,
				onClose: handleClose
			}),
			/* @__PURE__ */ jsxs("div", {
				className: "bg-white border-b border-gray-200 px-4 py-3 flex items-center justify-between",
				children: [/* @__PURE__ */ jsx("h1", {
					className: "text-lg font-semibold text-gray-900",
					children: "Account Transactions"
				}), /* @__PURE__ */ jsx(Button, {
					onClick: handleDeleteDocument,
					disabled: isDeleting,
					className: "bg-red-600 hover:bg-red-700 disabled:bg-gray-400 text-white px-4 py-2 rounded-lg font-medium shadow-sm transition-colors",
					children: isDeleting ? "Deleting..." : "Delete Document"
				})]
			}),
			/* @__PURE__ */ jsx("div", {
				className: "flex-1 overflow-auto",
				children: /* @__PURE__ */ jsxs("div", {
					className: "max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8",
					children: [/* @__PURE__ */ jsx(AccountSection, {
						account: document.state.global.account,
						hasFetchedTransactions: (document.state.global.transactions || []).length > 0,
						onSetAccount: (address, name) => {
							dispatch(setAccount({
								id: generateId(),
								account: address || "",
								name: name || ""
							}));
						}
					}), /* @__PURE__ */ jsxs("div", {
						className: "mt-8",
						children: [
							viewMode === "list" && /* @__PURE__ */ jsxs("div", {
								className: "space-y-6",
								children: [/* @__PURE__ */ jsxs("div", {
									className: "flex items-center justify-between",
									children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsxs("h2", {
										className: "text-2xl font-semibold text-gray-900",
										children: [
											"Transactions (",
											document.state.global.transactions.length,
											")"
										]
									}), /* @__PURE__ */ jsx("p", {
										className: "mt-1 text-sm text-gray-600",
										children: "Manage account transactions with details and budgets. Only new transactions will be added when fetching."
									})] }), /* @__PURE__ */ jsxs("div", {
										className: "flex space-x-3",
										children: [/* @__PURE__ */ jsx(Button, {
											onClick: handleFetchTransactions,
											disabled: isLoadingTransactions || !document.state.global.account?.account,
											className: "bg-green-600 hover:bg-green-700 disabled:bg-gray-400 text-white px-6 py-2.5 rounded-lg font-medium shadow-sm transition-colors",
											children: isLoadingTransactions ? "Fetching..." : "Fetch New Transactions"
										}), /* @__PURE__ */ jsx(Button, {
											onClick: () => setViewMode("add"),
											className: "bg-blue-600 hover:bg-blue-700 text-white px-6 py-2.5 rounded-lg font-medium shadow-sm transition-colors",
											children: "Add Transaction"
										})]
									})]
								}), /* @__PURE__ */ jsx(TransactionsTable, {
									transactions: document.state.global.transactions,
									onEdit: handleEditClick,
									onDelete: handleDeleteTransaction
								})]
							}),
							viewMode === "add" && /* @__PURE__ */ jsxs("div", {
								className: "max-w-3xl",
								children: [/* @__PURE__ */ jsxs("div", {
									className: "mb-6",
									children: [/* @__PURE__ */ jsx("h2", {
										className: "text-2xl font-semibold text-gray-900",
										children: "Add New Transaction"
									}), /* @__PURE__ */ jsx("p", {
										className: "mt-1 text-sm text-gray-600",
										children: "Fill in the transaction details below"
									})]
								}), /* @__PURE__ */ jsx(TransactionForm, {
									budgets: document.state.global.budgets,
									onSubmit: handleAddTransaction,
									onCancel: handleCancelForm
								})]
							}),
							viewMode === "edit" && editingTransaction && /* @__PURE__ */ jsxs("div", {
								className: "max-w-3xl",
								children: [/* @__PURE__ */ jsxs("div", {
									className: "mb-6",
									children: [/* @__PURE__ */ jsx("h2", {
										className: "text-2xl font-semibold text-gray-900",
										children: "Edit Transaction"
									}), /* @__PURE__ */ jsx("p", {
										className: "mt-1 text-sm text-gray-600",
										children: "Update the transaction details below"
									})]
								}), /* @__PURE__ */ jsx(TransactionForm, {
									transaction: editingTransaction,
									budgets: document.state.global.budgets,
									onSubmit: handleUpdateTransaction,
									onCancel: handleCancelForm
								})]
							})
						]
					})]
				})
			})
		]
	});
}
//#endregion
export { Editor as default };

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