<script lang="ts">
	import * as Table from '$lib/components/ui/table';
	import { tick } from 'svelte';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Textarea } from '$lib/components/ui/textarea';
	import { Badge } from '$lib/components/ui/badge';
	import {
		Plus,
		Pencil,
		Trash2,
		Loader2,
		Save as SaveIcon,
		Sparkles,
		Search,
		PackageOpen,
		Calendar,
		LayoutTemplate,
		X
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import type { Invoice } from '$lib/api/dashboard/a76/invoices';
	import { itemsApi, type Item as InvoiceItem } from '$lib/api/dashboard/a76/items';
	import { companyStore } from '$lib/stores/company.svelte';
	import ItemSheetFa from './fa/item-sheet-fa.svelte';
	import ItemSheetInv from './inv/item-sheet-inv.svelte';
	import { itemPresetsApi, type ItemPreset } from '$lib/api/dashboard/a76/item-presets';
	import ErrorPanelNotice from '$lib/components/ui/error-panel-notice.svelte';
	import { portal } from '$lib/actions/portal';
	import { cleanLineData, normalizeItemData, formatItemErrorRows } from '$lib/utils/items-logic';
	import { focusItemSheetField, type ItemSheetTabValue } from './focus-item-sheet-field';
	import { getVisibility } from '$lib/config/invoice-item-visibility';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosPestanaPartidas } from '$lib/config/shortcuts/dashboard/invoices/item/items_tab';
	import { m } from '$lib/i18n/messages';
	import { cn } from '$lib/utils';
	import { ITEMS_LINE_PLACEHOLDER } from '../focus-invoice-field';

	let {
		invoice,
		formData = $bindable(),
		exists = $bindable(),
		operationType = undefined,
		invoiceType = undefined,
		highlightFieldId = null,
		onDismissHighlightForField = undefined
	}: {
		invoice: Invoice | null;
		formData?: any;
		exists?: boolean;
		operationType?: number;
		invoiceType?: string;
		highlightFieldId?: string | null;
		onDismissHighlightForField?: (fieldKey: string) => void;
	} = $props();

	// 1. Core State
	let items = $state<InvoiceItem[]>([]);
	let imported = $state(0);
	let net_weight = $state(0);
	let gross_weight = $state(0);
	let itemsPerPage = 20;
	let currentPage = $state(1);
	let tableContainer = $state<HTMLDivElement>();
	let isLoadingMore = $state(false);
	let isLoadingItems = $state(false);
	let isSaving = $state(false);

	// 2. Sorting State
	let sortField = $state<string | null>(null);
	let sortOrder = $state<'asc' | 'desc'>('asc');

	// 3. Selection & Filtering State
	let selectedLineIds = $state<string[]>([]);
	let focusedLine = $state<any>(null);

	// 4. Preset State
	let presets = $state<ItemPreset[]>([]);
	let selectedPreset = $state<ItemPreset | null>(null);
	let searchPresets = $state('');
	let isLoadingPresets = $state(false);
	let isApplyingPreset = $state(false);
	let showUsePresetDialog = $state(false);
	let showCreatePresetDialog = $state(false);
	let createPresetName = $state('');
	let createPresetDescription = $state('');
	let builderItems: any[] = $state([]);
	let isSavingPreset = $state(false);
	let isTargetingPreset = $state(false);
	let editingBuilderIndex = $state<number | null>(null);
	let builderDraft = $state({
		description: '',
		quantity: 1,
		unit_cost_usd: 0,
		reference_number: ''
	});

	// 5. Form/Sheet State
	let showItemSheet = $state(false);
	let isEditMode = $state(false);
	let showDeleteDialog = $state(false);
	let selectedItem = $state<InvoiceItem | null>(null);
	let originalItemData = $state<Partial<InvoiceItem> | null>(null);
	let editingItem = $state<Partial<InvoiceItem>>({
		invoice_id: undefined,
		reference_number: '',
		order: '',
		warehouse: '',
		location: ''
	});

	let partidaNoticeOpen = $state(false);
	let partidaNoticeRows = $state<{ field: string; message: string; fieldPath?: string }[]>([]);
	let partidaNoticeVariant = $state<'error' | 'warning'>('error');
	let itemSheetWasOpen = $state(false);
	let faActiveTab = $state<string>('generales');

	const partidaErrorPanelLabels = $derived.by(() => ({
		clear: m.invoice_edit_items_error_panel_clear(),
		columnType: m.invoice_edit_items_error_panel_column_type(),
		columnField: m.invoice_edit_items_error_panel_column_field(),
		columnMessage: m.invoice_edit_items_error_panel_column_message(),
		emptyField: m.invoice_edit_items_error_panel_empty_field(),
		dismissRowAria: m.invoice_edit_items_error_panel_dismiss_row_aria(),
		toggleDetailsAria: m.invoice_edit_items_error_panel_toggle_details_aria()
	}));

	// 6. Derived Values - Optimized for performance
	const baseMappedLines = $derived.by(() => {
		const sourceItems = items?.length ? items : formData?.items || [];
		return (sourceItems || []).map((item: any, itemIndex: number) => ({
			...item,
			id: item?.id || `item-${itemIndex}`,
			line_number: item?.line_number ?? itemIndex + 1,
			reference_number: item?.reference_number,
			is_subitem: item?.is_subitem ?? false,
			class_code: item?.class_code ?? item?.class_id,
			class_description:
				item?.class_description ||
				item?.description?.description_spanish ||
				item?.description?.description_english ||
				'',
			unit_of_measure_code: item?.quantity?.unit_of_measure || item?.unit_of_measure,
			part_number_display: (item as any).part_number_display || item?.part_number,
			fa_data: item?.fa_data || {},
			warehouse: item?.warehouse,
			full_item: item
		}));
	});

	const flattenedLines = $derived.by(() => {
		let lines = [...baseMappedLines];

		if (sortField) {
			lines.sort((a: any, b: any) => {
				let valA: any = a[sortField!];
				let valB: any = b[sortField!];

				// Special handling for numeric and nested fields
				if (sortField === 'quantity') {
					valA = a.quantity?.quantity || 0;
					valB = b.quantity?.quantity || 0;
				} else if (sortField === 'unit_cost') {
					valA = a.financial?.unit_cost_usd || a.financial?.unit_cost_capture || 0;
					valB = b.financial?.unit_cost_usd || b.financial?.unit_cost_capture || 0;
				} else if (sortField === 'value') {
					valA = (a.quantity?.quantity || 0) * (a.financial?.unit_cost_usd || 0);
					valB = (b.quantity?.quantity || 0) * (b.financial?.unit_cost_usd || 0);
				} else if (sortField === 'line_number') {
					valA = Number(a.line_number) || 0;
					valB = Number(b.line_number) || 0;
				}

				// Standard comparison
				if (valA === undefined || valA === null) valA = '';
				if (valB === undefined || valB === null) valB = '';
				
				if (typeof valA === 'string') valA = valA.toLowerCase();
				if (typeof valB === 'string') valB = valB.toLowerCase();

				if (valA < valB) return sortOrder === 'asc' ? -1 : 1;
				if (valA > valB) return sortOrder === 'asc' ? 1 : -1;
				return 0;
			});
		}

		return lines;
	});

	const displayedItems = $derived(flattenedLines.slice(0, currentPage * itemsPerPage));

	const isAllSelected = $derived(
		flattenedLines.length > 0 && selectedLineIds.length === flattenedLines.length
	);

	const filteredPresets = $derived(
		presets.filter(
			(p) =>
				p.name.toLowerCase().includes(searchPresets.toLowerCase()) ||
				p.description?.toLowerCase().includes(searchPresets.toLowerCase())
		)
	);

	const selectedPresetItems = $derived(selectedPreset?.items || []);
	const selectedPresetCount = $derived(selectedPreset?.items?.length || 0);

	const invoiceSystem = $derived(invoice?.system || 'scaii');
	const itemVisibility = $derived.by(() => getVisibility(invoiceType, operationType));
	const showCrTrackingHeader = $derived(itemVisibility.showCrTrackingHeader);
	const emptyStateColspan = $derived.by(() => {
		if (operationType === 1) return 11;
		if (showCrTrackingHeader) return 12;
		if (invoiceType === 'REP' || invoiceType === 'REPAR') return 13;
		return 10;
	});

	const activeCompanyId = $derived(companyStore?.activeCompany?.id);
	const formItemsCount = $derived(formData?.items?.length || 0);

	// 7. Effects
	$effect(() => {
		if (invoice?.id && activeCompanyId) {
			loadItems();
		}
	});

	$effect(() => {
		if (!partidaNoticeOpen) {
			partidaNoticeRows = [];
		}
	});

	$effect(() => {
		if (itemSheetWasOpen && !showItemSheet) {
			partidaNoticeOpen = false;
			partidaNoticeRows = [];
		}
		itemSheetWasOpen = showItemSheet;
	});

	function showPartidaInlineNotice(message: string) {
		partidaNoticeVariant = 'warning';
		partidaNoticeRows = [{ field: '', message }];
		partidaNoticeOpen = true;
	}

	async function showPartidaErrorPanel(error: unknown) {
		partidaNoticeVariant = 'error';
		let rows = formatItemErrorRows(error);
		if (rows.length === 0) {
			rows = [{ field: '', message: m.invoice_edit_items_error_panel_fallback_message() }];
		}
		partidaNoticeRows = rows;
		partidaNoticeOpen = true;

		const firstPath = rows[0]?.fieldPath;
		if (firstPath) {
			await tick();
			focusItemSheetField(firstPath, (tab) => { faActiveTab = tab; });
		}
	}

	function dismissPartidaNoticeRow(index: number) {
		partidaNoticeRows = partidaNoticeRows.filter((_, i) => i !== index);
		if (partidaNoticeRows.length === 0) {
			partidaNoticeOpen = false;
		}
	}

	function handlePartidaFieldChange(fieldPath: string) {
		const idx = partidaNoticeRows.findIndex((r) => r.fieldPath === fieldPath);
		if (idx !== -1) dismissPartidaNoticeRow(idx);
	}

	// 8. Handlers & Functions
	function toggleSort(field: string) {
		if (sortField === field) {
			sortOrder = sortOrder === 'asc' ? 'desc' : 'asc';
		} else {
			sortField = field;
			sortOrder = 'asc';
		}
	}

	function toggleSelectAll() {
		if (isAllSelected) {
			selectedLineIds = [];
		} else {
			selectedLineIds = flattenedLines.map((l: any) => l.id.toString());
		}
	}

	function toggleSelectLine(id: string) {
		if (selectedLineIds.includes(id)) {
			selectedLineIds = selectedLineIds.filter((i) => i !== id);
		} else {
			selectedLineIds = [...selectedLineIds, id];
		}
	}

	async function loadItems() {
		if (!invoice?.id || !activeCompanyId) return;

		isLoadingItems = true;
		try {
			const response = await itemsApi.listByInvoice(invoice.id, activeCompanyId);
			if (response.data) {
				items = response.data.items || [];
				currentPage = 1;
				updateTotals();
			}
		} catch (error: any) {
			console.error('Error loading items:', error);
			showPartidaInlineNotice(
				error?.response?.data?.detail || 'No se pudieron cargar las partidas.'
			);
		} finally {
			isLoadingItems = false;
		}
	}

	function updateTotals() {
		imported = items.reduce((sum, item: any) => sum + (Number(item.quantity?.quantity) || 0), 0);
		net_weight = items.reduce((sum, item: any) => sum + (Number(item.quantity?.net_weight || (item as any).net_weight) || 0), 0);
		gross_weight = items.reduce((sum, item: any) => sum + (Number(item.quantity?.gross_weight || (item as any).gross_weight) || 0), 0);
	}

	function handleRowClick(line: any) {
		focusedLine = line;
	}

	async function handleScroll(e: Event) {
		const target = e.target as HTMLDivElement;
		const threshold = 150;
		const scrolledToBottom =
			target.scrollHeight - target.scrollTop - target.clientHeight < threshold;

		if (scrolledToBottom && !isLoadingMore && displayedItems.length < flattenedLines.length) {
			isLoadingMore = true;
			currentPage++;
			
			// Wait for Svelte to finish rendering the new items before allowing the next page load.
			// This prevents the "consecutive page explosion" that freezes the UI.
			await tick();
			
			isLoadingMore = false;
		}
	}


	function handleAdd() {
		if (!showCreatePresetDialog && !invoice?.id) {
			showPartidaInlineNotice(
				`${m.invoice_edit_items_unsaved_invoice_title()}. ${m.invoice_edit_items_unsaved_invoice_description()}`
			);
			return;
		}

		isEditMode = false;
		isTargetingPreset = showCreatePresetDialog;
		editingBuilderIndex = null;
		editingItem = {
			invoice_id: invoice?.id,
			line_number: (items.length || 0) + 1,
			reference_number: '',
			order: invoice?.purchase_order || '',
			financial: {},
			quantity: {},
			customs: {},
			description: {},
			fa_data: {}
		};
		showItemSheet = true;
	}

	function handleEdit(lineData: any) {
		isEditMode = true;
		selectedItem = lineData.full_item;
		editingItem = normalizeItemData(JSON.parse(JSON.stringify(lineData.full_item)));
		if (!editingItem.series) editingItem.series = [];
		originalItemData = JSON.parse(JSON.stringify(editingItem));
		showItemSheet = true;
	}

	function handleDelete(lineData: any) {
		selectedItem = lineData.full_item;
		showDeleteDialog = true;
	}

	function removeSelectedItemLocally() {
		if (!selectedItem) return;

		const itemRef = selectedItem;
		items = (items || []).filter((item) => item !== itemRef);

		if (Array.isArray(formData?.items)) {
			formData.items = formData.items.filter((item: any) => item !== itemRef);
		}

		updateTotals();
	}

	async function confirmDelete() {
		if (!selectedItem) return;
		isSaving = true;
		try {
			const hasPersistedId =
				typeof selectedItem.id === 'number' && Number.isFinite(selectedItem.id);

			if (hasPersistedId && activeCompanyId) {
				await itemsApi.delete(selectedItem.id, activeCompanyId);
				await loadItems();
			} else {
				removeSelectedItemLocally();
			}

			toast.success(m.invoice_edit_items_deleted());
			showDeleteDialog = false;
			selectedItem = null;
		} catch (error) {
			console.error('Error deleting item:', error);
			showPartidaInlineNotice(m.invoice_edit_items_delete_failed());
		} finally {
			isSaving = false;
		}
	}

	async function saveItem() {
		if (!editingItem) {
			showPartidaInlineNotice(m.invoice_edit_items_no_data_to_save());
			return;
		}
		
		// Basic validation
		if (!editingItem.class_id && !editingItem.description?.description_spanish) {
			showPartidaInlineNotice(m.invoice_edit_items_required_fields());
			await tick();
			const el =
				(document.getElementById('class_code') ||
					document.getElementById('clase')) as HTMLElement | null;
			el?.scrollIntoView({ behavior: 'smooth', block: 'center' });
			el?.focus();
			return;
		}

		if (isTargetingPreset) {
			saveItemToPreset();
			return;
		}

		if (!activeCompanyId) {
			showPartidaInlineNotice(m.invoice_edit_items_no_active_company());
			return;
		}
		
		if (!invoice?.id) {
			showPartidaInlineNotice(m.invoice_edit_items_no_invoice_id());
			return;
		}
		isSaving = true;
		try {
			const payload = cleanLineData(editingItem);

			if (isEditMode && selectedItem?.id) {
				const res = await itemsApi.update(selectedItem.id, activeCompanyId, {
					...payload,
					invoice_id: invoice.id
				});
				if (res.error) {
					showPartidaErrorPanel(res);
					return;
				}
				toast.success(m.invoice_edit_items_updated());
			} else {
				const createData = { ...payload, invoice_id: invoice.id };
				const res = await itemsApi.create(activeCompanyId, createData);
				if (res.error) {
					showPartidaErrorPanel(res);
					return;
				}
				toast.success(m.invoice_edit_items_created());
			}
			await loadItems();
			showItemSheet = false;
		} catch (error: unknown) {
			showPartidaErrorPanel(error);
		} finally {
			isSaving = false;
		}
	}

	function saveItemToPreset() {
		let cleanedItem = cleanLineData(editingItem);
		if (editingBuilderIndex !== null) {
			builderItems[editingBuilderIndex] = cleanedItem;
		} else {
			builderItems = [...builderItems, cleanedItem];
		}
		showItemSheet = false;
		isTargetingPreset = false;
		editingBuilderIndex = null;
		toast.success(m.invoice_edit_items_saved_to_template());
	}

	function openUsePresetDialog() {
		if (!invoice?.id) {
			showPartidaInlineNotice(m.invoice_edit_items_save_invoice_first());
			return;
		}
		showUsePresetDialog = true;
		loadPresets();
	}

	async function loadPresets() {
		if (!activeCompanyId) return;
		isLoadingPresets = true;
		try {
			const response = await itemPresetsApi.list(activeCompanyId);
			presets = response.data || [];
		} catch (error) {
			console.error('Error loading presets:', error);
		} finally {
			isLoadingPresets = false;
		}
	}

	async function applySelectedPreset() {
		if (!selectedPreset || !invoice?.id || !activeCompanyId) return;
		isApplyingPreset = true;
		try {
			for (const item of selectedPreset.items || []) {
				const payload = { ...item, invoice_id: invoice.id, id: undefined };
				const res = await itemsApi.create(activeCompanyId, payload);
				if (res.error) {
					showPartidaErrorPanel(res);
					return;
				}
			}
			await loadItems();
			toast.success(m.invoice_edit_items_template_applied());
			showUsePresetDialog = false;
		} catch (error) {
			console.error('Error applying preset:', error);
			showPartidaInlineNotice(m.invoice_edit_items_apply_template_error());
		} finally {
			isApplyingPreset = false;
		}
	}

	function openCreatePresetDialog() {
		builderItems = [];
		createPresetName = '';
		createPresetDescription = '';
		showCreatePresetDialog = true;
	}

	function handleEditInPreset(index: number) {
		editingBuilderIndex = index;
		editingItem = normalizeItemData(JSON.parse(JSON.stringify(builderItems[index])));
		isTargetingPreset = true;
		isEditMode = true;
		showItemSheet = true;
	}

	function handleRemoveFromPreset(index: number) {
		builderItems = builderItems.filter((_, i) => i !== index);
	}

	async function saveCurrentItemsAsPreset() {
		if (!createPresetName || !activeCompanyId) return;
		isSavingPreset = true;
		try {
			const payload = {
				name: createPresetName,
				description: createPresetDescription,
				items: builderItems
			};
			await itemPresetsApi.create(activeCompanyId, payload);
			toast.success(m.invoice_edit_items_template_saved());
			showCreatePresetDialog = false;
			loadPresets();
		} catch (error) {
			console.error('Error saving preset:', error);
			showPartidaInlineNotice(m.invoice_edit_items_save_template_error());
		} finally {
			isSavingPreset = false;
		}
	}

	const STICKY_LINE_HEAD = 'sticky left-0 z-40 bg-background shadow-[3px_0_8px_-4px_rgba(0,0,0,0.12)]';
	const STICKY_ACTIONS_HEAD = 'sticky right-0 z-40 w-[104px] min-w-[104px] bg-background text-right shadow-[-3px_0_8px_-4px_rgba(0,0,0,0.12)]';

	function stickyLineCellClass(itemId: string) {
		const focused = focusedLine?.id === itemId;
		return [
			'sticky left-0 z-30 shadow-[3px_0_8px_-4px_rgba(0,0,0,0.12)]',
			focused ? 'bg-muted' : 'bg-background group-hover/item-row:bg-muted/50'
		].join(' ');
	}

	function stickyActionsCellClass(itemId: string) {
		const focused = focusedLine?.id === itemId;
		return [
			'sticky right-0 z-30 w-[104px] min-w-[104px] text-right shadow-[-3px_0_8px_-4px_rgba(0,0,0,0.12)]',
			focused ? 'bg-muted' : 'bg-background group-hover/item-row:bg-muted/50'
		].join(' ');
	}

	useShortcuts(
		'Invoice Items Tab',
		obtenerAtajosPestanaPartidas({
			nuevaPartida: () => {
				if (showItemSheet) return;
				handleAdd();
			}
		})
	);
</script>

<div
	id="invoice-items-tab-root"
	tabindex="-1"
	class={cn(
		'grid grid-cols-4 grid-rows-1 gap-3',
		highlightFieldId === ITEMS_LINE_PLACEHOLDER && 'rounded-md ring-2 ring-destructive ring-offset-2'
	)}
	oninputcapture={() => {
		if (highlightFieldId !== ITEMS_LINE_PLACEHOLDER) return;
		onDismissHighlightForField?.(ITEMS_LINE_PLACEHOLDER);
	}}
	onchangecapture={() => {
		if (highlightFieldId !== ITEMS_LINE_PLACEHOLDER) return;
		onDismissHighlightForField?.(ITEMS_LINE_PLACEHOLDER);
	}}
>
	<div use:portal>
		<ErrorPanelNotice
			open={partidaNoticeOpen}
			variant={partidaNoticeVariant}
			title={partidaNoticeVariant === 'warning'
				? 'Advertencia'
				: m.invoice_edit_items_error_panel_title_with_count({
						count: String(partidaNoticeRows.length || 1)
					})}
			rows={partidaNoticeRows}
			durationMs={partidaNoticeVariant === 'warning' ? 8000 : 0}
			labels={partidaErrorPanelLabels}
			dismissibleRows={true}
			onClose={() => (partidaNoticeOpen = false)}
			onDismissRow={dismissPartidaNoticeRow}
		/>
	</div>

	<div class="col-span-3 space-y-3 rounded-md border p-3">
		<div class="mb-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
			<div>
				<h3 class="text-sm font-semibold">{m.invoice_edit_items_title()}</h3>
				<p class="text-xs text-muted-foreground">
					{m.invoice_edit_items_subtitle()}
				</p>
			</div>
			<div class="flex flex-wrap justify-end gap-2">
				<Button
					size="sm"
					variant="secondary"
					class="shadow-sm"
					onclick={openUsePresetDialog}
					type="button"
				>
					<Sparkles class="mr-1 h-4 w-4" />
					{m.invoice_edit_items_use_template()}
				</Button>
				<Button size="sm" variant="outline" onclick={openCreatePresetDialog} type="button">
					<Plus class="mr-1 h-4 w-4" />
					{m.invoice_edit_items_create_template()}
				</Button>
				<Button size="sm" onclick={handleAdd} type="button">
					<Plus class="mr-1 h-4 w-4" />
					{m.invoice_edit_items_add_items()}
				</Button>
			</div>
		</div>

		<div
			bind:this={tableContainer}
			onscroll={handleScroll}
			class="max-h-[500px] overflow-auto rounded-md border"
			data-invoice-items-table
		>
			<Table.Root>
				<Table.Header class="bg-background">
					<Table.Row inTabOrder={false}>
						<Table.Head 
							class="{STICKY_LINE_HEAD} cursor-pointer hover:bg-muted-foreground/10"
							onclick={() => toggleSort('line_number')}
						>
							<div class="flex items-center gap-1">
								{m.invoice_edit_items_column_line()}
								{#if sortField === 'line_number'}
									<div class="inline-flex">
										{#if sortOrder === 'asc'}
											<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>
										{:else}
											<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>
										{/if}
									</div>
								{/if}
							</div>
						</Table.Head>
						{#if operationType === 1}
							<Table.Head>{m.invoice_edit_items_column_impo_invoice()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_line()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_ps()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_imported_quantity()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_class()}</Table.Head>
							<Table.Head
								class="cursor-pointer hover:bg-muted-foreground/10"
								onclick={() => toggleSort('part_number_display')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_part_number()}
									{#if sortField === 'part_number_display'}
										<div class="inline-flex">
											{#if sortOrder === 'asc'}
												<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>
											{:else}
												<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>
											{/if}
										</div>
									{/if}
								</div>
							</Table.Head>
							<Table.Head
								class="cursor-pointer hover:bg-muted-foreground/10"
								onclick={() => toggleSort('class_description')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_description()}
									{#if sortField === 'class_description'}
										<div class="inline-flex">
											{#if sortOrder === 'asc'}
												<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>
											{:else}
												<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>
											{/if}
										</div>
									{/if}
								</div>
							</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_has_subitem()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_main_item()}</Table.Head>
						{:else if showCrTrackingHeader}
							<Table.Head>{m.invoice_edit_items_column_impo_invoice()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_line()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_ps()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_class()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_class_description()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_imported_quantity()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_um()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_preference()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_has_subitem()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_main_item()}</Table.Head>
						{:else if invoiceType === 'REP' || invoiceType === 'REPAR'}
							<Table.Head>{m.invoice_edit_items_column_impo_invoice()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_line()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_ps()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_class()}</Table.Head>
							<Table.Head
								class="cursor-pointer hover:bg-muted-foreground/10"
								onclick={() => toggleSort('part_number_display')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_part_number()}
									{#if sortField === 'part_number_display'}
										<div class="inline-flex">
											{#if sortOrder === 'asc'}
												<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>
											{:else}
												<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>
											{/if}
										</div>
									{/if}
								</div>
							</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_class_description()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_imported_quantity()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_um()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_preference()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_has_subitem()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_main_item()}</Table.Head>
						{:else}
							<Table.Head>{m.invoice_edit_items_column_ps()}</Table.Head>
							<Table.Head
								class="cursor-pointer select-none hover:bg-muted-foreground/10"
								onclick={() => toggleSort('class_code')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_class()}
									{#if sortField === 'class_code'}
										{#if sortOrder === 'asc'}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>{:else}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>{/if}
									{:else}
										<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down opacity-30"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
									{/if}
								</div>
							</Table.Head>
							<Table.Head
								class="cursor-pointer select-none hover:bg-muted-foreground/10"
								onclick={() => toggleSort('class_description')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_class_description()}
									{#if sortField === 'class_description'}
										{#if sortOrder === 'asc'}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>{:else}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>{/if}
									{:else}
										<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down opacity-30"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
									{/if}
								</div>
							</Table.Head>
							<Table.Head
								class="cursor-pointer select-none hover:bg-muted-foreground/10"
								onclick={() => toggleSort('quantity')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_quantity()}
									{#if sortField === 'quantity'}
										{#if sortOrder === 'asc'}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>{:else}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>{/if}
									{:else}
										<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down opacity-30"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
									{/if}
								</div>
							</Table.Head>
							<Table.Head
								class="cursor-pointer select-none hover:bg-muted-foreground/10"
								onclick={() => toggleSort('unit_of_measure_code')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_um()}
									{#if sortField === 'unit_of_measure_code'}
										{#if sortOrder === 'asc'}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>{:else}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>{/if}
									{:else}
										<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down opacity-30"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
									{/if}
								</div>
							</Table.Head>
							<Table.Head
								class="cursor-pointer select-none hover:bg-muted-foreground/10"
								onclick={() => toggleSort('reference_number')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_preference()}
									{#if sortField === 'reference_number'}
										{#if sortOrder === 'asc'}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>{:else}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>{/if}
									{:else}
										<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down opacity-30"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
									{/if}
								</div>
							</Table.Head>
							<Table.Head>{m.invoice_edit_items_column_has_subitem()}</Table.Head>
							<Table.Head
								class="cursor-pointer select-none hover:bg-muted-foreground/10"
								onclick={() => toggleSort('warehouse')}
							>
								<div class="flex items-center gap-1">
									{m.invoice_edit_items_column_main_item()}
									{#if sortField === 'warehouse'}
										{#if sortOrder === 'asc'}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-up"><path d="m18 15-6-6-6 6"/></svg>{:else}<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-down"><path d="m6 9 6 6 6-6"/></svg>{/if}
									{:else}
										<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down opacity-30"><path d="m7 15 5 5 5-5"/><path d="m7 9 5-5 5 5"/></svg>
									{/if}
								</div>
							</Table.Head>
						{/if}
						<Table.Head class={STICKY_ACTIONS_HEAD}>{m.invoice_edit_items_column_actions()}</Table.Head>
					</Table.Row>
				</Table.Header>
				<Table.Body>
					{#if displayedItems.length === 0}
						<Table.Row inTabOrder={false}>
							<Table.Cell
								colspan={emptyStateColspan}
								class="py-8 text-center text-muted-foreground"
							>
								{m.invoice_edit_items_no_items_available()}
							</Table.Cell>
						</Table.Row>
					{:else}
						{#each displayedItems as item (item.id)}
							<Table.Row
								data-item-line-row
								onclick={() => handleRowClick(item)}
								ondblclick={() => handleEdit(item)}
								onfocus={() => handleRowClick(item)}
								class="group/item-row cursor-pointer transition-colors hover:bg-muted/50 {focusedLine?.id ===
								item.id
									? 'bg-muted ring-1 ring-primary/20 ring-inset'
									: ''}"
							>
								{#if operationType === 1}
									<Table.Cell class={stickyLineCellClass(item.id)}>{item.line_number}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_invoice || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_line || '-'}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.part_number_display || '-'}</Table.Cell>
									<Table.Cell
										class="max-w-[200px] truncate"
										title={item.description?.description_spanish}
									>
										{item.description?.description_spanish || '-'}
									</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? m.invoice_edit_observations_yes() : m.invoice_edit_observations_no()}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{:else if showCrTrackingHeader}
									<Table.Cell class={stickyLineCellClass(item.id)}>{item.line_number}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_invoice || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_line || '-'}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell
										class="max-w-[200px] truncate"
										title={item.description?.description_spanish}
									>
										{item.description?.description_spanish || '-'}
									</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.unit_of_measure_code || '-'}</Table.Cell>
									<Table.Cell>{item.reference_number || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? m.invoice_edit_observations_yes() : m.invoice_edit_observations_no()}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{:else if invoiceType === 'REP' || invoiceType === 'REPAR'}
									<Table.Cell class={stickyLineCellClass(item.id)}>{item.line_number}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_invoice || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.search_line || '-'}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.part_number_display || '-'}</Table.Cell>
									<Table.Cell
										class="max-w-[200px] truncate"
										title={item.description?.description_spanish}
									>
										{item.description?.description_spanish || '-'}
									</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.unit_of_measure_code || '-'}</Table.Cell>
									<Table.Cell>{item.reference_number || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? m.invoice_edit_observations_yes() : m.invoice_edit_observations_no()}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{:else}
									<Table.Cell class={stickyLineCellClass(item.id)}>{item.line_number}</Table.Cell>
									<Table.Cell>{item.is_subitem ? 'S' : 'P'}</Table.Cell>
									<Table.Cell>{item.class_code || '-'}</Table.Cell>
									<Table.Cell>{item.class_description || '-'}</Table.Cell>
									<Table.Cell>{item.quantity?.quantity || '0'}</Table.Cell>
									<Table.Cell>{item.unit_of_measure_code || '-'}</Table.Cell>
									<Table.Cell>{item.reference_number || '-'}</Table.Cell>
									<Table.Cell>{item.fa_data?.contains_subitems ? m.invoice_edit_observations_yes() : m.invoice_edit_observations_no()}</Table.Cell>
									<Table.Cell>{item.warehouse || '-'}</Table.Cell>
								{/if}
								<Table.Cell class={stickyActionsCellClass(item.id)}>
									<div class="flex justify-end gap-2">
										<Button
											size="icon"
											variant="ghost"
											type="button"
											onclick={(e) => {
												e.stopPropagation();
												handleEdit(item);
											}}
										>
											<Pencil class="h-4 w-4" />
										</Button>
										<Button
											size="icon"
											variant="ghost"
											type="button"
											onclick={(e) => {
												e.stopPropagation();
												handleDelete(item);
											}}
										>
											<Trash2 class="h-4 w-4 text-destructive" />
										</Button>
									</div>
								</Table.Cell>
							</Table.Row>
						{/each}
						{#if isLoadingMore}
							<Table.Row inTabOrder={false}>
								<Table.Cell colspan={emptyStateColspan} class="py-4 text-center">
									<span class="text-sm text-muted-foreground">{m.invoice_edit_items_loaded_more_items()}</span>
								</Table.Cell>
							</Table.Row>
						{/if}
					{/if}
				</Table.Body>
			</Table.Root>
		</div>

		{#if flattenedLines.length > 0}
			<div class="text-right text-xs text-muted-foreground">
				{m.invoice_edit_items_showing_lines({ displayed: String(displayedItems.length), total: String(flattenedLines.length) })}
			</div>
		{/if}
	</div>

	<div class="col-start-4 space-y-4">
		{#if operationType === 1}
			<!-- Top Box: Descripción en español -->
			<div class="flex h-[200px] flex-col rounded-md border p-3">
				<h4 class="mb-2 text-xs font-semibold text-muted-foreground uppercase">
					{m.invoice_edit_items_spanish_description_label()}
				</h4>
				<div class="flex-1 overflow-auto rounded border bg-muted/30 p-2">
					{#if focusedLine}
						<p class="text-xs leading-relaxed font-medium">
							{focusedLine.description?.description_spanish || m.invoice_edit_items_no_description_short()}
						</p>
					{:else}
						<p class="flex h-full items-center justify-center text-xs text-muted-foreground italic">
							{m.invoice_edit_items_select_row_to_view_description()}
						</p>
					{/if}
				</div>
			</div>
		{/if}

		<!-- Bottom Box (or only box in Import): Quantities and Values -->
		<div class="space-y-3 rounded-md border p-3">
			<div>
				<h4 class="text-xs font-semibold text-muted-foreground uppercase">{m.invoice_edit_items_quantities()}</h4>
				<div>
					<div class="grid grid-cols-2 gap-3">
						<div>
							{m.invoice_edit_items_column_part_number()} <span class="text-blue-400">{items.length || 0}</span>
						</div>
						<div>
							{m.invoice_edit_items_bultos()} <span class="text-blue-400">0</span>
						</div>
					</div>
				</div>
				{m.invoice_edit_items_imported()}<span class="text-blue-400">{imported || 0}</span> <br />
				{m.invoice_edit_items_net_weight()} <span class="text-blue-400">{net_weight || 0}</span><br />
				{m.invoice_edit_items_gross_weight()} <span class="text-blue-400">{gross_weight || 0}</span> <br />
			</div>

			<h4 class="col-span-2 text-xs font-semibold text-muted-foreground uppercase">
				{m.invoice_edit_items_import_values_title()}
			</h4>
			{m.invoice_edit_items_dollars()}<span class="text-blue-400">0</span> <span class="text-red-400">USD</span> <br />
			{m.invoice_edit_items_pesos()} <span class="text-blue-400">0</span> <span class="text-red-400">MXN</span><br />
			{m.invoice_edit_items_capture_value()} <span class="text-blue-400">0</span> <span class="text-red-400">USD</span>

			<h4 class="col-span-2 text-xs font-semibold text-muted-foreground uppercase opacity-0">
				spacer
			</h4>

			{m.invoice_edit_items_customs_value_short()}<span class="text-blue-400">0</span> <span class="text-red-400">USD</span><br />
			{m.invoice_edit_items_customs_value_short()} <span class="text-blue-400">0</span> <span class="text-red-400">MXN</span><br />
		</div>
	</div>
</div>

<!-- Delete Confirmation Dialog -->
<Dialog.Root bind:open={showDeleteDialog}>
	<Dialog.Content class="[&>button]:hidden">
		<Dialog.Header>
			<Dialog.Title>Confirmar Eliminación</Dialog.Title>
			<Dialog.Description>
				¿Está seguro que desea eliminar este item? Esta acción no se puede deshacer.
			</Dialog.Description>
		</Dialog.Header>
		<Dialog.Footer>
			<Button
				variant="outline"
				onclick={() => (showDeleteDialog = false)}
				disabled={isSaving}
				type="button"
			>
				Cancelar
			</Button>
			<Button variant="destructive" onclick={confirmDelete} disabled={isSaving} type="button">
				{#if isSaving}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					Eliminando...
				{:else}
					Eliminar
				{/if}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Preset dialogs -->
<Dialog.Root
	bind:open={showUsePresetDialog}
	onOpenChange={(open) => {
		if (!open) {
			showUsePresetDialog = false;
			selectedPreset = null;
		}
	}}
>
	<Dialog.Content
		class="flex h-[85vh] flex-col gap-0 overflow-hidden p-0 sm:max-w-7xl [&>button]:hidden"
	>
		<!-- Fixed Header -->
		<div class="z-20 flex items-center justify-between border-b bg-background px-6 py-4">
			<div>
				<Dialog.Title>{m.invoice_edit_items_use_template()}</Dialog.Title>
				<Dialog.Description>
					{m.invoice_edit_items_use_template_description()}
				</Dialog.Description>
			</div>
			<div class="flex items-center gap-2">
				<Button
					variant="ghost"
					size="sm"
					onclick={() => loadPresets()}
					disabled={isLoadingPresets}
					class="h-8 text-muted-foreground"
				>
					<Loader2 class={`mr-2 h-3.5 w-3.5 ${isLoadingPresets ? 'animate-spin' : ''}`} />
					{m.invoice_edit_items_refresh()}
				</Button>
				<Button
					variant="ghost"
					size="icon"
					onclick={() => (showUsePresetDialog = false)}
					class="h-8 w-8 text-muted-foreground"
				>
					<X class="h-4 w-4" />
				</Button>
			</div>
		</div>

		<!-- Main Content Area (Split View) -->
		<div class="flex flex-1 overflow-hidden">
			<!-- Sidebar: List -->
			<div class="flex w-[340px] flex-col border-r bg-muted/30">
				<div
					class="border-b bg-background/50 p-4 backdrop-blur supports-[backdrop-filter]:bg-background/50"
				>
					<div class="relative">
						<Search
							class="absolute top-1/2 left-2.5 h-4 w-4 -translate-y-1/2 text-muted-foreground"
						/>
						<Input
							placeholder={m.invoice_edit_items_search_templates_placeholder()}
							class="h-9 bg-background pl-9"
							bind:value={searchPresets}
						/>
					</div>
				</div>

				<div class="flex-1 overflow-y-auto">
					{#if isLoadingPresets}
						<div
							class="flex flex-col items-center justify-center gap-3 py-12 text-muted-foreground"
						>
							<Loader2 class="h-8 w-8 animate-spin text-primary/20" />
							<span class="text-xs font-medium">{m.invoice_edit_items_loading()}</span>
						</div>
					{:else if filteredPresets.length === 0}
						<div
							class="flex flex-col items-center justify-center gap-3 px-6 py-12 text-center text-muted-foreground"
						>
							<PackageOpen class="h-10 w-10 opacity-20" />
							<p class="text-sm">{m.invoice_edit_items_no_templates_found()}</p>
						</div>
					{:else}
						{#each filteredPresets as preset}
							<button
								type="button"
								class={`group relative w-full border-b p-4 text-left transition-all hover:bg-muted/50 ${selectedPreset?.id === preset.id ? 'z-10 bg-background' : 'text-muted-foreground'}`}
								onclick={() => (selectedPreset = preset)}
							>
								{#if selectedPreset?.id === preset.id}
									<div class="absolute top-0 bottom-0 left-0 w-[3px] bg-primary"></div>
								{/if}
								<div class="space-y-1.5">
									<div class="flex items-start justify-between gap-2">
										<span
											class={`line-clamp-1 text-sm font-medium ${selectedPreset?.id === preset.id ? 'text-foreground' : ''}`}
											>{preset.name}</span
										>
										{#if preset.items?.length}
											<Badge
												variant="secondary"
												class="h-5 shrink-0 px-1.5 text-[10px] tabular-nums"
												>{preset.items.length}</Badge
											>
										{/if}
									</div>
									<p class="line-clamp-2 text-xs leading-relaxed opacity-80">
										{preset.description || m.invoice_edit_items_no_description()}
									</p>
									<div class="flex items-center pt-1 text-[10px] opacity-60">
										<Calendar class="mr-1 h-3 w-3" />
										{preset.created_at ? new Date(preset.created_at).toLocaleDateString() : 'N/A'}
									</div>
								</div>
							</button>
						{/each}
					{/if}
				</div>
			</div>

			<!-- Main Panel: Preview -->
			<div class="flex flex-1 flex-col overflow-hidden bg-slate-50/50 dark:bg-slate-900/50">
				{#if !selectedPreset}
					<div
						class="flex flex-1 flex-col items-center justify-center space-y-4 text-muted-foreground/50"
					>
						<div class="flex h-16 w-16 items-center justify-center rounded-full bg-muted/50">
							<LayoutTemplate class="h-8 w-8" />
						</div>
						<p class="font-medium">{m.invoice_edit_items_select_template_to_view()}</p>
					</div>
				{:else}
					<div class="flex h-full flex-col">
						<!-- Preview Header -->
						<div class="flex shrink-0 items-start justify-between border-b bg-background px-6 py-5">
							<div class="space-y-1">
								<h3 class="flex items-center gap-2 text-lg font-semibold">
									{selectedPreset.name}
								</h3>
								<p class="max-w-2xl text-sm leading-relaxed text-muted-foreground">
									{selectedPreset.description || m.invoice_edit_items_no_description_available()}
								</p>
							</div>
							<div class="ml-4 shrink-0 text-right">
								<div class="text-xs font-medium tracking-wider text-muted-foreground uppercase">
									{m.invoice_edit_items_created_label()}
								</div>
								<div class="text-sm font-medium tabular-nums">
									{selectedPreset.created_at
										? new Date(selectedPreset.created_at).toLocaleDateString(undefined, {
												dateStyle: 'long'
											})
										: '-'}
								</div>
							</div>
						</div>

						<!-- Preview Table -->
						<div class="relative flex-1 overflow-auto bg-background/50">
							<Table.Root>
								<Table.Header class="sticky top-0 z-10 bg-background shadow-sm">
									<Table.Row class="border-b hover:bg-transparent">
										<Table.Head class="h-10 w-12 bg-muted/10 text-center">#</Table.Head>
										<Table.Head class="h-10 bg-muted/10">{m.invoice_edit_items_item_description()}</Table.Head>
										<Table.Head class="h-10 w-24 bg-muted/10 text-center">{m.invoice_edit_items_quantity_short()}</Table.Head>
										<Table.Head class="h-10 w-32 bg-muted/10 text-right">Costo (USD)</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#if selectedPresetItems.length === 0}
										<Table.Row>
											<Table.Cell colspan={4} class="h-40 text-center text-muted-foreground">
												<div class="flex flex-col items-center gap-2">
													<PackageOpen class="h-8 w-8 opacity-20" />
													<span>{m.invoice_edit_items_template_empty_items()}</span>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										{#each selectedPresetItems as item, i}
											<Table.Row class="border-b-muted/40 hover:bg-muted/40">
												<Table.Cell
													class="border-r-muted/20 text-center font-mono text-xs text-muted-foreground"
												>
													{i + 1}
												</Table.Cell>
												<Table.Cell>
													<div class="flex flex-col py-0.5">
														<span class="text-sm font-medium text-foreground/90">
															{item?.description?.description_spanish || m.invoice_edit_items_no_description()}
														</span>
														{#if item.reference_number}
															<span class="mt-0.5 font-mono text-[10px] text-muted-foreground/70">
																REF: {item.reference_number}
															</span>
														{/if}
													</div>
												</Table.Cell>
												<Table.Cell class="text-center font-medium tabular-nums">
													{item?.quantity?.quantity || 0}
												</Table.Cell>
												<Table.Cell class="text-right text-muted-foreground tabular-nums">
													${(item?.financial?.unit_cost_usd || 0).toLocaleString(undefined, {
														minimumFractionDigits: 2
													})}
												</Table.Cell>
											</Table.Row>
										{/each}
									{/if}
								</Table.Body>
							</Table.Root>
						</div>
					</div>
				{/if}
			</div>
		</div>

		<!-- Sticky Footer -->
		<div class="z-20 flex shrink-0 justify-end gap-3 border-t bg-background px-6 py-4">
			<Button variant="outline" onclick={() => (showUsePresetDialog = false)} type="button">
				{m.invoice_edit_items_cancel()}
			</Button>
			<Button
				onclick={applySelectedPreset}
				disabled={!selectedPreset || selectedPresetCount === 0 || isApplyingPreset}
				class="min-w-[160px] bg-primary text-primary-foreground shadow-sm hover:bg-primary/90"
			>
				{#if isApplyingPreset}
					<Loader2 class="mr-2 h-4 w-4 animate-spin" />
					{m.invoice_edit_items_applying()}
				{:else}
					<Sparkles class="mr-2 h-4 w-4" />
					{m.invoice_edit_items_apply_template()}
				{/if}
			</Button>
		</div>
	</Dialog.Content>
</Dialog.Root>

<Dialog.Root
	bind:open={showCreatePresetDialog}
	onOpenChange={(open) => {
		if (!open) {
			createPresetName = '';
			createPresetDescription = '';
		}
	}}
>
	<Dialog.Content class="sm:max-w-4xl [&>button]:hidden">
		<Dialog.Header>
			<Dialog.Title>{m.invoice_edit_items_create_template_dialog_title()}</Dialog.Title>
			<Dialog.Description>{m.invoice_edit_items_create_template_dialog_description()}</Dialog.Description>
			>
		</Dialog.Header>

		<div class="space-y-4">
			<div class="grid gap-3 md:grid-cols-2">
				<div class="space-y-2">
					<label for="preset-name" class="text-sm font-medium">{m.invoice_edit_items_template_name_label()}</label>
					<Input
						id="preset-name"
						placeholder={m.invoice_edit_items_template_name_placeholder()}
						bind:value={createPresetName}
					/>
				</div>
				<div class="space-y-2">
					<label for="preset-description" class="text-sm font-medium">{m.invoice_edit_items_template_description_label()}</label>
					<Textarea
						id="preset-description"
						rows={2}
						placeholder={m.invoice_edit_items_template_description_placeholder()}
						bind:value={createPresetDescription}
					/>
				</div>
			</div>

			<div class="flex items-center justify-end">
				<div class="mr-auto text-sm text-muted-foreground">
					<Badge variant="secondary">{builderItems.length} {m.invoice_edit_items_template_items_count()}</Badge>
				</div>
			</div>

			<div class="max-h-[50vh] overflow-hidden overflow-y-auto rounded-md border">
				<div class="flex items-center justify-between border-b bg-muted/30 p-2">
					<span class="text-xs font-medium tracking-wider text-muted-foreground uppercase"
						>{m.invoice_edit_items_template_items_title()}</span
					>
					<Button size="sm" variant="outline" class="h-7 text-xs" onclick={handleAdd}>
						<Plus class="mr-1 h-3.5 w-3.5" /> {m.invoice_edit_items_add_item_line()}
					</Button>
				</div>

				<Table.Root>
					<Table.Header>
						<Table.Row>
							<Table.Head class="w-10 text-center">{m.invoice_edit_items_template_table_hash()}</Table.Head>
							<Table.Head>{m.invoice_edit_items_template_table_description()}</Table.Head>
							<Table.Head class="text-center">{m.invoice_edit_items_template_table_quantity()}</Table.Head>
							<Table.Head class="pr-4 text-right">{m.invoice_edit_items_template_table_actions()}</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#if builderItems.length === 0}
							<Table.Row>
								<Table.Cell
									colspan={4}
									class="py-8 text-center text-sm text-muted-foreground italic"
								>
									{m.invoice_edit_items_template_empty()}
								</Table.Cell>
							</Table.Row>
						{:else}
							{#each builderItems as item, i}
								<Table.Row>
									<Table.Cell class="text-center font-mono text-xs text-muted-foreground">
										{i + 1}
									</Table.Cell>
									<Table.Cell>
										<div class="flex flex-col">
											<span class="text-sm font-medium">
												{item?.[0]?.description?.description_spanish || m.invoice_edit_items_no_description()}
											</span>
											<span class="text-[10px] text-muted-foreground"
												>{m.invoice_edit_items_reference()} {item.reference_number || '-'}</span
											>
										</div>
									</Table.Cell>
									<Table.Cell class="text-center text-sm">
										{item?.[0]?.quantity?.quantity || 0}
									</Table.Cell>
									<Table.Cell class="pr-2 text-right">
										<div class="flex justify-end gap-1">
											<Button
												size="icon"
												variant="ghost"
												class="h-7 w-7"
												onclick={() => handleEditInPreset(i)}
											>
												<Pencil class="h-3.5 w-3.5" />
											</Button>
											<Button
												size="icon"
												variant="ghost"
												class="h-7 w-7 text-destructive"
												onclick={() => handleRemoveFromPreset(i)}
											>
												<Trash2 class="h-3.5 w-3.5" />
											</Button>
										</div>
									</Table.Cell>
								</Table.Row>
							{/each}
						{/if}
					</Table.Body>
				</Table.Root>
			</div>

			<div class="flex justify-end gap-2">
				<Button variant="outline" onclick={() => (showCreatePresetDialog = false)} type="button"
					>{m.invoice_edit_items_cancel()}</Button
				>
				<Button
					onclick={saveCurrentItemsAsPreset}
					disabled={isSavingPreset || builderItems.length === 0}
					class="bg-emerald-600 text-white hover:bg-emerald-700"
					type="button"
				>
					{#if isSavingPreset}
						<Loader2 class="mr-2 h-4 w-4 animate-spin" />
						{m.invoice_edit_items_saving()}
					{:else}
						<SaveIcon class="mr-2 h-4 w-4" />
						{m.invoice_edit_items_save_template()}
					{/if}
				</Button>
			</div>
		</div>
	</Dialog.Content>
</Dialog.Root>

<!-- Item Sheet (Panel lateral para agregar/editar) -->
<!-- Renderizar el componente apropiado según el sistema -->
{#if invoiceSystem === 'fixed_asset'}
	<ItemSheetFa
		bind:open={showItemSheet}
		{isEditMode}
		bind:editingItem
		{invoice}
		{invoiceType}
		{operationType}
		{isTargetingPreset}
		onSave={saveItem}
		onCancel={() => {
			showItemSheet = false;
		}}
		{isSaving}
		bind:activeTab={faActiveTab}
		onValidationFieldChange={handlePartidaFieldChange}
	/>
{:else}
	<ItemSheetInv
		bind:open={showItemSheet}
		{isEditMode}
		bind:editingItem
		{invoice}
		{isTargetingPreset}
		onSave={saveItem}
		onCancel={() => {
			showItemSheet = false;
		}}
		{isSaving}
	/>
{/if}
