<script lang="ts">
	import { onMount } from 'svelte';
	import * as Card from '$lib/components/ui/card';
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as RadioGroup from '$lib/components/ui/radio-group';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import { Separator } from '$lib/components/ui/separator';
	import {
		Printer,
		HelpCircle,
		X,
		Calendar,
		FileSearch,
		Filter,
		Globe,
		Search,
		Mail,
		Info,
		ChevronRight,
		Book,
		MapPin,
		FileText,
		Settings,
		FileSpreadsheet,
		ArrowLeftRight,
		ShieldCheck,
		Calculator,
		Download,
		Folder,
		Eye,
		CalendarRange,
		LayoutList,
		Image as ImageIcon,
		Maximize2,
		Table2,
		Scale,
		Scan
	} from 'lucide-svelte';
	import * as DropdownMenu from '$lib/components/ui/dropdown-menu';
	import * as Dialog from '$lib/components/ui/dialog';
	import { toast } from 'svelte-sonner';
	import PdfProgressDialog from '$lib/components/dashboard/invoices/pdf-progress-dialog.svelte';
	import DownloadedPartsForm from '$lib/components/dashboard/reports/downloaded-parts-form.svelte';
	import {
		invoiceMovementsApi,
		type MovementItem,
		type MovementItemDetailed,
		type AllMovementsFilter
	} from '$lib/api/dashboard/a76/invoice-movements';
	import type { BaseFilter } from '$lib/api/dashboard/a76/invoice-movements';
	import { saldosReportApi, type SaldosFilter } from '$lib/api/dashboard/a76/saldos-report';
	import { api } from '$lib/api';
	import { companyStore } from '$lib/stores/company.svelte';
	import { page } from '$app/state';

	// 🛡️ SEGURIDAD
	import { currentUser, userHasPermission } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	interface PageData {
		status?: number;
		error?: string;
		[key: string]: any;
	}

	let { data }: { data: PageData } = $props();

	let createDialogOpen = $state(false);
	let status = $state<number>(data.status || 200);
	let error = $state<string | null>(data.error || null);

	const canView = $derived(userHasPermission($currentUser, 'report.view'));
	const canProcess = $derived(userHasPermission($currentUser, 'report.process'));

	const isError = $derived(!canView || status >= 400 || error);

	// --- ESTADO CON RUNAS (SVELTE 5) ---

	let activeReportType = $state<'invoices' | 'saldos' | 'partes_descargadas'>('invoices');

	const menuOptions = [
		{
			label: 'Saldos Temporales',
			icon: Calculator,
			onclick: () => {
				activeReportType = 'saldos';
				showResults = false;
			}
		},
		{
			label: 'Descargos',
			icon: FileSpreadsheet,
			onclick: () => {
				activeReportType = 'partes_descargadas';
				showResults = false;
			}
		},
		{
			label: 'Catálogos',
			icon: Book,
			items: [
				'Agentes Aduanales',
				'Clases',
				'Partes',
				'Clientes Proveedores',
				'Fracciones Americanas y de Canada',
				'Pedimentos',
				'Partidas',
				'Tipos de Cambio',
				'Transportistas',
				'Unidades de Medida',
				'Interfaz Impo-Expo',
				'Carta Porte',
				'Listado de Entradas'
			]
		},
		{ label: 'Búsquedas', icon: Search, items: [] },
		{ label: 'Localizaciones', icon: MapPin, items: [] },
		{
			label: 'Declaraciones',
			icon: FileText,
			items: ['Hoja de Cálculo', 'Manifestación al Valor', 'Importación vs Exportación']
		},
		{
			label: 'Generales',
			icon: Settings,
			items: ['Verificación de Pedimento', 'Reporte de Pedimentos por A. Aduanal']
		},
		{
			label: 'EXCEL',
			icon: FileSpreadsheet,
			items: ['Depreciación de Activo Fijo']
		},
		{
			label: 'Movimientos',
			icon: ArrowLeftRight,
			items: ['Facturas Impo/Expo', 'Partidas Impo/Expo', 'Reporte de lotes']
		},
		{ label: 'Auditorias', icon: ShieldCheck, items: ['SCAF vs Almacén'] }
	];

	let dates = $state({
		from: '',
		to: '',
		type: 'invoice' as 'invoice' | 'payment'
	});

	let types = $state({
		import: { DEF: false, TEM: false, REP: false },
		export: {
			// Tipo Principal (ahora checkboxes)
			main: { DEF: false, CREG: false, REP: false },
			// Opciones adicionales (Checkboxes)
			additional: {
				AFIJO: false,
				REEXP: false,
				NODES: false,
				DONAC: false,
				SCRAP: false,
				TODAS: false
			}
		},
		other: { VEMEX: false, CREGEXP: false, COMEX: false, TODAS: false }
	});

	let filters = $state({
		includeNA: false,
		downloaded: 'all' as 'all' | 'downloaded' | 'not_downloaded',
		omitLowBalance: false,
		balanceType: 'both' as 'normal' | 'repair' | 'both',
		level: 'all' as 'partida' | 'subpartida' | 'all'
	});

	let selectors = $state({
		provider: '',
		soldTo: '',
		pedimentoKey: '',
		assetClass: '',
		assetType: '',
		location: ''
	});

	let config = $state({
		currency: 'foreign' as 'foreign' | 'national',
		reportType: 'normal' as 'normal' | 'detailed' | 'with_download',
		exchangeRate: 'invoice_date' as 'invoice_date' | 'payment_date',
		sendEmail: false,
		julianDate: false,
		shelter: false,
		endDateAsCutoff: false,
		showPendingSeries: false,
		includeAssetTagImages: false,
		useLargeAssetTagIcons: false,
		includeReglaOctava: false
	});

	type ReportToggleKey =
		| 'endDateAsCutoff'
		| 'showPendingSeries'
		| 'includeAssetTagImages'
		| 'useLargeAssetTagIcons'
		| 'sendEmail'
		| 'julianDate'
		| 'includeReglaOctava'
		| 'shelter';

	const reportToggleOptions: {
		id: string;
		label: string;
		key: ReportToggleKey;
		icon: any;
	}[] = [
		{
			id: 'opt-cutoff',
			label: 'Activar fecha final como fecha corte',
			key: 'endDateAsCutoff',
			icon: CalendarRange
		},
		{
			id: 'opt-series',
			label: 'Mostrar Series Pendientes por descargar',
			key: 'showPendingSeries',
			icon: Scan
		},
		{
			id: 'opt-images',
			label: 'Incluir imagenes por asset tag',
			key: 'includeAssetTagImages',
			icon: ImageIcon
		},
		{
			id: 'opt-icons',
			label: 'Utilizar iconos grandes por asset tag',
			key: 'useLargeAssetTagIcons',
			icon: Maximize2
		},
		{
			id: 'opt-email',
			label: 'Enviar correos electronicos',
			key: 'sendEmail',
			icon: Mail
		},
		{
			id: 'opt-julian',
			label: 'Usar fecha juliana en reportes excel',
			key: 'julianDate',
			icon: Table2
		},
		{ id: 'opt-regla', label: 'Incluir regla octava', key: 'includeReglaOctava', icon: Scale },
		{ id: 'opt-shelter', label: 'Opcion shelter', key: 'shelter', icon: ShieldCheck }
	];

	// --- ESTADO ESPECÍFICO SALDOS TEMPORALES ---
	let saldosRangeType = $state<'pedimento' | 'payment_date' | 'invoice_date' | 'parts' | 'classes'>(
		'pedimento'
	);
	let saldosIdentifiers = $state({ from: '', to: '' });

	let loading = $state(false);
	let results = $state<MovementItem[] | MovementItemDetailed[]>([]);
	let showResults = $state(false);
	let reportTitle = $state('REPORTE DE FACTURAS');
	let currencyLabel = $state('Moneda: Pesos');

	// Progression Dialog State
	let showProgressDialog = $state(false);
	let currentTaskId = $state<string | null>(null);
	let currentStatusFunction = $state<((taskId: string) => Promise<any>) | null>(null);

	// Diálogo de selección
	let dialogOpen = $state(false);
	let dialogType:
		| 'provider'
		| 'soldTo'
		| 'pedimentoKey'
		| 'assetClass'
		| 'assetType'
		| 'location'
		| 'pedimentoFrom'
		| 'pedimentoTo'
		| 'partFrom'
		| 'partTo'
		| 'classFrom'
		| 'classTo'
		| null = $state(null);
	let clientsProviders = $state<any[]>([]);
	let pedimentoCodes = $state<any[]>([]);
	let assetClasses = $state<any[]>([]);
	let assetTypes = $state<any[]>([]);
	let locations = $state<any[]>([]);
	let pedimentosList = $state<any[]>([]);
	let partsList = $state<any[]>([]);
	let dialogSearch = $state('');
	let saldosPrintPart = $state(false);
	let saldosPrintClass = $state(true);

	// Prevenir que ambas opciones se desmarquen (comportamiento Radio obligatorio)
	$effect(() => {
		if (!saldosPrintPart && !saldosPrintClass) {
			if (saldosRangeType === 'classes') {
				saldosPrintClass = true;
			} else {
				saldosPrintPart = true;
			}
		}
	});

	// Usamos efectos específicos para simular comportamiento de Radio
	$effect(() => {
		if (saldosPrintPart) saldosPrintClass = false;
	});
	$effect(() => {
		if (saldosPrintClass) saldosPrintPart = false;
	});

	// Reset condicional de opciones según el tipo de rango seleccionado (UX)
	$effect(() => {
		if (saldosRangeType === 'parts') {
			saldosPrintPart = true;
		} else if (saldosRangeType === 'classes') {
			saldosPrintClass = true;
			if (selectors.assetClass) selectors.assetClass = '';
		}
	});

	function handleTodasChange(checked: boolean) {
		if (checked) {
			// Clarion: IF Loc:Todas = 1 THEN ...
			// Solo marca los checkboxes específicos que marca Clarion

			// Importación: Definitiva, Temporal, Reparación
			types.import.DEF = true; // Loc:ImpoDef = 1
			types.import.TEM = true; // Loc:ImpoTemp = 1
			types.import.REP = true; // Loc:ImpoRep = 1

			// Exportación Principal: Solo Cambio de Régimen
			types.export.main.CREG = true; // Loc:CamRegimen = 1
			// NO marca DEF ni REP según el código Clarion

			// Exportación Adicional: Todas las opciones
			types.export.additional.AFIJO = true; // Loc:ExpoAFijo = 1
			types.export.additional.REEXP = true; // Loc:ExpoReExp = 1
			types.export.additional.NODES = true; // Loc:ExpoNodes = 1
			types.export.additional.DONAC = true; // Loc:ExpoDonac = 1
			types.export.additional.SCRAP = true; // Loc:ExpoScrap = 1

			// Otras: VeMex y ComMex
			types.other.VEMEX = true; // Loc:VeMex = 1
			types.other.COMEX = true; // Loc:ComMex = 1
			// NO marca CREGEXP según el código Clarion
		} else {
			// Clarion: ELSE ... = 0
			// Desmarcar los mismos checkboxes
			types.import.DEF = false;
			types.import.TEM = false;
			types.import.REP = false;

			types.export.main.CREG = false;

			types.export.additional.AFIJO = false;
			types.export.additional.REEXP = false;
			types.export.additional.NODES = false;
			types.export.additional.DONAC = false;
			types.export.additional.SCRAP = false;

			types.other.VEMEX = false;
			types.other.COMEX = false;
		}
	}

	onMount(() => {
		const type = page.url.searchParams.get('type');
		if (type === 'saldos') {
			activeReportType = 'saldos';
		}
	});

	function handleSaldosRangeTypeChange(type: typeof saldosRangeType) {
		saldosRangeType = type;
		dates.from = '';
		dates.to = '';
		saldosIdentifiers.from = '';
		saldosIdentifiers.to = '';
	}

	function generateSaldosReport() {
		if (!canView) return toast.error('No tienes permiso para ver reportes.');
		if (!canProcess) return toast.error('No tienes permiso para generar saldos.');

		// Validaciones de rango
		if (
			saldosRangeType === 'pedimento' ||
			saldosRangeType === 'parts' ||
			saldosRangeType === 'classes'
		) {
			if (!saldosIdentifiers.from || !saldosIdentifiers.to) {
				toast.error('Debe ingresar ambos límites del rango (Desde/Hasta)');
				return;
			}
		}

		if (
			saldosRangeType === 'payment_date' ||
			saldosRangeType === 'invoice_date' ||
			saldosRangeType === 'parts' ||
			saldosRangeType === 'classes'
		) {
			if (!dates.from || !dates.to) {
				toast.error('Debe ingresar ambas fechas del rango (Desde/Hasta)');
				return;
			}
		}

		loading = true;

		const filter: SaldosFilter = {
			// Range
			range_type: saldosRangeType,
			start_date: saldosIdentifiers.from || null,
			end_date: saldosIdentifiers.to || null,
			date_start: dates.from || null,
			date_end: dates.to || null,

			// Column 2
			currency: config.currency,
			report_type: config.reportType,
			exchange_rate: config.exchangeRate,
			omit_low_balance: filters.omitLowBalance,
			balance_type: filters.balanceType,
			level: filters.level,

			// Column 3
			end_date_as_cutoff: config.endDateAsCutoff,
			show_pending_series: config.showPendingSeries,
			include_asset_tag_images: config.includeAssetTagImages,
			use_large_asset_tag_icons: config.useLargeAssetTagIcons,
			send_email: config.sendEmail,
			julian_date: config.julianDate,
			include_regla_octava: config.includeReglaOctava,
			shelter: config.shelter,

			// Print options
			print_part: saldosPrintPart,
			print_class: saldosPrintClass,

			// Selectors
			provider: selectors.provider || null,
			buyer: selectors.soldTo || null,
			asset_class: selectors.assetClass || null,
			asset_type: selectors.assetType || null,
			location: selectors.location || null,
			pedimento_code: selectors.pedimentoKey || null
		};

		saldosReportApi
			.generateReportAsync(filter, companyStore.activeCompany?.id!)
			.then((response) => {
				const taskId = response.data?.task_id;
				if (!taskId) {
					toast.error('Error al iniciar la generación del reporte');
					loading = false;
					return;
				}

				// Adapter para PdfProgressDialog (mapea status->state, meta->info)
				const getMappedTaskStatus = async (id: string) => {
					const res = await saldosReportApi.getTaskStatus(id);
					return {
						state: res.data?.status || 'UNKNOWN',
						info: res.data?.meta,
						result: res.data?.result
					};
				};

				// Mostrar el dialogo de progreso
				showProgressDialog = true;
				currentTaskId = taskId;
				currentStatusFunction = getMappedTaskStatus;
			})
			.catch((error: any) => {
				toast.error(error.message || 'Error al iniciar la generación del reporte');
				loading = false;
			});
	}

	function closeProgressDialog() {
		showProgressDialog = false;
		currentTaskId = null;
		currentStatusFunction = null;
	}

	function onCsvComplete(result: any) {
		try {
			if (result.status === 'success') {
				const base64 = result.content;
				const binStr = atob(base64);
				const len = binStr.length;
				const arr = new Uint8Array(len);
				for (let i = 0; i < len; i++) {
					arr[i] = binStr.charCodeAt(i);
				}
				// Agregar Byte Order Mark (BOM) para que Excel interprete correctamente el UTF-8
				const bom = new Uint8Array([0xef, 0xbb, 0xbf]);
				const blob = new Blob([bom, arr], { type: result.media_type || 'text/csv;charset=utf-8' });

				const url = window.URL.createObjectURL(blob);
				const a = document.createElement('a');
				a.href = url;
				a.download = result.file_name || 'saldos_temporales.csv';
				document.body.appendChild(a);
				a.click();
				window.URL.revokeObjectURL(url);
				document.body.removeChild(a);
				toast.success('Reporte descargado exitosamente');
			} else {
				toast.error('El worker reportó un error: ' + (result.message || 'Desconocido'));
			}
		} catch (e) {
			console.error('Error al procesar descarga:', e);
			toast.error('Error al procesar el archivo descargado');
		} finally {
			setTimeout(() => {
				showProgressDialog = false;
				currentTaskId = null;
				loading = false;
			}, 1000);
		}
	}

	// --- DERIVED STATE FOR EXPORT VALIDATION ---

	/**
	 * Determine which export additional options should be disabled based on main export type selection.
	 * Rules:
	 * - If REP (Reparación) is selected: disable REEXP, DONAC, SCRAP
	 * - If CREG (C. Régimen) is selected: disable REEXP, DONAC, NODES
	 */
	const isExportAdditionalDisabled = $derived({
		REEXP: types.export.main.REP || types.export.main.CREG,
		DONAC: types.export.main.REP || types.export.main.CREG,
		SCRAP: types.export.main.REP,
		NODES: types.export.main.CREG,
		AFIJO: false,
		TODAS: false
	});

	// Auto-uncheck disabled export additional options
	$effect(() => {
		if (isExportAdditionalDisabled.REEXP && types.export.additional.REEXP) {
			types.export.additional.REEXP = false;
		}
		if (isExportAdditionalDisabled.DONAC && types.export.additional.DONAC) {
			types.export.additional.DONAC = false;
		}
		if (isExportAdditionalDisabled.SCRAP && types.export.additional.SCRAP) {
			types.export.additional.SCRAP = false;
		}
		if (isExportAdditionalDisabled.NODES && types.export.additional.NODES) {
			types.export.additional.NODES = false;
		}
	});

	// --- VALIDACIONES ---

	function formatDateToYYYYMMDD(dateStr: string): string {
		if (!dateStr) return '';
		// dateStr viene como YYYY-MM-DD del input type="date"
		return dateStr.replace(/-/g, '');
	}

	function validateDates(): { valid: boolean; message?: string } {
		if (!dates.from || !dates.to) {
			return { valid: false, message: 'El rango de fechas es obligatorio' };
		}

		const fromDate = new Date(dates.from);
		const toDate = new Date(dates.to);

		if (fromDate > toDate) {
			return { valid: false, message: 'La fecha inicial no puede ser mayor que la fecha final' };
		}

		// Validar que no sea más de 1 año de diferencia
		const oneYearMs = 365 * 24 * 60 * 60 * 1000;
		if (toDate.getTime() - fromDate.getTime() > oneYearMs) {
			return { valid: false, message: 'El rango de fechas no puede ser mayor a 1 año' };
		}

		return { valid: true };
	}

	function validateMovementTypes(): { valid: boolean; message?: string } {
		const hasImportSelected = Object.values(types.import).some((v) => v);
		const hasOtherSelected = Object.values(types.other).some((v) => v);
		const hasExportAdditional = Object.values(types.export.additional).some((v) => v);
		const hasExportMain = Object.values(types.export.main).some((v) => v);

		if (!hasImportSelected && !hasOtherSelected && !hasExportAdditional && !hasExportMain) {
			return { valid: false, message: 'Debe seleccionar al menos un tipo de movimiento' };
		}

		return { valid: true };
	}

	function validateBusinessRules(): { valid: boolean; message?: string } {
		// Validación: Filtro de descargadas solo para Reparaciones y Exportaciones
		if (filters.downloaded !== 'all') {
			const hasRepairOrExport =
				types.import.REP ||
				Object.values(types.export.main).some((v) => v) ||
				Object.values(types.export.additional).some((v) => v);

			if (!hasRepairOrExport) {
				return {
					valid: false,
					message: 'El filtro de descargadas solo aplica a Reparaciones y Exportaciones'
				};
			}
		}

		// Si TODAS está marcado, saltar validaciones de combinaciones incompatibles
		// ya que es una combinación especial permitida en Clarion
		if (types.other.TODAS || types.export.additional.TODAS) {
			return { valid: true };
		}

		// Validación 3: COMEX y IMPDF son mutuamente excluyentes
		if (types.import.DEF && types.other.COMEX) {
			return {
				valid: false,
				message: 'No puede seleccionar IMPDF (Definitiva) y COMEX al mismo tiempo'
			};
		}

		// Validación 4: Para Exportaciones de Reparación (solo AFIJO y NODES)
		if (types.export.main.REP) {
			const invalidExportTypes =
				types.export.additional.SCRAP ||
				types.export.additional.REEXP ||
				types.export.additional.DONAC;

			if (invalidExportTypes) {
				return { valid: false, message: 'Exportaciones de Reparación solo permiten AFIJO y NODES' };
			}
		}

		// Validación 5: Para Cambio de Régimen (solo AFIJO o SCRAP)
		if (types.export.main.CREG) {
			const invalidCRegTypes =
				types.export.additional.NODES ||
				types.export.additional.REEXP ||
				types.export.additional.DONAC;

			if (invalidCRegTypes) {
				return { valid: false, message: 'Cambio de Régimen solo permite AFIJO o SCRAP' };
			}

			// No puede combinarse con otros tipos principales
			if (types.export.main.DEF || types.export.main.REP) {
				return {
					valid: false,
					message:
						'Cambio de Régimen no puede combinarse con otros tipos de exportación principales'
				};
			}
		}

		// Validación 6: VEMEX no puede combinarse con otros tipos de export
		if (types.other.VEMEX) {
			const hasOtherExports =
				types.export.additional.AFIJO ||
				types.export.additional.NODES ||
				types.export.additional.SCRAP ||
				types.export.additional.REEXP ||
				types.export.additional.DONAC ||
				Object.values(types.export.main).some((v) => v);

			if (hasOtherExports) {
				return {
					valid: false,
					message: 'VEMEX no puede combinarse con otros tipos de exportación'
				};
			}
		}

		// Validación 7: CREGEXP (Cambio Régimen Export) validaciones
		if (types.other.CREGEXP) {
			const hasOtherTypes =
				types.import.DEF ||
				types.import.TEM ||
				types.import.REP ||
				Object.values(types.export.main).some((v) => v) ||
				Object.values(types.export.additional).some((v) => v) ||
				types.other.VEMEX ||
				types.other.COMEX;

			if (hasOtherTypes) {
				return {
					valid: false,
					message: 'Cambio Régimen Export no puede combinarse con otros tipos'
				};
			}
		}

		// Validación 8: Tipo de fecha debe ser FF o FP
		if (dates.type !== 'invoice' && dates.type !== 'payment') {
			return { valid: false, message: 'Tipo de fecha debe ser Factura (FF) o Pago (FP)' };
		}

		return { valid: true };
	}

	// --- LÓGICA ---

	// Estado del Context Menu
	let contextMenu = $state({
		open: false,
		x: 0,
		y: 0
	});

	function handleContextMenu(e: MouseEvent) {
		e.preventDefault();
		contextMenu = {
			open: true,
			x: e.clientX,
			y: e.clientY
		};
	}

	function closeContextMenu() {
		contextMenu.open = false;
	}

	// Acción: Generar Reporte (Email / Background) - Click Izquierdo
	async function generateReport() {
		if (!canView) return toast.error('No tienes permiso para ver reportes.');
		if (!canProcess) return toast.error('No tienes permiso para procesar reportes.');

		const filter = buildAllMovementsFilter();
		if (!filter) return;

		// Email sending is controlled by config.sendEmail checkbox

		loading = true;
		// Initial toast
		const toastId = toast.loading('Iniciando generación de reporte...');

		try {
			// 1. Trigger Async Generation
			const response = await invoiceMovementsApi.generateReportAsync(companyStore.activeCompany?.id!, filter);

			if (!response.data || !response.data.task_id) {
				toast.error('Error al iniciar la generación del reporte', { id: toastId });
				loading = false;
				return;
			}

			const taskId = response.data.task_id;

			// 2. Poll for status
			const pollInterval = setInterval(async () => {
				try {
					const statusResponse = await invoiceMovementsApi.getTaskStatus(taskId);
					const statusData = statusResponse.data;

					if (!statusData) return;

					if (statusData.status === 'SUCCESS') {
						clearInterval(pollInterval);
						loading = false;

						// Download the file automatically
						if (statusData.result?.content) {
							try {
								// Decode base64 content
								const base64Content = statusData.result.content;
								const binaryString = atob(base64Content);
								const bytes = new Uint8Array(binaryString.length);
								for (let i = 0; i < binaryString.length; i++) {
									bytes[i] = binaryString.charCodeAt(i);
								}

								// Create blob and download
								const blob = new Blob([bytes], { type: 'text/csv;charset=utf-8;' });
								const url = window.URL.createObjectURL(blob);
								const link = document.createElement('a');
								link.href = url;
								link.download = statusData.result.file_name || 'reporte_facturas.csv';
								document.body.appendChild(link);
								link.click();
								document.body.removeChild(link);
								window.URL.revokeObjectURL(url);

								toast.success(
									`Reporte generado y descargado.${config.sendEmail ? ' También se ha enviado por correo.' : ''}`,
									{
										id: toastId
									}
								);
							} catch (downloadErr) {
								console.error('Error downloading file:', downloadErr);
								toast.success(
									`Reporte generado correctamente.${config.sendEmail ? ' Se ha enviado un correo con los resultados.' : ''}`,
									{ id: toastId }
								);
							}
						} else {
							toast.success(
								`Reporte generado correctamente.${config.sendEmail ? ' Se ha enviado un correo con los resultados.' : ''}`,
								{ id: toastId }
							);
						}
					} else if (statusData.status === 'FAILURE') {
						clearInterval(pollInterval);
						loading = false;
						// Try to extract specific error from meta or result
						const errorMsg =
							statusData.meta?.exc_message ||
							statusData.result?.exc_message ||
							statusData.result?.detail ||
							'Error en la generación del reporte';

						console.error('Task Failure Details:', statusData);
						toast.error(errorMsg, { id: toastId });
					} else if (statusData.status === 'PROCESSING') {
						// Update progress
						if (statusData.meta) {
							const { current, total, status } = statusData.meta;
							const percentage = Math.round((current / total) * 100);
							toast.loading(`${status} (${percentage}%)`, { id: toastId });
						}
					}
				} catch (err) {
					console.error('Error polling status:', err);
					// Don't stop polling on transient network errors, but maybe log it
				}
			}, 1000); // Poll every 1 second
		} catch (error: any) {
			console.error('Error generando reporte:', error);
			toast.error(error.message || 'Error al generar el reporte', { id: toastId });
			loading = false;
		}
	}

	// Acción: Vista Previa (Tabla) - Click Derecho -> Opción
	async function previewReport() {
		if (!canView) return toast.error('No tienes permiso para ver reportes.');
		
		closeContextMenu();
		const filter = buildAllMovementsFilter();
		if (!filter) return;

		// Para preview, no enviamos correo (o respetamos config, pero generalmente preview es solo ver)
		filter.send_email = false;

		loading = true;
		results = [];
		showResults = false;

		toast.info('Cargando vista previa...');

		try {
			const response = await invoiceMovementsApi.getAllMovements(companyStore.activeCompany?.id!, filter);

			if (response.error) {
				toast.error(response.error);
				return;
			}

			if (response.data) {
				results = response.data;
				showResults = true;

				if (results.length === 0) {
					toast.warning('No se encontraron resultados con los filtros seleccionados');
				} else {
					toast.success(`${results.length} registros cargados en vista previa`);
				}
			}
		} catch (error: any) {
			console.error('Error generando vista previa:', error);
			toast.error(error.message || 'Error al generar la vista previa');
		} finally {
			loading = false;
		}
	}

	// Helper para construir el filtro (extraído de la lógica anterior)
	function buildAllMovementsFilter(): AllMovementsFilter | null {
		// Validaciones
		const dateValidation = validateDates();
		if (!dateValidation.valid) {
			toast.error(`Error: ${dateValidation.message}`);
			return null;
		}
		const movementValidation = validateMovementTypes();
		if (!movementValidation.valid) {
			toast.error(`Error: ${movementValidation.message}`);
			return null;
		}
		const businessValidation = validateBusinessRules();
		if (!businessValidation.valid) {
			toast.error(`Error: ${businessValidation.message}`);
			return null;
		}

		const allMovementsFilter: AllMovementsFilter = {
			range_type: dates.type === 'invoice' ? 'FF' : 'FP',
			start_date: formatDateToYYYYMMDD(dates.from),
			end_date: formatDateToYYYYMMDD(dates.to),
			include_cancelled: filters.includeNA,
			provider: selectors.provider || null,
			buyer: selectors.soldTo || null,
			pedimento_code: selectors.pedimentoKey || null,
			report_type: config.reportType === 'normal' ? 'Normal' : 'Detallado',
			currency_type: config.currency === 'foreign' ? 'ME' : 'MN',
			exchange_rate_type: config.exchangeRate === 'invoice_date' ? 'FF' : 'FP',
			is_shelter: config.shelter,
			// Granular flags
			import_temp: !!types.import.TEM,
			import_def: !!types.import.DEF,
			import_rep: !!types.import.REP,
			export_def: !!(
				types.export.main.DEF ||
				types.other.VEMEX ||
				types.export.additional.TODAS ||
				Object.values(types.export.additional).some((v) => v)
			),
			export_rep: !!types.export.main.REP,
			send_email: config.sendEmail
		};

		// Override flags if "TODAS" is selected
		if (types.other.TODAS) {
			allMovementsFilter.import_temp = true;
			allMovementsFilter.import_def = true;
			allMovementsFilter.import_rep = true;
			allMovementsFilter.export_def = true;
			allMovementsFilter.export_rep = true;
			allMovementsFilter.operation_type = null;
		} else if (types.export.additional.TODAS) {
			// TODAS for exports: only search export movements
			allMovementsFilter.import_temp = false;
			allMovementsFilter.import_def = false;
			allMovementsFilter.import_rep = false;
			allMovementsFilter.export_def = true;
			allMovementsFilter.export_rep = true;
			allMovementsFilter.operation_type = 'exp';
		} else {
			const hasImports =
				allMovementsFilter.import_temp ||
				allMovementsFilter.import_def ||
				allMovementsFilter.import_rep;
			const hasExports = allMovementsFilter.export_def || allMovementsFilter.export_rep;

			if (hasImports && hasExports) {
				allMovementsFilter.operation_type = null;
			} else if (hasImports) {
				allMovementsFilter.operation_type = 'imp';
			} else if (hasExports) {
				allMovementsFilter.operation_type = 'exp';
			}
		}

		// Set discharge filter (Global)
		const dischargeFilter =
			filters.downloaded === 'downloaded'
				? 'SiDes'
				: filters.downloaded === 'not_downloaded'
					? 'NoDes'
					: 'ALL';
		allMovementsFilter.discharge_filter = dischargeFilter;

		return allMovementsFilter;
	}

	async function handleGenerateReport() {
		// Wrapper for compatibility if button still calls this
		await generateReport();
	}

	function downloadCSV() {
		if (results.length === 0) {
			toast.error('No hay resultados para exportar');
			return;
		}

		const lines: string[] = [];

		// Título del reporte
		lines.push(reportTitle);
		lines.push(''); // Línea vacía

		// Información de moneda
		lines.push(currencyLabel);
		lines.push(''); // Línea vacía

		// Total de registros
		lines.push(`TOTAL DE REGISTROS:,${results.length}`);
		lines.push(''); // Línea vacía

		if (config.reportType === 'normal') {
			// Headers modo NORMAL (22 columnas)
			const headers = [
				'PEDIMENTO',
				'PEDIMENTO18',
				'CLAVE',
				'PEDIMENTO R1',
				'FACTURA',
				'FECHA FACT',
				'VALOR TOTAL',
				'TIPO DE CAMBIO',
				'TIPO OPER.',
				'TIPO EXPO.',
				'CAMBIO REG.',
				'ESTATUS',
				'E-DOCUMENT',
				'NUM. OPERACION',
				'NÚMERO GAFETE ÚNICO',
				'ADUANA CRUCE',
				'PROYECTO',
				'USUARIO QUE CAPTURÓ LA FACTURA',
				'USUARIO QUE ACTUALIZÓ LA FACTURA',
				'FECHA PAGO',
				'NUM. CAJA',
				'SECUENCIA'
			];
			lines.push(headers.join(','));
			lines.push(''); // Línea vacía

			// Datos modo normal
			results.forEach((row) => {
				const values = [
					row.Pedimento || '',
					row.Pedimento18 || '',
					row.ClavePed || '',
					row.PedimentoR1 || '',
					`"${row.Factura}"`,
					config.julianDate ? row.FechaFactura || '' : formatDateFromYYYYMMDD(row.FechaFactura),
					row.ValorComercialMN || '0',
					row.TipoCambio || '0',
					row.TipoMovTemDef || '',
					row.TipoExpo || '',
					row.EsCambioRegimen || '',
					row.Estatus || '',
					row.EDocument || '',
					row.NumOperacionVU || '',
					row.NumGafUni || '',
					`"${row.AduanaCru || ''}"`,
					row.BaseDeDatos || '',
					row.UsuarioCap || '',
					row.UsuarioAcr || '',
					config.julianDate ? row.Fecha_Pago || '' : formatDateFromYYYYMMDD(row.Fecha_Pago),
					row.NumCaja || '',
					row.Lote || ''
				];
				lines.push(values.join(','));
			});
		} else {
			// Headers modo DETALLADO (47 columnas - más columnas que el normal)
			const headers = [
				'PEDIMENTO',
				'PEDIMENTO 18',
				'CLAVE',
				'REGIMEN',
				'PEDIMENTO R1',
				'FECHA INICIO',
				'FECHA FINAL',
				'FECHA PAGO',
				'REMESA',
				'FACTURA',
				'FECHA FACT',
				'FECHA EMISION',
				'PROVEEDOR',
				'RFC PROV.',
				'TAX ID PROV.',
				'CLIENTE',
				'RFC CLI.',
				'TAX ID CLI.',
				'AGENTE ADUANAL',
				'PATENTE',
				'ADUANA',
				'CLASE',
				'DESC ESPAÑOL',
				'DESC INGLES',
				'CANT. IMPO/EXPO',
				'U.M.',
				'VALOR COMERC',
				'TIPO DE CAMBIO',
				'PESO NETO',
				'PESO BRUTO',
				'ORDEN COMPRA/VENTA',
				'FRACCION ARANC.',
				'PREFERENCIA',
				'SECTOR',
				'PAIS ORIGEN',
				'TIPO OPER.',
				'TIPO EXPO.',
				'PARTIDA/SUBPARTIDA',
				'CAMBIO REG.',
				'ESTATUS',
				'E-DOCUMENT',
				'NUM. OPERACION',
				'MARCA',
				'MODELO',
				'SERIE(S)',
				'NÚMERO GAFETE ÚNICO',
				'FRACCION AMERICANA',
				'ECCN',
				'SIMBOLO DE LA EXCEPCION DE LICENCIA',
				'ADUANA CRUCE',
				'PROYECTO',
				'USUARIO QUE CAPTURÓ LA FACTURA',
				'USUARIO QUE ACTUALIZÓ LA FACTURA',
				'NUM CAJA',
				'TRANSPORTISTA',
				'LOTE',
				'LINEA PARTIDA'
			];
			lines.push(headers.join(','));
			lines.push(''); // Línea vacía

			// Datos modo detallado
			results.forEach((row: any) => {
				const values = [
					row.Pedimento || '',
					row.Pedimento18 || '',
					row.ClavePed || '',
					row.Regimen || '',
					row.PedimentoR1 || '',
					config.julianDate ? row.Fecha_Inicio || '' : formatDateFromYYYYMMDD(row.Fecha_Inicio),
					config.julianDate ? row.Fecha_Fin || '' : formatDateFromYYYYMMDD(row.Fecha_Fin),
					config.julianDate ? row.Fecha_Pago || '' : formatDateFromYYYYMMDD(row.Fecha_Pago),
					row.Remesa || '',
					`"${row.Factura}"`,
					config.julianDate ? row.FechaFactura || '' : formatDateFromYYYYMMDD(row.FechaFactura),
					config.julianDate ? row.FechaEmision || '' : formatDateFromYYYYMMDD(row.FechaEmision),
					row.Proveedor || '',
					row.RFCProveedor || '',
					row.ProveedorTaxID || '',
					row.VendidoA || '',
					row.VendidoARFC || '',
					row.VendidoATaxID || '',
					row.AgenteAduanal || '',
					row.Patente || '',
					row.Aduana || '',
					row.NumParte || '',
					row.DescripcionE || '',
					row.DescripcionI || '',
					row.CantidadIE || '0',
					row.UniMed || '',
					row.ValorComercialMN || '0',
					row.TipoCambio || '0',
					row.PesoNeto || '0',
					row.PesoBruto || '0',
					row.OrdenCompraVenta || '',
					row.FraccionArancelaria || '',
					row.Preferencia || '',
					row.Sector || '',
					row.PaisOrigen || '',
					row.TipoMovTemDef || '',
					row.TipoExpo || '',
					row.Advalorem || '',
					row.EsCambioRegimen || '',
					row.Estatus || '',
					row.EDocument || '',
					row.NumOperacionVU || '',
					row.Marca || '',
					row.Modelo || '',
					row.Series || '',
					row.NumGafUni || '',
					row.FraccionAmericana || '',
					row.ECCN || '',
					row.SimboloEx || '',
					`"${row.AduanaCru || ''}"`,
					row.BaseDeDatos || '',
					row.UsuarioCap || '',
					row.UsuarioAcr || '',
					row.NumCaja || '',
					row.Transportista || '',
					row.Lote || '',
					row.Linea || ''
				];
				lines.push(values.join(','));
			});
		}

		const csv = lines.join('\n');
		const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
		const url = URL.createObjectURL(blob);
		const link = document.createElement('a');
		link.href = url;
		const mode = config.reportType === 'normal' ? 'normal' : 'detallado';
		link.download = `reporte_facturas_${mode}_${formatDateToYYYYMMDD(dates.from)}_${formatDateToYYYYMMDD(dates.to)}.csv`;
		link.click();
		URL.revokeObjectURL(url);

		toast.success('Reporte descargado exitosamente');
	}

	function formatDateFromYYYYMMDD(dateStr: string | null): string {
		if (!dateStr || dateStr === '-' || dateStr === '0') return '-';

		// Si es un timestamp ISO (contiene 'T' o '-')
		if (dateStr.includes('T') || (dateStr.includes('-') && dateStr.length > 8)) {
			try {
				const date = new Date(dateStr);
				// Verificar si es una fecha válida
				if (isNaN(date.getTime())) return '-';
				// Si es 1970 o anterior, es una fecha inválida/vacía
				if (date.getFullYear() <= 1970) return '-';

				const day = String(date.getDate()).padStart(2, '0');
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const year = date.getFullYear();
				return `${day}/${month}/${year}`;
			} catch {
				return '-';
			}
		}

		// YYYYMMDD -> DD/MM/YYYY
		if (dateStr.length === 8 && /^\d{8}$/.test(dateStr)) {
			const year = dateStr.substring(0, 4);
			const month = dateStr.substring(4, 6);
			const day = dateStr.substring(6, 8);
			return `${day}/${month}/${year}`;
		}

		return dateStr;
	}

	function formatCurrency(value: number | null | undefined): string {
		if (value === null || value === undefined) return '-';
		return new Intl.NumberFormat('en-US', {
			minimumFractionDigits: 2,
			maximumFractionDigits: 2
		}).format(value);
	}

	function handleClose() {
		// Reset form instead of navigating back
		showResults = false;
		results = [];
		loading = false;
	}

	async function openSelectionDialog(type: NonNullable<typeof dialogType>) {
		dialogType = type;
		dialogSearch = '';

		if (type === 'pedimentoKey') {
			// Cargar claves de pedimento
			try {
				const response = await api.get(
					'/v1/public/reference_data/pedimento-codes/?page=1&page_size=1000'
				);
				pedimentoCodes = response.data?.items || [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando claves de pedimento:', error);
				toast.error('Error al cargar las claves de pedimento');
			}
			return;
		}

		if (type === 'assetClass') {
			try {
				const companyId = companyStore.activeCompany?.id;
				const response = await api.get(
					`/v1/a76/classes/with-fa-data?company_id=${companyId}&page_size=1000${config.shelter ? '&all_companies=true' : ''}`
				);
				assetClasses = response.data?.items ?? [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando clases:', error);
				toast.error('Error al cargar las clases');
			}
			return;
		}

		if (type === 'assetType') {
			try {
				const response = await api.get(
					`/v1/public/reference_data/material-types/?type=${encodeURIComponent('ACTIVO FIJO')}&page_size=1000`
				);
				assetTypes = response.data?.items || [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando tipos de activo:', error);
				toast.error('Error al cargar los tipos de activo');
			}
			return;
		}

		if (type === 'location') {
			try {
				const companyId = companyStore.activeCompany?.id;
				const response = await api.get(
					`/v1/a76/ports/?company_id=${companyId}&page_size=1000${config.shelter ? '&all_companies=true' : ''}`
				);
				locations = response.data?.items || [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando localizaciones:', error);
				toast.error('Error al cargar las localizaciones');
			}
			return;
		}

		if (type === 'pedimentoFrom' || type === 'pedimentoTo') {
			try {
				const companyId = companyStore.activeCompany?.id;
				const response = await api.get(
					`/v1/a76/pedimentos/?company_id=${companyId}&page_size=1000${config.shelter ? '&all_companies=true' : ''}`
				);
				pedimentosList = response.data?.items || [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando pedimentos:', error);
				toast.error('Error al cargar los pedimentos');
			}
			return;
		}

		if (type === 'partFrom' || type === 'partTo') {
			try {
				const companyId = companyStore.activeCompany?.id;
				const response = await api.get(
					`/v1/a76/parts/?company_id=${companyId}&page_size=1000${config.shelter ? '&all_companies=true' : ''}`
				);
				partsList = response.data?.items || [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando partes:', error);
				toast.error('Error al cargar las partes');
			}
			return;
		}

		if (type === 'classFrom' || type === 'classTo') {
			try {
				const companyId = companyStore.activeCompany?.id;
				const response = await api.get(
					`/v1/a76/classes/with-fa-data?company_id=${companyId}&page_size=1000${config.shelter ? '&all_companies=true' : ''}`
				);
				assetClasses = response.data?.items ?? [];
				dialogOpen = true;
			} catch (error: any) {
				console.error('Error cargando clases:', error);
				toast.error('Error al cargar las clases');
			}
			return;
		}

		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			toast.error('No hay compañía seleccionada');
			return;
		}
		let isLoadingDialog = true;
		try {
			// No filtramos por tipo en el API para obtener todos los registros
			// Filtraremos client-side para incluir 'both'
			const response = await api.get(
				`/v1/a76/clients-providers?company_id=${companyId}&limit=1000${config.shelter ? '&all_companies=true' : ''}`
			);
			const allItems = response.data?.items || [];

			// Filtrar según el tipo solicitado, incluyendo 'both'
			const searchType = type === 'provider' ? 'provider' : 'client';
			clientsProviders = allItems.filter(
				(item: any) => item.client_or_provider === searchType || item.client_or_provider === 'both'
			);

			dialogOpen = true;
		} catch (error: any) {
			console.error('Error cargando datos:', error);
			toast.error('Error al cargar la lista');
		} finally {
			isLoadingDialog = false;
		}
	}

	function selectItem(item: any) {
		if (dialogType === 'provider') {
			selectors.provider = item.name || '';
		} else if (dialogType === 'soldTo') {
			selectors.soldTo = item.name || '';
		} else if (dialogType === 'pedimentoKey') {
			selectors.pedimentoKey = item.code || '';
		} else if (dialogType === 'assetClass') {
			selectors.assetClass = item.class_code || '';
		} else if (dialogType === 'assetType') {
			selectors.assetType = item.key || '';
		} else if (dialogType === 'location') {
			selectors.location = item.location_code || '';
		} else if (dialogType === 'pedimentoFrom') {
			saldosIdentifiers.from = `${item.year}-${item.license}-${item.pedimento_number}`;
		} else if (dialogType === 'pedimentoTo') {
			saldosIdentifiers.to = `${item.year}-${item.license}-${item.pedimento_number}`;
		} else if (dialogType === 'partFrom') {
			saldosIdentifiers.from = item.part_number || '';
		} else if (dialogType === 'partTo') {
			saldosIdentifiers.to = item.part_number || '';
		} else if (dialogType === 'classFrom') {
			saldosIdentifiers.from = item.class_code || '';
		} else if (dialogType === 'classTo') {
			saldosIdentifiers.to = item.class_code || '';
		}
		dialogOpen = false;
	}

	const filteredItems = $derived(
		dialogType === 'pedimentoKey'
			? pedimentoCodes
					.filter((item) => {
						if (!dialogSearch) return true;
						const searchLower = dialogSearch.toLowerCase();
						return (
							item.code?.toLowerCase().includes(searchLower) ||
							item.description?.toLowerCase().includes(searchLower)
						);
					})
					.sort((a, b) =>
						(a.code || '').localeCompare(b.code || '', undefined, {
							numeric: true,
							sensitivity: 'base'
						})
					)
			: dialogType === 'assetClass'
				? assetClasses
						.filter((item) => {
							if (!dialogSearch) return true;
							const searchLower = dialogSearch.toLowerCase();
							return (
								item.class_code?.toLowerCase().includes(searchLower) ||
								item.description_es?.toLowerCase().includes(searchLower)
							);
						})
						.sort((a, b) =>
							(a.class_code || '').localeCompare(b.class_code || '', undefined, {
								numeric: true,
								sensitivity: 'base'
							})
						)
				: dialogType === 'assetType'
					? assetTypes
							.filter((item) => {
								if (!dialogSearch) return true;
								const searchLower = dialogSearch.toLowerCase();
								return (
									item.key?.toLowerCase().includes(searchLower) ||
									item.description?.toLowerCase().includes(searchLower)
								);
							})
							.sort((a, b) =>
								(a.key || '').localeCompare(b.key || '', undefined, {
									numeric: true,
									sensitivity: 'base'
								})
							)
					: dialogType === 'location'
						? locations
								.filter((item) => {
									if (!dialogSearch) return true;
									const searchLower = dialogSearch.toLowerCase();
									return (
										item.location_code?.toLowerCase().includes(searchLower) ||
										item.location_description?.toLowerCase().includes(searchLower)
									);
								})
								.sort((a, b) =>
									(a.location_code || '').localeCompare(b.location_code || '', undefined, {
										numeric: true,
										sensitivity: 'base'
									})
								)
						: dialogType === 'pedimentoFrom' || dialogType === 'pedimentoTo'
							? pedimentosList
									.filter((item) => {
										if (!dialogSearch) return true;
										const searchLower = dialogSearch.toLowerCase();
										return (
											item.pedimento_number?.toLowerCase().includes(searchLower) ||
											item.license?.toLowerCase().includes(searchLower)
										);
									})
									.sort((a, b) =>
										(a.pedimento_number || '').localeCompare(b.pedimento_number || '', undefined, {
											numeric: true,
											sensitivity: 'base'
										})
									)
							: dialogType === 'partFrom' || dialogType === 'partTo'
								? partsList
										.filter((item) => {
											if (!dialogSearch) return true;
											const searchLower = dialogSearch.toLowerCase();
											return (
												item.part_number?.toLowerCase().includes(searchLower) ||
												item.description_spanish?.toLowerCase().includes(searchLower)
											);
										})
										.sort((a, b) =>
											(a.part_number || '').localeCompare(b.part_number || '', undefined, {
												numeric: true,
												sensitivity: 'base'
											})
										)
								: dialogType === 'classFrom' || dialogType === 'classTo'
									? assetClasses
											.filter((item) => {
												if (!dialogSearch) return true;
												const searchLower = dialogSearch.toLowerCase();
												return (
													item.class_code?.toLowerCase().includes(searchLower) ||
													item.description_es?.toLowerCase().includes(searchLower)
												);
											})
											.sort((a, b) =>
												(a.class_code || '').localeCompare(b.class_code || '', undefined, {
													numeric: true,
													sensitivity: 'base'
												})
											)
									: clientsProviders
											.filter((item) => {
												if (!dialogSearch) return true;
												const searchLower = dialogSearch.toLowerCase();
												return (
													item.name?.toLowerCase().includes(searchLower) ||
													item.rfc?.toLowerCase().includes(searchLower) ||
													item.tax_id?.toLowerCase().includes(searchLower)
												);
											})
											.sort((a, b) =>
												(a.name || '').localeCompare(b.name || '', undefined, {
													numeric: true,
													sensitivity: 'base'
												})
											)
	);
</script>

<svelte:window onclick={closeContextMenu} />

<div
	class="animate-in fade-in slide-in-from-bottom-4 flex min-h-full flex-col gap-1.5 pb-4 duration-500"
>
	<!-- Encabezado de Página Compacto -->
	<div class="flex shrink-0 flex-col gap-1 px-1 sm:flex-row sm:items-center sm:justify-between">
		<div class="flex min-w-0 items-center gap-2 sm:gap-3">
			<h1 class="flex items-center gap-2 text-lg font-bold tracking-tight text-foreground sm:text-xl">
				{#if activeReportType === 'invoices'}
					<FileSearch class="h-6 w-6 text-primary" />
					Reporte de Facturas
				{:else if activeReportType === 'partes_descargadas'}
					<Button
						variant="ghost"
						size="icon"
						class="h-8 w-8 text-muted-foreground hover:text-primary"
						onclick={() => (activeReportType = 'invoices')}
					>
                        <ArrowLeftRight class="h-5 w-5 rotate-180" />
					</Button>
					<FileSearch class="h-6 w-6 text-primary" />
					Partes Descargadas
				{:else}
					<Button
						variant="ghost"
						size="icon"
						class="h-8 w-8 text-muted-foreground hover:text-primary"
						onclick={() => (activeReportType = 'invoices')}
					>
                        <ArrowLeftRight class="h-5 w-5 rotate-180" />
					</Button>
					<Calculator class="h-6 w-6 text-primary" />
					Saldos Temporales
				{/if}
			</h1>
			<span
				class="rounded-full border bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground"
			>
				V2.0
			</span>
		</div>
		<div class="text-[11px] text-muted-foreground sm:text-xs">
			{#if activeReportType === 'invoices'}
				Reportes de Movimientos Impo/Expo
			{:else if activeReportType === 'partes_descargadas'}
				Reportes de Partes Descargadas
			{:else}
				Reportes de Control Fiscal
			{/if}
		</div>
	</div>

	<Separator />

	{#if isError}
		<ErrorState
			status={!canView ? 403 : status}
			error={!canView ? 'Permission denied: report.view' : error || ''}
			onRetry={() => window.location.reload()}
		/>
	{:else}
		<!-- Sección de Acceso Rápido (Gestión de Pedimentos) Compacta -->

	<div class="grid shrink-0 grid-cols-2 gap-2 sm:grid-cols-4 md:grid-cols-5 xl:grid-cols-10">
		{#each menuOptions as item}
			{#if item.items && item.items.length > 0}
				<DropdownMenu.Root>
					<DropdownMenu.Trigger class="w-full">
						{#snippet child({ props })}
							<Button
								{...props}
								variant="outline"
								size="sm"
								class="flex h-10 w-full items-center justify-center gap-2 border-dashed text-muted-foreground transition-all hover:border-solid hover:border-primary/50 hover:bg-primary/5 hover:text-primary"
							>
								<item.icon class="h-4 w-4" />
								<span class="hidden text-xs font-bold tracking-wider uppercase xl:inline-block"
									>{item.label}</span
								>
							</Button>
							{/snippet}
					</DropdownMenu.Trigger>
					<DropdownMenu.Content class="w-56">
						<DropdownMenu.Label
							class="text-xs font-bold tracking-wider text-muted-foreground uppercase"
							>{item.label}</DropdownMenu.Label
						>
						<DropdownMenu.Separator />
						<div class="max-h-[300px] overflow-y-auto">
							{#each item.items as subItem}
								<DropdownMenu.Item onclick={() => {
									if (subItem === 'Partes Descargadas') {
										activeReportType = 'partes_descargadas';
										showResults = false;
									} else {
										toast.info(`Seleccionado: ${subItem}`);
									}
								}}>
									{subItem}
								</DropdownMenu.Item>
							{/each}
						</div>
					</DropdownMenu.Content>
				</DropdownMenu.Root>
			{:else}
				<Button
					variant="outline"
					size="sm"
					class="flex h-10 w-full items-center justify-center gap-2 border-dashed text-muted-foreground transition-all hover:border-solid hover:border-primary/50 hover:bg-primary/5 hover:text-primary"
					onclick={() => {
						if ('onclick' in item && item.onclick) {
							(item as any).onclick();
						} else if ('url' in item && item.url) {
							window.location.href = (item as any).url;
						} else {
							toast.info(`Acción rápida: ${item.label}`);
						}
					}}
				>
					<item.icon class="h-4 w-4" />
					<span class="hidden text-xs font-bold tracking-wider uppercase xl:inline-block"
						>{item.label}</span
					>
				</Button>
			{/if}
		{/each}
	</div>

	<Separator />

	<!-- Contenido Principal - Layout Normal -->
	<div class="grid grid-cols-1 content-start items-start gap-2 text-foreground xl:grid-cols-2 2xl:grid-cols-3">
		{#if activeReportType === 'invoices'}
			<!-- Columna 1: Fechas y Clasificación -->
			<Card.Root class="flex h-full flex-col">
				<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
					<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
						<Calendar class="h-4 w-4" /> Periodo y Clasificación
					</Card.Title>
				</Card.Header>
				<Card.Content class="flex-1 space-y-3 p-3">
					<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
						<div class="flex-1 space-y-1">
							<Label class="text-xs font-bold text-muted-foreground uppercase">Fecha Inicio</Label>
							<Input
								type="date"
								class="h-8 cursor-pointer"
								bind:value={dates.from}
								onclick={(e) => {
									const input = e.currentTarget;
									if (input && typeof input.showPicker === 'function') {
										input.showPicker();
									}
								}}
							/>
						</div>
						<div class="flex-1 space-y-1">
							<Label class="text-xs font-bold text-muted-foreground uppercase">Fecha Fin</Label>
							<Input
								type="date"
								class="h-8 cursor-pointer"
								bind:value={dates.to}
								onclick={(e) => {
									const input = e.currentTarget;
									if (input && typeof input.showPicker === 'function') {
										input.showPicker();
									}
								}}
							/>
						</div>
					</div>

					<Separator />

					<div class="space-y-4">
						<!-- Importación -->
						<div>
							<Label
								class="mb-2 block border-b pb-1 text-xs font-bold text-muted-foreground uppercase"
								>Importación</Label
							>
							<div class="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
								{#each Object.keys(types.import) as key}
									<div class="flex items-center space-x-2">
										<Checkbox
											id="imp-{key}"
											class="h-3.5 w-3.5"
											disabled={types.other.TODAS}
											bind:checked={types.import[key as keyof typeof types.import]}
										/>
										<Label for="imp-{key}" class="cursor-pointer text-xs font-medium">
											{key === 'DEF' ? 'Definitiva' : key === 'TEM' ? 'Temporal' : 'Reparación'}
										</Label>
									</div>
								{/each}
							</div>
						</div>

						<!-- Exportación -->
						<div>
							<Label
								class="mb-2 block border-b pb-1 text-xs font-bold text-muted-foreground uppercase"
								>Exportación</Label
							>
							<div class="space-y-3">
								<!-- Main Types -->
								<div class="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
									<div class="flex items-center space-x-2">
										<Checkbox
											id="exp-m-def"
											class="h-3.5 w-3.5"
											disabled={types.other.TODAS}
											bind:checked={types.export.main.DEF}
										/>
										<Label for="exp-m-def" class="cursor-pointer text-xs font-medium"
											>Definitiva</Label
										>
									</div>
									<div class="flex items-center space-x-2">
										<Checkbox
											id="exp-m-creg"
											class="h-3.5 w-3.5"
											disabled={types.other.TODAS}
											bind:checked={types.export.main.CREG}
										/>
										<Label for="exp-m-creg" class="cursor-pointer text-xs font-medium"
											>C. Régimen</Label
										>
									</div>
									<div class="flex items-center space-x-2">
										<Checkbox
											id="exp-m-rep"
											class="h-3.5 w-3.5"
											disabled={types.other.TODAS}
											bind:checked={types.export.main.REP}
										/>
										<Label for="exp-m-rep" class="cursor-pointer text-xs font-medium"
											>Reparación</Label
										>
									</div>
								</div>

								<!-- Additional Options (Sin subtítulo) -->
								<div class="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
									{#each Object.keys(types.export.additional) as key}
										<div class="flex items-center space-x-2">
											<Checkbox
												id="exp-add-{key}"
												class="h-3.5 w-3.5"
												disabled={(types.other.TODAS && key !== 'TODAS') ||
													isExportAdditionalDisabled[
														key as keyof typeof isExportAdditionalDisabled
													]}
												bind:checked={
													types.export.additional[key as keyof typeof types.export.additional]
												}
											/>
											<Label for="exp-add-{key}" class="cursor-pointer text-[10px] font-normal"
												>{key}</Label
											>
										</div>
									{/each}
								</div>
							</div>
						</div>

						<!-- Otras -->
						<div>
							<Label
								class="mb-2 block border-b pb-1 text-xs font-bold text-muted-foreground uppercase"
								>Otras</Label
							>
							<div class="grid grid-cols-1 gap-2 sm:grid-cols-2 xl:grid-cols-3">
								{#each Object.keys(types.other) as key}
									<div class="flex items-center space-x-2">
										<Checkbox
											id="other-{key}"
											class="h-3.5 w-3.5"
											disabled={types.other.TODAS && key !== 'TODAS'}
											bind:checked={types.other[key as keyof typeof types.other]}
											onCheckedChange={(v) => {
												if (key === 'TODAS') handleTodasChange(v as boolean);
											}}
										/>
										<Label for="other-{key}" class="cursor-pointer text-xs font-normal">
											{key === 'CREGEXP' ? 'C. REG. EXP.' : key}
										</Label>
									</div>
								{/each}
							</div>
						</div>
					</div>
				</Card.Content>
			</Card.Root>

			<!-- Columna 2: Filtros e Identificadores -->
			<Card.Root class="flex h-full flex-col">
				<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
					<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
						<Search class="h-4 w-4" /> Filtros e Identificadores
					</Card.Title>
				</Card.Header>
				<Card.Content class="flex-1 space-y-3 p-3">
					<div class="space-y-2">
						{#each [{ label: 'Proveedor', key: 'provider' as const }, { label: 'Vendido a', key: 'soldTo' as const }, { label: 'Clave de Pedimento', key: 'pedimentoKey' as const }] as item}
							<div class="space-y-1">
								<Label class="text-xs font-bold text-muted-foreground uppercase">{item.label}</Label
								>
								<div class="flex items-center gap-2">
									<Input
										bind:value={selectors[item.key]}
										class="h-8 flex-1 text-sm"
										placeholder={`Buscar ${item.label.split('/')[0]}...`}
									/>
									<Button
										variant="outline"
										size="icon"
										class="h-8 w-8 shrink-0"
										onclick={() => openSelectionDialog(item.key)}
									>
										<Folder class="h-4 w-4" />
									</Button>
								</div>
							</div>
						{/each}
					</div>

					<div class="py-1">
						<Separator />
					</div>

					<div class="space-y-2">
						<Label class="text-xs font-bold text-muted-foreground uppercase"
							>Filtros por Partida</Label
						>

						<div
							class="flex items-center space-x-2 rounded-md border bg-muted/10 p-2 transition-colors hover:bg-muted/20"
						>
							<Checkbox id="filter-na" class="h-4 w-4" bind:checked={filters.includeNA} />
							<Label for="filter-na" class="cursor-pointer text-sm font-medium"
								>Incluir Facturas NA</Label
							>
						</div>

						<div class="space-y-1.5 pt-1">
							<RadioGroup.Root bind:value={filters.downloaded} class="flex flex-col gap-1.5">
								<div
									class="flex items-center space-x-3 rounded-md border px-3 py-2 transition-colors hover:bg-muted/50"
								>
									<RadioGroup.Item value="all" id="d1" class="h-4 w-4" />
									<Label for="d1" class="flex-1 cursor-pointer text-sm font-medium"
										>Todas las Partidas</Label
									>
								</div>
								<div
									class="flex items-center space-x-3 rounded-md border px-3 py-2 transition-colors hover:bg-muted/50"
								>
									<RadioGroup.Item value="downloaded" id="d2" class="h-4 w-4" />
									<Label for="d2" class="flex-1 cursor-pointer text-sm font-medium"
										>Solo Descargadas</Label
									>
								</div>
								<div
									class="flex items-center space-x-3 rounded-md border px-3 py-2 transition-colors hover:bg-muted/50"
								>
									<RadioGroup.Item value="not_downloaded" id="d3" class="h-4 w-4" />
									<Label for="d3" class="flex-1 cursor-pointer text-sm font-medium"
										>Solo No Descargadas</Label
									>
								</div>
							</RadioGroup.Root>
						</div>
					</div>
				</Card.Content>
			</Card.Root>

			<!-- Columna 3: Configuración y Acciones -->
			<Card.Root class="flex h-full flex-col">
				<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
					<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
						<Globe class="h-4 w-4" /> Configuración Final
					</Card.Title>
				</Card.Header>
				<Card.Content class="flex-1 space-y-4 p-3">
					<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
						<div class="space-y-1.5">
							<Label class="text-xs font-bold text-muted-foreground uppercase">Tipo de Fecha</Label>
							<RadioGroup.Root bind:value={dates.type} class="flex flex-col gap-1">
								<div
									class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
								>
									<RadioGroup.Item value="invoice" id="dt-inv" class="h-4 w-4" />
									<Label for="dt-inv" class="flex-1 cursor-pointer text-sm font-medium"
										>Factura</Label
									>
								</div>
								<div
									class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
								>
									<RadioGroup.Item value="payment" id="dt-pay" class="h-4 w-4" />
									<Label for="dt-pay" class="flex-1 cursor-pointer text-sm font-medium">Pago</Label>
								</div>
							</RadioGroup.Root>
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-bold text-muted-foreground uppercase">Tipo de Moneda</Label
							>
							<RadioGroup.Root bind:value={config.currency} class="flex flex-col gap-1">
								<div
									class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
								>
									<RadioGroup.Item value="foreign" id="curr-usd" class="h-4 w-4" />
									<Label for="curr-usd" class="flex-1 cursor-pointer text-sm font-medium"
										>Extranjera</Label
									>
								</div>
								<div
									class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
								>
									<RadioGroup.Item value="national" id="curr-mxn" class="h-4 w-4" />
									<Label for="curr-mxn" class="flex-1 cursor-pointer text-sm font-medium"
										>Nacional</Label
									>
								</div>
								<div
									class="flex items-center space-x-2 rounded-md border px-2 py-1.5 transition-colors hover:bg-muted"
								>
									<RadioGroup.Item value="capture" id="curr-cap" class="h-4 w-4" />
									<Label for="curr-cap" class="flex-1 cursor-pointer text-sm font-medium"
										>Captura</Label
									>
								</div>
							</RadioGroup.Root>
						</div>
					</div>

					<div class="py-1">
						<Separator />
					</div>

					<div class="grid grid-cols-1 gap-3 sm:grid-cols-2">
						<div class="space-y-1.5">
							<Label class="text-xs font-bold text-muted-foreground uppercase">Reporte</Label>
							<RadioGroup.Root bind:value={config.reportType} class="flex flex-col gap-1.5">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="normal" id="rt-norm" class="h-4 w-4" />
									<Label for="rt-norm" class="cursor-pointer text-sm font-medium">Normal</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="detailed" id="rt-det" class="h-4 w-4" />
									<Label for="rt-det" class="cursor-pointer text-sm font-medium">Detallado</Label>
								</div>
							</RadioGroup.Root>
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs font-bold text-muted-foreground uppercase">Tipo de Cambio</Label
							>
							<RadioGroup.Root bind:value={config.exchangeRate} class="flex flex-col gap-1.5">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="invoice_date" id="er-inv" class="h-4 w-4" />
									<Label for="er-inv" class="cursor-pointer text-sm font-medium"
										>Fecha Factura</Label
									>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="payment_date" id="er-pay" class="h-4 w-4" />
									<Label for="er-pay" class="cursor-pointer text-sm font-medium">Fecha Pago</Label>
								</div>
							</RadioGroup.Root>
						</div>
					</div>

					<div class="space-y-2 border-t pt-1">
						<Label class="text-xs font-bold text-muted-foreground uppercase"
							>Opciones Avanzadas</Label
						>
						<div class="flex flex-col gap-1.5">
							<div
								class="flex items-center justify-between rounded border p-2 transition-colors hover:bg-muted/10"
							>
								<Label for="opt-email" class="cursor-pointer text-sm"
									>Enviar por Correo Electrónico</Label
								>
								<Checkbox id="opt-email" class="h-4 w-4" bind:checked={config.sendEmail} />
							</div>
							<div
								class="flex items-center justify-between rounded border p-2 transition-colors hover:bg-muted/10"
							>
								<Label for="opt-julian" class="flex-1 cursor-pointer text-sm"
									>Usar Fecha Juliana (Excel)</Label
								>
								<Checkbox id="opt-julian" class="h-4 w-4" bind:checked={config.julianDate} />
							</div>
							<div
								class="flex items-center justify-between rounded border p-2 transition-colors hover:bg-muted/10"
							>
								<Label for="opt-shelter" class="flex-1 cursor-pointer text-sm"
									>Generar Reporte Shelter</Label
								>
								<Checkbox id="opt-shelter" class="h-4 w-4" bind:checked={config.shelter} />
							</div>
						</div>
					</div>
				</Card.Content>
				<Card.Footer class="mt-auto gap-2 border-t bg-muted/10 p-2.5">
					<Button
						class="h-9 flex-1 text-sm shadow-sm"
						size="default"
						onclick={generateReport}
						oncontextmenu={handleContextMenu}
						disabled={loading}
					>
						{#if loading}
							<div
								class="mr-2 h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary-foreground/30 border-t-primary-foreground"
							></div>
							Generando...
						{:else}
							<Printer class="mr-2 h-3.5 w-3.5" />
							Imprimir Reporte
						{/if}
					</Button>
					<Button
						variant="ghost"
						size="icon"
						class="h-9 w-9 text-muted-foreground hover:text-destructive"
						onclick={handleClose}
					>
						<X class="h-4 w-4" />
					</Button>
				</Card.Footer>
			</Card.Root>
		{:else if activeReportType === 'saldos'}
			<!-- SALDOS TEMPORALES -->
			<!-- Columna 1: Periodo y Clasificación -->
			<Card.Root class="flex h-full flex-col">
				<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
					<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
						<Calendar class="h-4 w-4" /> Periodo y Clasificación
					</Card.Title>
				</Card.Header>
				<Card.Content class="flex-1 space-y-4 p-3">
					<!-- Por rango de section -->
					<div class="space-y-2">
						<Label class="text-xs font-bold text-muted-foreground uppercase">Por rango de</Label>
						<div class="grid grid-cols-1 gap-1.5">
							<div class="flex flex-wrap gap-1.5">
								<Button
									variant={saldosRangeType === 'pedimento' ? 'default' : 'outline'}
									size="sm"
									class="h-7 text-[10px] font-bold uppercase transition-all"
									onclick={() => handleSaldosRangeTypeChange('pedimento')}
								>
									Pedimentos
								</Button>
								<Button
									variant={saldosRangeType === 'payment_date' ? 'default' : 'outline'}
									size="sm"
									class="h-7 text-[10px] font-bold uppercase transition-all"
									onclick={() => handleSaldosRangeTypeChange('payment_date')}
								>
									Fecha de pago
								</Button>
								<Button
									variant={saldosRangeType === 'invoice_date' ? 'default' : 'outline'}
									size="sm"
									class="h-7 text-[10px] font-bold uppercase transition-all"
									onclick={() => handleSaldosRangeTypeChange('invoice_date')}
								>
									Fecha de facturas
								</Button>
								<Button
									variant={saldosRangeType === 'parts' ? 'default' : 'outline'}
									size="sm"
									class="h-7 text-[10px] font-bold uppercase transition-all"
									onclick={() => handleSaldosRangeTypeChange('parts')}
								>
									Partes
								</Button>
								<Button
									variant={saldosRangeType === 'classes' ? 'default' : 'outline'}
									size="sm"
									class="h-7 text-[10px] font-bold uppercase transition-all"
									onclick={() => handleSaldosRangeTypeChange('classes')}
								>
									Clases
								</Button>
							</div>
						</div>
					</div>

					<Separator />

					<div class="space-y-3">
						<!-- Identificadores (Pedimentos, Partes, Clases) -->
						{#if saldosRangeType === 'pedimento' || saldosRangeType === 'parts' || saldosRangeType === 'classes'}
							<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
								<div class="flex-1 space-y-1">
									<Label class="text-xs font-bold text-muted-foreground uppercase">
										{saldosRangeType === 'pedimento'
											? 'De'
											: saldosRangeType === 'parts'
												? 'De la parte'
												: 'De la clase'}
									</Label>
									<div class="flex items-center gap-2">
										<Input
											type="text"
											class="h-8 flex-1"
											placeholder={saldosRangeType === 'pedimento'
												? 'Pedimento inicial'
												: saldosRangeType === 'parts'
													? 'Parte inicial'
													: 'Clase inicial'}
											bind:value={saldosIdentifiers.from}
										/>
										<Button
											variant="outline"
											size="icon"
											class="h-8 w-8 shrink-0 transition-colors hover:bg-primary/10 hover:text-primary"
											onclick={() => {
												if (saldosRangeType === 'pedimento') openSelectionDialog('pedimentoFrom');
												else if (saldosRangeType === 'parts') openSelectionDialog('partFrom');
												else if (saldosRangeType === 'classes') openSelectionDialog('classFrom');
											}}
										>
											<Folder class="h-3.5 w-3.5" />
										</Button>
									</div>
								</div>
								<div class="flex-1 space-y-1">
									<Label class="text-xs font-bold text-muted-foreground uppercase">
										{saldosRangeType === 'pedimento'
											? 'Hasta'
											: saldosRangeType === 'parts'
												? 'Hasta la parte'
												: 'Hasta la clase'}
									</Label>
									<div class="flex items-center gap-2">
										<Input
											type="text"
											class="h-8 flex-1"
											placeholder={saldosRangeType === 'pedimento'
												? 'Pedimento final'
												: saldosRangeType === 'parts'
													? 'Parte final'
													: 'Clase final'}
											bind:value={saldosIdentifiers.to}
										/>
										<Button
											variant="outline"
											size="icon"
											class="h-8 w-8 shrink-0 transition-colors hover:bg-primary/10 hover:text-primary"
											onclick={() => {
												if (saldosRangeType === 'pedimento') openSelectionDialog('pedimentoTo');
												else if (saldosRangeType === 'parts') openSelectionDialog('partTo');
												else if (saldosRangeType === 'classes') openSelectionDialog('classTo');
											}}
										>
											<Folder class="h-3.5 w-3.5" />
										</Button>
									</div>
								</div>
							</div>
						{/if}

						<!-- Fechas (Pago, Facturas, o adicional para Partes/Clases) -->
						{#if saldosRangeType === 'payment_date' || saldosRangeType === 'invoice_date' || saldosRangeType === 'parts' || saldosRangeType === 'classes'}
							<div class="flex flex-col gap-3 sm:flex-row sm:items-center">
								<div class="flex-1 space-y-1">
									<Label class="text-xs font-bold text-muted-foreground uppercase">
										{saldosRangeType === 'payment_date' || saldosRangeType === 'invoice_date'
											? 'Desde'
											: 'De la fecha'}
									</Label>
									<Input
										type="date"
										class="h-8 cursor-pointer"
										bind:value={dates.from}
										onclick={(e) => {
											const input = e.currentTarget;
											if (input && typeof input.showPicker === 'function') {
												input.showPicker();
											}
										}}
									/>
								</div>
								<div class="flex-1 space-y-1">
									<Label class="text-xs font-bold text-muted-foreground uppercase">
										{saldosRangeType === 'payment_date' || saldosRangeType === 'invoice_date'
											? 'Hasta'
											: 'Hasta la fecha'}
									</Label>
									<Input
										type="date"
										class="h-8 cursor-pointer"
										bind:value={dates.to}
										onclick={(e) => {
											const input = e.currentTarget;
											if (input && typeof input.showPicker === 'function') {
												input.showPicker();
											}
										}}
									/>
								</div>
							</div>
						{/if}
					</div>
					<Separator class="my-2" />

					<!-- Opciones de Impresión Moved from Column 2 -->
					<div
						class="space-y-2 rounded-md border bg-primary/5 p-3 transition-colors hover:bg-primary/10"
					>
						<Label class="mb-1 flex items-center gap-2 text-xs font-black text-primary uppercase">
							<Printer class="h-4 w-4" /> Opciones de Impresión:
						</Label>
						<div class="flex flex-wrap items-center gap-4">
							<div class="flex items-center space-x-2">
								<Checkbox
									id="s-print-part"
									class="h-4 w-4"
									bind:checked={saldosPrintPart}
									disabled={saldosRangeType === 'parts' || saldosRangeType === 'classes'}
								/>
								<Label
									for="s-print-part"
									class="cursor-pointer text-sm font-bold text-primary uppercase {saldosRangeType ===
										'parts' || saldosRangeType === 'classes'
										? 'opacity-50'
										: ''}">PARTE</Label
								>
							</div>
							<div class="flex items-center space-x-2">
								<Checkbox
									id="s-print-class"
									class="h-4 w-4"
									bind:checked={saldosPrintClass}
									disabled={saldosRangeType === 'classes'}
								/>
								<Label
									for="s-print-class"
									class="cursor-pointer text-sm font-bold text-primary uppercase {saldosRangeType ===
									'classes'
										? 'opacity-50'
										: ''}">CLASE</Label
								>
							</div>
						</div>
					</div>
					<div class="space-y-3 pt-1">
						<Label class="flex items-center gap-2 text-xs font-black text-primary uppercase">
							<Filter class="h-3 w-3" /> Imprimir por catálogo:
						</Label>

						{#each [{ label: 'PARTE/CLASE', key: 'assetClass' as const }, { label: 'ACTIVO FIJO', key: 'assetType' as const }, { label: 'CLAVE PED', key: 'pedimentoKey' as const }, { label: 'CLIENTE', key: 'provider' as const }, { label: 'LOCALIZACION', key: 'location' as const }] as item}
							<div class="space-y-1">
								<Label class="text-[10px] font-bold text-muted-foreground uppercase"
									>{item.label}</Label
								>
								<div class="flex items-center gap-2">
									<Input
										bind:value={selectors[item.key]}
										class="h-8 flex-1 text-xs"
										placeholder={`Seleccionar ${item.label.toLowerCase()}...`}
										disabled={item.key === 'assetClass' && saldosRangeType === 'classes'}
									/>
									<Button
										variant="outline"
										size="icon"
										class="h-8 w-8 shrink-0 transition-colors hover:bg-primary/10 hover:text-primary"
										onclick={() => openSelectionDialog(item.key)}
										disabled={item.key === 'assetClass' && saldosRangeType === 'classes'}
									>
										<Folder class="h-3.5 w-3.5" />
									</Button>
								</div>
							</div>
						{/each}
					</div>
				</Card.Content>
			</Card.Root>

			<!-- Columna 2: Filtros e Identificadores -->
			<Card.Root class="flex h-full flex-col">
				<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
					<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
						<Search class="h-4 w-4" /> Filtros e Identificadores
					</Card.Title>
				</Card.Header>
				<Card.Content class="flex-1 space-y-3 p-3">
					<div class="space-y-4">
						<!-- Tipo moneda -->
						<div class="space-y-1.5">
							<Label class="text-[10px] font-bold text-muted-foreground uppercase"
								>Tipo moneda</Label
							>
							<RadioGroup.Root bind:value={config.currency} class="flex flex-wrap gap-4">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="foreign" id="cur-f" class="h-4 w-4" />
									<Label for="cur-f" class="cursor-pointer text-sm font-medium">Extranjera</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="national" id="cur-n" class="h-4 w-4" />
									<Label for="cur-n" class="cursor-pointer text-sm font-medium">Nacional</Label>
								</div>
							</RadioGroup.Root>
						</div>

						<Separator class="opacity-50" />

						<!-- Seleccionar -->
						<div class="space-y-1.5">
							<Label class="text-[10px] font-bold text-muted-foreground uppercase"
								>Seleccionar</Label
							>
							<RadioGroup.Root bind:value={config.reportType} class="flex flex-col gap-2">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="normal" id="sel-n" class="h-4 w-4" />
									<Label for="sel-n" class="cursor-pointer text-sm font-medium">Normal</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="detailed" id="sel-d" class="h-4 w-4" />
									<Label for="sel-d" class="cursor-pointer text-sm font-medium">Detallando</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="with_download" id="sel-w" class="h-4 w-4" />
									<Label for="sel-w" class="cursor-pointer text-sm font-medium">Con descarga</Label>
								</div>
							</RadioGroup.Root>
						</div>

						<Separator class="opacity-50" />

						<!-- Tipo de cambio -->
						<div class="space-y-1.5">
							<Label class="text-[10px] font-bold text-muted-foreground uppercase"
								>Tipo de cambio</Label
							>
							<RadioGroup.Root bind:value={config.exchangeRate} class="flex flex-col gap-2">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="invoice_date" id="xr-i" class="h-4 w-4" />
									<Label for="xr-i" class="cursor-pointer text-sm font-medium">Factura</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="payment_date" id="xr-p" class="h-4 w-4" />
									<Label for="xr-p" class="cursor-pointer text-sm font-medium"
										>Fecha de pago pedimento</Label
									>
								</div>
							</RadioGroup.Root>
						</div>

						<Separator class="opacity-50" />

						<!-- Omitir cantidades -->
						<div class="space-y-1.5">
							<Label class="text-[10px] font-bold text-muted-foreground uppercase"
								>Omitir cantidades con balance menor a:</Label
							>
							<RadioGroup.Root
								value={filters.omitLowBalance ? 'yes' : 'no'}
								onValueChange={(v) => (filters.omitLowBalance = v === 'yes')}
								class="flex flex-wrap gap-6"
							>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="yes" id="omit-y" class="h-4 w-4" />
									<Label for="omit-y" class="cursor-pointer text-sm font-medium">Si</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="no" id="omit-n" class="h-4 w-4" />
									<Label for="omit-n" class="cursor-pointer text-sm font-medium">No</Label>
								</div>
							</RadioGroup.Root>
						</div>

						<Separator class="opacity-50" />

						<!-- ¿Saldos? -->
						<div class="space-y-1.5">
							<Label class="text-[10px] font-bold text-muted-foreground uppercase">¿Saldos?</Label>
							<RadioGroup.Root bind:value={filters.balanceType} class="flex flex-col gap-2">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="normal" id="bt-n" class="h-4 w-4" />
									<Label for="bt-n" class="cursor-pointer text-sm font-medium">Normales</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="repair" id="bt-r" class="h-4 w-4" />
									<Label for="bt-r" class="cursor-pointer text-sm font-medium">Reparación</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="both" id="bt-b" class="h-4 w-4" />
									<Label for="bt-b" class="cursor-pointer text-sm font-medium">Ambos</Label>
								</div>
							</RadioGroup.Root>
						</div>

						<Separator class="opacity-50" />

						<!-- Tipo (Nivel) -->
						<div class="space-y-1.5">
							<Label class="text-[10px] font-bold text-muted-foreground uppercase">Tipo</Label>
							<RadioGroup.Root bind:value={filters.level} class="flex flex-col gap-2">
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="partida" id="lvl-p" class="h-4 w-4" />
									<Label for="lvl-p" class="cursor-pointer text-sm font-medium">Partida</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="subpartida" id="lvl-s" class="h-4 w-4" />
									<Label for="lvl-s" class="cursor-pointer text-sm font-medium">SubPartida</Label>
								</div>
								<div class="flex items-center space-x-2">
									<RadioGroup.Item value="all" id="lvl-a" class="h-4 w-4" />
									<Label for="lvl-a" class="cursor-pointer text-sm font-medium">Todas</Label>
								</div>
							</RadioGroup.Root>
						</div>
					</div>
				</Card.Content>
			</Card.Root>

			<!-- Columna 3: Configuración y Acciones -->
			<Card.Root class="flex h-full flex-col">
				<Card.Header class="shrink-0 border-b bg-muted/20 px-3 py-2">
					<Card.Title class="flex items-center gap-2 text-sm font-semibold text-primary">
						<Globe class="h-4 w-4" /> Configuración Final
					</Card.Title>
				</Card.Header>
				<Card.Content class="flex-1 space-y-4 p-3">
					<div class="space-y-1.5">
						<Label class="text-[10px] font-bold text-muted-foreground uppercase"
							>Opciones de Reporte</Label
						>
						<div class="flex flex-col gap-1.5">
							{#each reportToggleOptions as opt}
								<div
									class="group flex items-center justify-between gap-3 rounded-lg border bg-card p-2.5 shadow-sm transition-all hover:border-primary/50 hover:bg-primary/5 hover:shadow-md"
								>
									<div class="flex items-center gap-3">
										<div
											class="flex h-8 w-8 items-center justify-center rounded-md bg-primary/10 text-primary transition-colors group-hover:bg-primary group-hover:text-primary-foreground"
										>
											<opt.icon class="h-4 w-4" />
										</div>
										<Label
											for={opt.id}
											class="cursor-pointer text-xs leading-tight font-bold text-foreground transition-colors group-hover:text-primary"
										>
											{opt.label}
										</Label>
									</div>
									<Checkbox
										id={opt.id}
										class="h-4 w-4 border-2 transition-transform active:scale-90"
										bind:checked={config[opt.key]}
									/>
								</div>
							{/each}
						</div>
					</div>
				</Card.Content>
				<Card.Footer class="mt-auto gap-2 border-t bg-muted/10 p-2.5">
					<Button
						class="h-9 flex-1 text-sm shadow-sm"
						size="default"
						onclick={generateSaldosReport}
						disabled={loading}
					>
						{#if loading}
							<div
								class="mr-2 h-3.5 w-3.5 animate-spin rounded-full border-2 border-primary-foreground/30 border-t-primary-foreground"
							></div>
							Procesando...
						{:else}
							<Printer class="mr-2 h-3.5 w-3.5" />
							Imprimir Saldos
						{/if}
					</Button>
					<Button
						variant="ghost"
						size="icon"
						class="h-9 w-9 text-muted-foreground hover:text-destructive"
						onclick={() => (activeReportType = 'invoices')}
					>
						<X class="h-4 w-4" />
					</Button>
				</Card.Footer>
			</Card.Root>
		{:else if activeReportType === 'partes_descargadas'}
			<div class="xl:col-span-2 2xl:col-span-3 h-full">
				<DownloadedPartsForm />
			</div>
		{/if}
	</div>

	<!-- Tabla de Resultados (Dialog Modal) -->
	<Dialog.Root
		open={showResults}
		onOpenChange={(v) => {
			if (!v) showResults = false;
		}}
	>
		<Dialog.Content showCloseButton={false} class="flex h-[90vh] !max-w-[95vw] flex-col gap-0 p-0">
			<Dialog.Header class="shrink-0 border-b bg-muted/40 px-6 py-4">
				<div class="flex items-center justify-between">
					<div>
						<Dialog.Title class="flex items-center gap-2 text-xl">
							<FileText class="h-5 w-5 text-primary" />
							{reportTitle}
						</Dialog.Title>
						<Dialog.Description class="mt-1.5">
							{results.length} registros encontrados • {currencyLabel}
						</Dialog.Description>
					</div>
					<div class="flex gap-2">
						<Button variant="outline" size="sm" onclick={downloadCSV} class="gap-2 shadow-sm">
							<Download class="h-4 w-4" />
							Exportar CSV
						</Button>
						<Dialog.Close
							class="inline-flex h-9 w-9 items-center justify-center rounded-md border border-input bg-background whitespace-nowrap shadow-sm ring-offset-background transition-colors hover:bg-accent hover:bg-muted hover:text-accent-foreground hover:text-muted-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:outline-none disabled:pointer-events-none disabled:opacity-50"
						>
							<X class="h-4 w-4" />
							<span class="sr-only">Cerrar</span>
						</Dialog.Close>
					</div>
				</div>
			</Dialog.Header>

			<div class="flex-1 overflow-auto bg-muted/20 p-4">
				<div class="overflow-hidden rounded-md border bg-card text-card-foreground shadow-sm">
					<table class="w-full border-collapse text-left text-sm">
						<thead
							class="sticky top-0 z-10 border-b border-border bg-muted/80 text-muted-foreground shadow-sm backdrop-blur-sm"
						>
							<tr>
								{#each config.reportType === 'normal' ? ['PEDIMENTO', 'CLAVE', 'FACTURA', 'FECHA FACT', 'VALOR COM.', 'TIPO OPER.', 'ESTATUS', 'PROYECTO'] : ['PEDIMENTO', 'FACTURA', 'FECHA FACT', 'PROVEEDOR', 'CLIENTE', 'CANTIDAD', 'DESC. ESPAÑOL', 'TIPO OPER.'] as header}
									<th
										class="px-4 py-3 text-xs font-semibold tracking-wider whitespace-nowrap uppercase"
									>
										{header}
									</th>
								{/each}
							</tr>
						</thead>
						<tbody class="divide-y divide-border">
							{#each results as row}
								<tr class="bg-card transition-colors hover:bg-muted/50">
									{#if config.reportType === 'normal'}
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-medium text-primary"
											>{row.Pedimento || '-'}</td
										>
										<td class="border-r-dashed border-r border-border/50 px-4 py-2.5"
											>{row.ClavePed || '-'}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-mono whitespace-nowrap"
											>{row.Factura}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-xs text-muted-foreground"
											>{formatDateFromYYYYMMDD(row.FechaFactura)}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-right font-mono"
											>${formatCurrency(row.ValorComercialMN)}</td
										>
										<td class="border-r-dashed border-r border-border/50 px-4 py-2.5">
											<span
												class="rounded-full border border-blue-200 bg-blue-100 px-2 py-0.5 text-[10px] font-bold text-blue-700 dark:border-blue-800 dark:bg-blue-900/30 dark:text-blue-400"
											>
												{row.TipoMovTemDef}
											</span>
										</td>
										<td class="border-r-dashed border-r border-border/50 px-4 py-2.5">
											<span
												class="rounded-full px-2 py-0.5 text-[10px] font-bold {row.Estatus === 'C'
													? 'border border-destructive/20 bg-destructive/10 text-destructive'
													: 'border border-green-200 bg-green-100 text-green-700 dark:border-green-800 dark:bg-green-900/30 dark:text-green-400'}"
											>
												{row.Estatus || 'A'}
											</span>
										</td>
										<td class="px-4 py-2.5 text-xs text-muted-foreground">{row.BaseDeDatos}</td>
									{:else}
										{@const detailRow = row as MovementItemDetailed}
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-medium text-primary"
											>{detailRow.Pedimento || '-'}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 font-mono font-medium whitespace-nowrap"
											>{detailRow.Factura}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-xs text-muted-foreground"
											>{formatDateFromYYYYMMDD(detailRow.FechaFactura)}</td
										>
										<td
											class="border-r-dashed max-w-[150px] truncate border-r border-border/50 px-4 py-2.5 text-xs"
											title={detailRow.Proveedor}>{detailRow.Proveedor || '-'}</td
										>
										<td
											class="border-r-dashed max-w-[150px] truncate border-r border-border/50 px-4 py-2.5 text-xs"
											title={detailRow.VendidoA}>{detailRow.VendidoA || '-'}</td
										>
										<td
											class="border-r-dashed border-r border-border/50 px-4 py-2.5 text-right font-mono"
											>{detailRow.CantidadIE || '0'}</td
										>
										<td
											class="border-r-dashed max-w-[200px] truncate border-r border-border/50 px-4 py-2.5 text-xs"
											title={detailRow.DescripcionE}>{detailRow.DescripcionE || '-'}</td
										>
										<td class="px-4 py-2.5">
											<span
												class="rounded-full border border-purple-200 bg-purple-100 px-2 py-0.5 text-[10px] font-bold text-purple-700 dark:border-purple-800 dark:bg-purple-900/30 dark:text-purple-400"
											>
												{detailRow.TipoMovTemDef}
											</span>
										</td>
									{/if}
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
		</Dialog.Content>
	</Dialog.Root>

<!-- Diálogo de Selección -->
<Dialog.Root bind:open={dialogOpen}>
	<Dialog.Content class="!max-w-[90vw] p-6 sm:!max-w-[90vw]">
		<Dialog.Header>
			<Dialog.Title>
				Seleccionar {dialogType === 'pedimentoKey'
					? 'Clave de Pedimento'
					: dialogType === 'assetClass' || dialogType === 'classFrom' || dialogType === 'classTo'
						? 'Clase'
						: dialogType === 'assetType'
							? 'Tipo de Activo'
							: dialogType === 'location'
								? 'Localización'
								: dialogType === 'provider'
									? 'Proveedor'
									: dialogType === 'soldTo'
										? 'Cliente'
										: dialogType?.startsWith('pedimento')
											? 'Pedimento'
											: 'Parte'}
			</Dialog.Title>
			<Dialog.Description>
				Busca y selecciona {dialogType === 'pedimentoKey'
					? 'una clave de pedimento'
					: dialogType === 'assetClass' || dialogType === 'classFrom' || dialogType === 'classTo'
						? 'una clase'
						: dialogType === 'assetType'
							? 'un tipo de activo'
							: dialogType === 'location'
								? 'una localización'
								: dialogType === 'provider'
									? 'un proveedor'
									: dialogType === 'soldTo'
										? 'un cliente'
										: dialogType?.startsWith('pedimento')
											? 'un pedimento'
											: 'una parte'} de la lista
			</Dialog.Description>
		</Dialog.Header>

		<div class="mt-4">
			<div class="mb-3 flex items-center gap-2">
				<Search class="h-4 w-4 text-muted-foreground" />
				<Input
					bind:value={dialogSearch}
					placeholder={dialogType === 'pedimentoKey' ||
					dialogType === 'assetClass' ||
					dialogType === 'classFrom' ||
					dialogType === 'classTo' ||
					dialogType === 'assetType' ||
					dialogType === 'location' ||
					dialogType?.startsWith('pedimento') ||
					dialogType?.startsWith('part')
						? 'Buscar por código o descripción...'
						: 'Buscar por nombre, RFC, calle, ciudad...'}
					class="flex-1"
				/>
			</div>

			<div class="max-h-[55vh] overflow-x-auto rounded-lg border">
				{#if dialogType === 'pedimentoKey' || dialogType === 'assetClass' || dialogType === 'classFrom' || dialogType === 'classTo' || dialogType === 'assetType' || dialogType === 'location' || dialogType?.startsWith('pedimento') || dialogType?.startsWith('part')}
					<table class="w-full text-sm">
						<thead class="bg-muted">
							<tr>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Código</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Descripción</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-center font-semibold whitespace-nowrap"
									>Acción</th
								>
							</tr>
						</thead>
						<tbody>
							{#if filteredItems.length === 0}
								<tr>
									<td colspan="3" class="px-4 py-8 text-center text-muted-foreground">
										No se encontraron resultados
									</td>
								</tr>
							{:else}
								{#each filteredItems as item}
									<tr
										class="cursor-pointer border-b transition-colors hover:bg-muted/50"
										onclick={() => selectItem(item)}
									>
										<td class="px-3 py-2.5 font-medium">
											{dialogType === 'pedimentoKey'
												? item.code || '-'
												: dialogType === 'assetClass' ||
													  dialogType === 'classFrom' ||
													  dialogType === 'classTo'
													? item.class_code || '-'
													: dialogType === 'assetType'
														? item.key || '-'
														: dialogType === 'location'
															? item.location_code || '-'
															: dialogType?.startsWith('pedimento')
																? item.pedimento_number || '-'
																: item.part_number || '-'}
										</td>
										<td class="px-3 py-2.5">
											{dialogType === 'pedimentoKey'
												? item.description || '-'
												: dialogType === 'assetClass' ||
													  dialogType === 'classFrom' ||
													  dialogType === 'classTo'
													? item.description_es || '-'
													: dialogType === 'assetType'
														? item.description || '-'
														: dialogType === 'location'
															? item.location_description || '-'
															: dialogType?.startsWith('pedimento')
																? `Aduana: ${item.customs_office} - Pat.: ${item.license}`
																: item.description_spanish || '-'}
										</td>
										<td class="px-3 py-2.5 text-center">
											<Button size="sm" variant="ghost" class="h-8">Seleccionar</Button>
										</td>
									</tr>
								{/each}
							{/if}
						</tbody>
					</table>
				{:else}
					<table class="w-full text-sm">
						<thead class="bg-muted">
							<tr>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Clave</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Nombre</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Tipo</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>RFC</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Calles</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Núm. Ext</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>CP</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Colonia</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-left font-semibold whitespace-nowrap"
									>Ciudad</th
								>
								<th
									class="sticky top-0 bg-muted px-3 py-2 text-center font-semibold whitespace-nowrap"
									>Acción</th
								>
							</tr>
						</thead>
						<tbody>
							{#if filteredItems.length === 0}
								<tr>
									<td colspan="10" class="px-4 py-8 text-center text-muted-foreground">
										No se encontraron resultados
									</td>
								</tr>
							{:else}
								{#each filteredItems as item}
									<tr
										class="cursor-pointer border-b transition-colors hover:bg-muted/50"
										onclick={() => selectItem(item)}
									>
										<td class="px-3 py-2.5 text-muted-foreground">{item.id || '-'}</td>
										<td class="px-3 py-2.5 font-medium whitespace-nowrap">{item.name || '-'}</td>
										<td class="px-3 py-2.5 text-center">
											<span
												class="inline-flex h-7 w-7 items-center justify-center rounded-full text-xs font-semibold {item.client_or_provider ===
												'provider'
													? 'bg-purple-100 text-purple-700'
													: item.client_or_provider === 'client'
														? 'bg-blue-100 text-blue-700'
														: 'bg-green-100 text-green-700'}"
											>
												{item.client_or_provider === 'provider'
													? 'P'
													: item.client_or_provider === 'client'
														? 'C'
														: 'A'}
											</span>
										</td>
										<td class="px-3 py-2.5 whitespace-nowrap">{item.rfc || '-'}</td>
										<td class="px-3 py-2.5 whitespace-nowrap">{item.address?.streets || '-'}</td>
										<td class="px-3 py-2.5 text-center whitespace-nowrap"
											>{item.address?.exterior_number || '-'}</td
										>
										<td class="px-3 py-2.5 text-center whitespace-nowrap"
											>{item.address?.postal_code || '-'}</td
										>
										<td class="px-3 py-2.5 whitespace-nowrap"
											>{item.address?.neighborhood || '-'}</td
										>
										<td class="px-3 py-2.5 whitespace-nowrap">{item.address?.city || '-'}</td>
										<td class="px-3 py-2.5 text-center whitespace-nowrap">
											<Button size="sm" variant="ghost" class="h-8">Seleccionar</Button>
										</td>
									</tr>
								{/each}
							{/if}
						</tbody>
					</table>
				{/if}
			</div>
		</div>

		<Dialog.Footer class="mt-4">
			<Button variant="outline" onclick={() => (dialogOpen = false)}>Cancelar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Manual Context Menu -->
{#if contextMenu.open}
	<div
		class="animate-in fade-in-80 fixed z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md"
		style="top: {contextMenu.y}px; left: {contextMenu.x}px;"
	>
		<button
			class="relative flex w-full cursor-default items-center rounded-sm px-2 py-1.5 text-sm outline-none select-none hover:bg-accent hover:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50"
			onclick={(e) => {
				e.preventDefault();
				e.stopPropagation();
				previewReport();
			}}
		>
			<Eye class="mr-2 h-4 w-4" />
			Ver vista previa
		</button>
	</div>
{/if}

	{/if}
</div>

<PdfProgressDialog
	bind:open={showProgressDialog}
	taskId={currentTaskId}
	getStatus={currentStatusFunction}
	onComplete={onCsvComplete}
	onClose={closeProgressDialog}
	title="Generando Reporte de Saldos Temporales"
/>
