<script lang="ts">
	import { page } from '$app/stores';
	import { Button } from '$lib/components/ui/button';
	import * as Tabs from '$lib/components/ui/tabs';
	import * as Card from '$lib/components/ui/card';
	import { Separator } from '$lib/components/ui/separator';
	import { 
		ArrowLeft, 
		Save, 
		Package, 
		FileText,
		FileCode,
		Plus,
		Trash2,
		Search,
		Layers,
		Info,
		Edit2,
		Folder,
		X,
		Settings2,
		ShieldCheck,
		UserCircle2,
		Container,
		Navigation,
		FlaskConical,
		Boxes,
		Calendar,
		Users
	} from 'lucide-svelte';
	import { onMount } from 'svelte';
	import { partsApi, type Part } from '$lib/api/dashboard/a76/parts';
	import { clientsProvidersApi, type ClientProvider } from '$lib/api/dashboard/a76/clients-providers';
	import { companyStore } from '$lib/stores/company.svelte';
	import { toast } from 'svelte-sonner';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Switch } from '$lib/components/ui/switch';
	import * as Table from '$lib/components/ui/table';
	import { Badge } from '$lib/components/ui/badge';
	import * as Dialog from "$lib/components/ui/dialog";
	import PartSelector from '$lib/components/dashboard/goods/parts/PartSelector.svelte';
	import LicenseExceptionSelector from '$lib/components/dashboard/goods/parts/LicenseExceptionSelector.svelte';
	import AgencyTariffCodeSelector from '$lib/components/dashboard/goods/parts/AgencyTariffCodeSelector.svelte';
	import IdentifierSelector from '$lib/components/dashboard/goods/parts/IdentifierSelector.svelte';
	import CartaPorteSelector from '$lib/components/dashboard/goods/parts/CartaPorteSelector.svelte';
	import ClientSelectorDialog from '$lib/components/dashboard/goods/modales/client-selector-dialog.svelte';
	import { aphisCatalogApi, type AphisCatalogRecord } from '$lib/api/dashboard/a76/aphis-catalog';

	const idParam = $page.params.id;
	const isNew = $derived(idParam === 'new');
	const id = $derived(isNew ? null : Number(idParam));
	let part = $state<Part | null>(null);
	let loading = $state(true);
	let activeTab = $state('catalogo');
	
	// Catálogo de clientes
	let clients = $state<ClientProvider[]>([]);
	let isClientSearchOpen = $state(false);

	// Catálogo global de APHIS (independiente de las partes)
	let aphisCatalogRecords = $state<AphisCatalogRecord[]>([]);

	// Estado del formulario de extensión
	let formData = $state({
		// Fila 1
		part_number: '',
		part_type: '',
		// Fila 2
		license_code: '',
		eccn: '',
		dta: '',
		dtb: '',
		// Fila 3
		export_code: '',
		exclusion_symbol: '',
		dtg: '',
		// Fila 4
		width: '',
		thickness: '',
		specification: '',
		// Fila 5 (Tabla y USMCA)
		client_part_names: [] as { part_number: string, client_id: string, client_name: string, part_name: string }[],
		nafta_result: 'NO_APLICA',
		nafta_percentage: 0,
		// Fila 6
		reference_number: '',
		// Fila 7 (Campos informativos simulados)
		agency_code_definition: '',
		agency_info: {
			code: 'ADU',
			required: 'Required',
			program: 'A76-A24',
			definition: 'Agency definition details...'
		},
		// Fila 8
		description_spanish: '',
		// Fila 9
		part_identifiers: [] as any[],
		// Fila 10
		carta_porte: '',
		// Fila 11
		use_rule_8: false,
		// Sustitutos (Pestaña Continuación)
		substitute_parts: [] as { substitute_part_number: string }[],
		// Aphis - solo los dos inputs de referencia
		aphis_data: {
			input1: '',
			input2: ''
		}
	});

	// Estado del diálogo de clientes
	let isClientDialogOpen = $state(false);
	let editingClientIndex = $state<number | null>(null);
	let clientFormData = $state({
		part_number: '',
		client_id: '',
		client_name: '',
		part_name: ''
	});

	// Estado del diálogo de sustitutos
	let isSubstituteDialogOpen = $state(false);
	let editingSubstituteIndex = $state<number | null>(null);
	let substituteFormData = $state({
		substitute_part_number: ''
	});

	// Estado de APHIS
	let isAphisDialogOpen = $state(false);
	let isAphisDetailDialogOpen = $state(false);
	let editingAphisIndex = $state<number | null>(null);
	let aphisActiveDetailTab = $state('general');

	let aphisFormData = $state({
		general: { 
			program_code: '', 
			processing_code: '', 
			aphis_type: '', 
			disclaimer: '', 
			electronic_image: '', 
			confidential: '', 
			global_product_id: '',
			intended_use_code: '',
			intended_use_description: '',
			item_type: '',
			product_code: '',
			product_code_2: '',
			product_code_3: '',
			scientific_genus_name: '',
			scientific_species_name: '',
			scientific_sub_species_name: '',
			common_name_specific: '',
			common_name_general: '',
			signed_doc: '',
			signed_doc_date: '',
			signed_doc_id: '',
			invoice_number: '',
			quantity_1: '',
			quantity_2: '',
			quantity_3: '',
			inspection: '',
			inspection_date: '',
			inspection_loc_date: '',
			inspection_location: '',
			country_production: '',
			country_source: ''
		},
		characteristics: [] as any[],
		stype_pitems: [] as any[],
		lpcos: [] as any[],
		entities: [] as any[],
		containers: [] as any[],
		routing: [] as any[]
	});

	// Estado para Diálogo de Characteristic
	let isAphisCharacteristicDialogOpen = $state(false);
	let editingAphisCharacteristicIndex = $state<number | null>(null);
	let aphisCharacteristicFormData = $state({
		item_id: '', number_from: '', number_to: '', category_type: '',
		commodity_qua: '', commodity_char_qua: '', description: '', category_code: ''
	});

	// Estado para Diálogo de Stype Pitems
	let isAphisStypeDialogOpen = $state(false);
	let editingAphisStypeIndex = $state<number | null>(null);
	let aphisStypeFormData = $state({
		source_type_code: '', country_code: '', geo_location: '',
		processing_start: '', processing_end: '', processing_type: '', processing_desc: ''
	});

	// Estado para Diálogo de LPCO
	let isAphisLpcoDialogOpen = $state(false);
	let editingAphisLpcoIndex = $state<number | null>(null);
	let aphisLpcoFormData = $state({
		issuer: '', issuer_loc_qua: '', issuer_loc: '', issuer_loc_desc: '',
		uom: '', txn_type: '', type: '', number: '',
		date_qual: '', date: '', qty: ''
	});

	// Estado para Diálogo de Entities
	let isAphisEntitiesDialogOpen = $state(false);
	let editingAphisEntitiesIndex = $state<number | null>(null);
	let aphisEntitiesFormData = $state({
		consignee_key: '', broker_key: '', 
		lpco_auth_party_key: '', grower_key: ''
	});

	// Estado para Diálogo de Containers
	let isAphisContainersDialogOpen = $state(false);
	let editingAphisContainersIndex = $state<number | null>(null);
	let aphisContainersFormData = $state({
		container_number: '', length: '', type: ''
	});

	// Estado para Diálogo de Routing
	let isAphisRoutingDialogOpen = $state(false);
	let editingAphisRoutingIndex = $state<number | null>(null);
	let aphisRoutingFormData = $state({
		type: '', country: '', name: ''
	});

	// Estado del selector de partes (catálogo)
	let isPartSelectorOpen = $state(false);

	// Estados para nuevos selectores de catálogos fijos
	let isLicenseSelectorOpen = $state(false);
	let isAgencySelectorOpen = $state(false);
	let isIdentifierSelectorOpen = $state(false);
	let isCartaPorteSelectorOpen = $state(false);

	// Manejadores de selección
	function handleLicenseSelect(item: any) {
		formData.exclusion_symbol = item.key;
		isLicenseSelectorOpen = false;
		toast.success(`Símbolo seleccionado: ${item.key}`);
	}

	function handleAgencySelect(item: any) {
		formData.agency_code_definition = item.definition;
		formData.agency_info = {
			code: item.agency_code,
			required: item.requirement_level === 'R' ? 'Required' : 'Maybe Required',
			program: item.program_code,
			definition: item.definition
		};
		isAgencySelectorOpen = false;
		toast.success(`Agencia seleccionada: ${item.agency_code}`);
	}

	function handleIdentifierSelect(item: any) {
		// Guardamos como un objeto simple (el usuario dijo "nada más es uno")
		formData.part_identifiers = [{
			clave: item.key,
			descripcion: item.description,
			nivel: item.level,
			complemento: item.complement || ''
		}];
		isIdentifierSelectorOpen = false;
		toast.success(`Identificador seleccionado: ${item.key}`);
	}

	function handleCartaPorteSelect(item: any) {
		formData.carta_porte = item.code;
		isCartaPorteSelectorOpen = false;
		toast.success(`Carta Porte seleccionada: ${item.code}`);
	}

	function clearIdentifier() {
		formData.part_identifiers = [];
		toast.info('Identificador removido');
	}

	async function loadPart() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		loading = true;
		try {
			// Cargar catálogo de clientes y catálogo global APHIS en paralelo
			const [clientsRes, aphisRes] = await Promise.all([
				clientsProvidersApi.list(companyId, 1, 1000),
				aphisCatalogApi.list(companyId)
			]);
			clients = clientsRes.data?.items || [];
			aphisCatalogRecords = (aphisRes as any).data || [];

			if (isNew) {
				loading = false;
				return;
			}

			if (!id) return;

			const res = await partsApi.get(id, companyId);
			if (res.data) {
				part = res.data;
				// Mapear datos al formData
				formData.part_number = part.part_number || '';
				formData.description_spanish = part.description_spanish || '';
				formData.license_code = part.license_code || '';
				formData.eccn = part.eccn || '';
				formData.export_code = part.export_code || '';
				formData.exclusion_symbol = part.exclusion_symbol || '';

				if (part.inv_data) {
					formData.part_type = part.inv_data.part_type || '';
					formData.dta = part.inv_data.dta || '';
					formData.dtb = part.inv_data.dtb || '';
					formData.dtg = part.inv_data.dtg || '';
					formData.width = part.inv_data.width || '';
					formData.thickness = part.inv_data.thickness || '';
					formData.specification = part.inv_data.specification || '';
					formData.reference_number = part.inv_data.reference_number || '';
					formData.nafta_result = part.inv_data.nafta_result || 'NO_APLICA';
					formData.nafta_percentage = Number(part.inv_data.nafta_percentage) || 0;
					formData.use_rule_8 = !!part.inv_data.use_rule_8;
					formData.agency_code_definition = (part.inv_data as any).agency_code_definition || '';
					formData.carta_porte = (part.inv_data as any).carta_porte || '';
					
					// Mapear client_part_names
					let rawClientParts = (part.inv_data as any).client_part_names || [];
					formData.client_part_names = rawClientParts.map((cp: any) => {
						const client = clients.find(c => c.id.toString() === cp.client_id.toString());
						return {
							...cp,
							client_name: client ? client.name : (cp.client_name || 'Desconocido')
						};
					});

					formData.part_identifiers = (part.inv_data as any).part_identifiers || [];
					formData.substitute_parts = (part.inv_data as any).substitute_parts || [];
					const aphisStored = (part.inv_data as any).aphis_data || {};
					formData.aphis_data = { input1: aphisStored.input1 || '', input2: aphisStored.input2 || '' };
				}
			}
		} catch (e) {
			console.error('Error cargando datos:', e);
			toast.error('Error al cargar la información');
		} finally {
			loading = false;
		}
	}

	onMount(() => {
		loadPart();
	});

	async function handleSave() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		if (isNew) {
			toast.error('Debe crear la parte en el formulario principal antes de guardar extensiones.');
			return;
		}

		try {
			loading = true;
			const updateData = {
				part_number: formData.part_number,
				description_spanish: formData.description_spanish,
				license_code: formData.license_code,
				eccn: formData.eccn,
				export_code: formData.export_code,
				exclusion_symbol: formData.exclusion_symbol,
				inv_data: {
					part_type: formData.part_type,
					dta: formData.dta,
					dtb: formData.dtb,
					dtg: formData.dtg,
					width: formData.width,
					thickness: formData.thickness,
					specification: formData.specification,
					reference_number: formData.reference_number,
					nafta_result: formData.nafta_result,
					nafta_percentage: formData.nafta_percentage,
					use_rule_8: formData.use_rule_8,
					agency_code_definition: formData.agency_code_definition,
					carta_porte: formData.carta_porte,
					client_part_names: formData.client_part_names,
					part_identifiers: formData.part_identifiers,
					substitute_parts: formData.substitute_parts,
					// Guardamos solo los dos inputs de referencia APHIS (el catálogo es independiente)
					aphis_data: formData.aphis_data
				}
			};

			await partsApi.update(id!, updateData as any, companyId);
			toast.success('Cambios guardados correctamente');
		} catch (e) {
			console.error('Error guardando:', e);
			toast.error('Error al guardar los cambios');
		} finally {
			loading = false;
		}
	}

	// Gestión del Diálogo de Clientes
	function openClientAdd() {
		editingClientIndex = null;
		clientFormData = {
			part_number: formData.part_number || '',
			client_id: '',
			client_name: '',
			part_name: ''
		};
		isClientDialogOpen = true;
	}

	function openClientEdit(index: number) {
		editingClientIndex = index;
		const row = formData.client_part_names[index];
		clientFormData = {
			part_number: row.part_number || '',
			client_id: row.client_id.toString(),
			client_name: row.client_name || '',
			part_name: row.part_name || ''
		};
		isClientDialogOpen = true;
	}

	function saveClientRow() {
		if (!clientFormData.client_id) {
			toast.error('Debe seleccionar un cliente.');
			return;
		}

		const selectedClient = clients.find(c => c.id.toString() === clientFormData.client_id);
		const newRow: { part_number: string, client_id: string, client_name: string, part_name: string } = {
			part_number: clientFormData.part_number,
			client_id: clientFormData.client_id,
			client_name: clientFormData.client_name,
			part_name: clientFormData.part_name
		};

		if (editingClientIndex !== null) {
			formData.client_part_names[editingClientIndex] = newRow;
		} else {
			formData.client_part_names = [...formData.client_part_names, newRow];
		}

		isClientDialogOpen = false;
		toast.success(editingClientIndex !== null ? 'Registro actualizado' : 'Registro agregado');
	}

	function handleClientSelect(client: ClientProvider) {
		clientFormData.client_id = client.id.toString();
		clientFormData.client_name = client.name;
		isClientSearchOpen = false;
	}

	function handleClientClear() {
		clientFormData.client_id = '';
		clientFormData.client_name = '';
	}

	function removeClientRow(index: number) {
		formData.client_part_names = formData.client_part_names.filter((_, i) => i !== index);
		toast.info('Registro eliminado');
	}

	// Gestión del Diálogo de Sustitutos
	function openSubstituteAdd() {
		editingSubstituteIndex = null;
		substituteFormData = { substitute_part_number: '' };
		isSubstituteDialogOpen = true;
	}

	function openSubstituteEdit(index: number) {
		editingSubstituteIndex = index;
		substituteFormData = { 
			substitute_part_number: formData.substitute_parts[index].substitute_part_number 
		};
		isSubstituteDialogOpen = true;
	}

	function handlePartSelect(p: Part) {
		substituteFormData.substitute_part_number = p.part_number;
		isPartSelectorOpen = false;
		toast.success(`Parte seleccionada: ${p.part_number}`);
	}

	function saveSubstituteRow() {
		if (!substituteFormData.substitute_part_number) {
			toast.error('Debe ingresar un número de parte sustituto.');
			return;
		}

		const newRow = { substitute_part_number: substituteFormData.substitute_part_number };

		if (editingSubstituteIndex !== null) {
			formData.substitute_parts[editingSubstituteIndex] = newRow;
		} else {
			formData.substitute_parts = [...formData.substitute_parts, newRow];
		}

		isSubstituteDialogOpen = false;
		toast.success(editingSubstituteIndex !== null ? 'Sustituto actualizado' : 'Sustituto agregado');
	}

	function removeSubstituteRow(index: number) {
		formData.substitute_parts = formData.substitute_parts.filter((_, i) => i !== index);
		toast.info('Sustituto eliminado');
	}

	// Gestión de APHIS
	function openAphisAdd() {
		editingAphisIndex = null;
		aphisFormData = {
			general: { 
				program_code: '', processing_code: '', aphis_type: '', disclaimer: '', electronic_image: '', confidential: '', global_product_id: '',
				intended_use_code: '', intended_use_description: '', item_type: '', product_code: '', product_code_2: '', product_code_3: '',
				scientific_genus_name: '', scientific_species_name: '', scientific_sub_species_name: '', common_name_specific: '', common_name_general: '',
				signed_doc: '', signed_doc_date: '', signed_doc_id: '', invoice_number: '', quantity_1: '', quantity_2: '', quantity_3: '',
				inspection: '', inspection_date: '', inspection_loc_date: '', inspection_location: '', country_production: '', country_source: ''
			},
			characteristics: [],
			stype_pitems: [],
			lpcos: [],
			entities: [],
			containers: [],
			routing: []
		};
		aphisActiveDetailTab = 'general';
		isAphisDetailDialogOpen = true;
	}

	function openAphisEdit(index: number) {
		editingAphisIndex = index;
		const row = aphisCatalogRecords[index];
		aphisFormData = {
			general: { 
				program_code: row.program_code || '', 
				processing_code: row.processing_code || '', 
				aphis_type: row.aphis_type || '', 
				disclaimer: row.disclaimer || '', 
				electronic_image: row.electronic_image || '', 
				confidential: row.confidential || '', 
				global_product_id: row.global_product_id || '',
				intended_use_code: row.intended_use_code || '',
				intended_use_description: row.intended_use_description || '',
				item_type: row.item_type || '',
				product_code: row.product_code || '',
				product_code_2: row.product_code_2 || '',
				product_code_3: row.product_code_3 || '',
				scientific_genus_name: row.scientific_genus_name || '',
				scientific_species_name: row.scientific_species_name || '',
				scientific_sub_species_name: row.scientific_sub_species_name || '',
				common_name_specific: row.common_name_specific || '',
				common_name_general: row.common_name_general || '',
				signed_doc: row.signed_doc || '',
				signed_doc_date: row.signed_doc_date || '',
				signed_doc_id: row.signed_doc_id || '',
				invoice_number: row.invoice_number || '',
				quantity_1: row.quantity_1 || '',
				quantity_2: row.quantity_2 || '',
				quantity_3: row.quantity_3 || '',
				inspection: row.inspection || '',
				inspection_date: row.inspection_date || '',
				inspection_loc_date: row.inspection_loc_date || '',
				inspection_location: row.inspection_location || '',
				country_production: row.country_production || '',
				country_source: row.country_source || ''
			},
			characteristics: row.characteristics || [],
			stype_pitems: row.pitems || [],
			lpcos: row.lpcos || [],
			entities: row.entities || [],
			containers: row.containers || [],
			routing: row.routing || []
		};
		aphisActiveDetailTab = 'general';
		isAphisDetailDialogOpen = true;
	}

	async function saveAphisDetail() {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;

		// Consolidar todos los datos (General + 6 pestañas de detalle)
		const payload: any = { 
			...aphisFormData.general,
			characteristics: aphisFormData.characteristics,
			pitems: aphisFormData.stype_pitems,
			lpcos: aphisFormData.lpcos,
			entities: aphisFormData.entities,
			containers: aphisFormData.containers,
			routing: aphisFormData.routing
		};

		// Limpiar campos vacíos (convertir "" a null para evitar errores de validación en el backend)
		Object.keys(payload).forEach(key => {
			if (payload[key] === "") payload[key] = null;
		});

		try {
			if (editingAphisIndex !== null) {
				const existingId = aphisCatalogRecords[editingAphisIndex].id;
				await aphisCatalogApi.update(existingId!, payload, companyId);
			} else {
				await aphisCatalogApi.create(payload, companyId);
			}
			// Recargar el catálogo completo para reflejar los datos reales del backend
			const reloaded = await aphisCatalogApi.list(companyId);
			aphisCatalogRecords = (reloaded as any).data || reloaded || [];
			isAphisDetailDialogOpen = false;
			toast.success(editingAphisIndex !== null ? 'Registro Aphis actualizado' : 'Registro Aphis agregado');
		} catch (e) {
			console.error('Error guardando APHIS:', e);
			toast.error('Error al guardar el registro Aphis');
		}
	}


	async function removeAphisRow(index: number) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		const record = aphisCatalogRecords[index];
		try {
			if (record.id) await aphisCatalogApi.delete(record.id, companyId);
			aphisCatalogRecords = aphisCatalogRecords.filter((_: AphisCatalogRecord, i: number) => i !== index);
			toast.info('Registro Aphis eliminado');
		} catch (e) {
			console.error('Error eliminando APHIS:', e);
			toast.error('Error al eliminar el registro');
		}
	}

	// --- Funciones para Aphis Characteristic ---
	function openAphisCharacteristicAdd() {
		editingAphisCharacteristicIndex = null;
		aphisCharacteristicFormData = {
			item_id: '', number_from: '', number_to: '', category_type: '',
			commodity_qua: '', commodity_char_qua: '', description: '', category_code: ''
		};
		isAphisCharacteristicDialogOpen = true;
	}

	function openAphisCharacteristicEdit(index: number) {
		editingAphisCharacteristicIndex = index;
		aphisCharacteristicFormData = { ...aphisFormData.characteristics[index] };
		isAphisCharacteristicDialogOpen = true;
	}

	function saveAphisCharacteristicRow() {
		if (editingAphisCharacteristicIndex !== null) {
			aphisFormData.characteristics[editingAphisCharacteristicIndex] = { ...aphisCharacteristicFormData };
		} else {
			aphisFormData.characteristics = [...aphisFormData.characteristics, { ...aphisCharacteristicFormData }];
		}
		isAphisCharacteristicDialogOpen = false;
		toast.success(editingAphisCharacteristicIndex !== null ? 'Característica actualizada' : 'Característica agregada');
	}

	function removeAphisCharacteristicRow(index: number) {
		aphisFormData.characteristics = aphisFormData.characteristics.filter((_, i) => i !== index);
		toast.info('Característica eliminada');
	}

	// --- Funciones para Aphis Stype Pitems ---
	function openAphisStypeAdd() {
		editingAphisStypeIndex = null;
		aphisStypeFormData = {
			source_type_code: '', country_code: '', geo_location: '',
			processing_start: '', processing_end: '', processing_type: '', processing_desc: ''
		};
		isAphisStypeDialogOpen = true;
	}

	function openAphisStypeEdit(index: number) {
		editingAphisStypeIndex = index;
		aphisStypeFormData = { ...aphisFormData.stype_pitems[index] };
		isAphisStypeDialogOpen = true;
	}

	function saveAphisStypeRow() {
		if (editingAphisStypeIndex !== null) {
			aphisFormData.stype_pitems[editingAphisStypeIndex] = { ...aphisStypeFormData };
		} else {
			aphisFormData.stype_pitems = [...aphisFormData.stype_pitems, { ...aphisStypeFormData }];
		}
		isAphisStypeDialogOpen = false;
		toast.success(editingAphisStypeIndex !== null ? 'Registro Stype actualizado' : 'Registro Stype agregado');
	}

	function removeAphisStypeRow(index: number) {
		aphisFormData.stype_pitems = aphisFormData.stype_pitems.filter((_, i) => i !== index);
		toast.info('Registro Stype eliminado');
	}

	// --- Funciones para Aphis LPCO ---
	function openAphisLpcoAdd() {
		editingAphisLpcoIndex = null;
		aphisLpcoFormData = {
			issuer: '', issuer_loc_qua: '', issuer_loc: '', issuer_loc_desc: '',
			uom: '', txn_type: '', type: '', number: '',
			date_qual: '', date: '', qty: ''
		};
		isAphisLpcoDialogOpen = true;
	}

	function openAphisLpcoEdit(index: number) {
		editingAphisLpcoIndex = index;
		aphisLpcoFormData = { ...aphisFormData.lpcos[index] };
		isAphisLpcoDialogOpen = true;
	}

	function saveAphisLpcoRow() {
		if (editingAphisLpcoIndex !== null) {
			aphisFormData.lpcos[editingAphisLpcoIndex] = { ...aphisLpcoFormData };
		} else {
			aphisFormData.lpcos = [...aphisFormData.lpcos, { ...aphisLpcoFormData }];
		}
		isAphisLpcoDialogOpen = false;
		toast.success(editingAphisLpcoIndex !== null ? 'LPCO actualizado' : 'LPCO agregado');
	}

	function removeAphisLpcoRow(index: number) {
		aphisFormData.lpcos = aphisFormData.lpcos.filter((_, i) => i !== index);
		toast.info('LPCO eliminado');
	}

	// --- Funciones para Aphis Entities ---
	function openAphisEntitiesAdd() {
		editingAphisEntitiesIndex = null;
		aphisEntitiesFormData = {
			consignee_key: '', broker_key: '', 
			lpco_auth_party_key: '', grower_key: ''
		};
		isAphisEntitiesDialogOpen = true;
	}

	function openAphisEntitiesEdit(index: number) {
		editingAphisEntitiesIndex = index;
		aphisEntitiesFormData = { ...aphisFormData.entities[index] };
		isAphisEntitiesDialogOpen = true;
	}

	function saveAphisEntitiesRow() {
		if (editingAphisEntitiesIndex !== null) {
			aphisFormData.entities[editingAphisEntitiesIndex] = { ...aphisEntitiesFormData };
		} else {
			aphisFormData.entities = [...aphisFormData.entities, { ...aphisEntitiesFormData }];
		}
		isAphisEntitiesDialogOpen = false;
		toast.success(editingAphisEntitiesIndex !== null ? 'Entidad actualizada' : 'Entidad agregada');
	}

	function removeAphisEntitiesRow(index: number) {
		aphisFormData.entities = aphisFormData.entities.filter((_, i) => i !== index);
		toast.info('Entidad eliminada');
	}

	// --- Funciones para Aphis Containers ---
	function openAphisContainersAdd() {
		editingAphisContainersIndex = null;
		aphisContainersFormData = { container_number: '', length: '', type: '' };
		isAphisContainersDialogOpen = true;
	}

	function openAphisContainersEdit(index: number) {
		editingAphisContainersIndex = index;
		aphisContainersFormData = { ...aphisFormData.containers[index] };
		isAphisContainersDialogOpen = true;
	}

	function saveAphisContainersRow() {
		if (editingAphisContainersIndex !== null) {
			aphisFormData.containers[editingAphisContainersIndex] = { ...aphisContainersFormData };
		} else {
			aphisFormData.containers = [...aphisFormData.containers, { ...aphisContainersFormData }];
		}
		isAphisContainersDialogOpen = false;
		toast.success(editingAphisContainersIndex !== null ? 'Contenedor actualizado' : 'Contenedor agregado');
	}

	function removeAphisContainersRow(index: number) {
		aphisFormData.containers = aphisFormData.containers.filter((_, i) => i !== index);
		toast.info('Contenedor eliminado');
	}

	// --- Funciones para Aphis Routing ---
	function openAphisRoutingAdd() {
		editingAphisRoutingIndex = null;
		aphisRoutingFormData = { type: '', country: '', name: '' };
		isAphisRoutingDialogOpen = true;
	}

	function openAphisRoutingEdit(index: number) {
		editingAphisRoutingIndex = index;
		aphisRoutingFormData = { ...aphisFormData.routing[index] };
		isAphisRoutingDialogOpen = true;
	}

	function saveAphisRoutingRow() {
		if (editingAphisRoutingIndex !== null) {
			aphisFormData.routing[editingAphisRoutingIndex] = { ...aphisRoutingFormData };
		} else {
			aphisFormData.routing = [...aphisFormData.routing, { ...aphisRoutingFormData }];
		}
		isAphisRoutingDialogOpen = false;
		toast.success(editingAphisRoutingIndex !== null ? 'Ruta actualizada' : 'Ruta agregada');
	}

	function removeAphisRoutingRow(index: number) {
		aphisFormData.routing = aphisFormData.routing.filter((_, i) => i !== index);
		toast.info('Ruta eliminada');
	}
</script>

<div class="flex flex-col gap-6 p-6">
	<div class="flex items-center justify-between">
		<div class="flex items-center gap-4">
			<Button variant="outline" size="icon" href="/dashboard/goods/parts/edit/{idParam}">
				<ArrowLeft class="h-5 w-5" />
			</Button>
			<div>
				<h1 class="text-3xl font-bold tracking-tight">Extensión de Mercancía</h1>
				<p class="text-muted-foreground">
					Campos especiales para: <span class="font-mono font-bold text-primary">{isNew ? 'Nueva Parte' : (part?.part_number || 'Cargando...')}</span>
				</p>
			</div>
		</div>
		<Button onclick={handleSave} disabled={loading} class="gap-2">
			{#if loading}
				<FileCode class="h-4 w-4 animate-spin" />
			{:else}
				<Save class="h-4 w-4" />
			{/if}
			Guardar Cambios
		</Button>
	</div>

	<Separator />

	<Tabs.Root bind:value={activeTab} class="w-full">
		<Tabs.List class="grid w-full max-sm:w-full grid-cols-2">
			<Tabs.Trigger value="catalogo" class="gap-2">
				<Package class="h-4 w-4" />
				Catálogo de partes
			</Tabs.Trigger>
			<Tabs.Trigger value="continuacion" class="gap-2">
				<FileText class="h-4 w-4" />
				Continuación
			</Tabs.Trigger>
		</Tabs.List>

		<div class="mt-6 text-sm">
			<Tabs.Content value="catalogo" class="animate-in fade-in duration-300">
				<Card.Root>
					<Card.Content class="p-6 space-y-8">
						<!-- SECCION 1: Identificación y Aduana -->
						<div class="space-y-4">
							<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div class="space-y-2">
									<Label>Número de parte</Label>
									<Input bind:value={formData.part_number} />
								</div>
								<div class="space-y-2">
									<Label>Tipo parte</Label>
									<select 
										bind:value={formData.part_type}
										class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
									>
										<option value="">Seleccione...</option>
										<option value="MP">Materia Prima</option>
										<option value="PT">Producto Terminado</option>
									</select>
								</div>
							</div>

							<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
								<div class="space-y-2">
									<Label>License code</Label>
									<Input bind:value={formData.license_code} maxlength={3} />
								</div>
								<div class="space-y-2">
									<Label>ECCN</Label>
									<Input bind:value={formData.eccn} maxlength={20} />
								</div>
								<div class="space-y-2">
									<Label>DTA</Label>
									<Input bind:value={formData.dta} maxlength={3} />
								</div>
								<div class="space-y-2">
									<Label>DTB</Label>
									<Input bind:value={formData.dtb} maxlength={3} />
								</div>
							</div>

							<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
								<div class="space-y-2">
									<Label>Export code</Label>
									<Input bind:value={formData.export_code} maxlength={2} />
								</div>
								<div class="space-y-2">
									<Label>Símbolo de excepción</Label>
									<div class="flex gap-2">
										<Input 
											value={formData.exclusion_symbol} 
											placeholder="Seleccione..." 
											readonly 
											onclick={() => isLicenseSelectorOpen = true}
											class="cursor-pointer hover:border-primary transition-colors"
										/>
										<Button variant="outline" size="icon" onclick={() => isLicenseSelectorOpen = true}>
											<Search class="h-4 w-4" />
										</Button>
									</div>
								</div>
								<div class="space-y-2">
									<Label>DTG</Label>
									<Input bind:value={formData.dtg} maxlength={3} />
								</div>
							</div>
						</div>

						<Separator />

						<!-- SECCION 2: Atributos Físicos -->
						<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
							<div class="space-y-2">
								<Label>Anchura</Label>
								<Input bind:value={formData.width} />
							</div>
							<div class="space-y-2">
								<Label>Espesor</Label>
								<Input bind:value={formData.thickness} />
							</div>
							<div class="space-y-2">
								<Label>SPEC</Label>
								<Input bind:value={formData.specification} />
							</div>
						</div>

						<Separator />

						<!-- SECCION 3: Clientes y USMCA -->
						<div class="space-y-4">
							<div class="flex items-center justify-between">
								<Label class="text-base font-bold text-primary">Gestión de Clientes y USMCA</Label>
								<Button variant="outline" size="sm" onclick={openClientAdd} class="gap-2">
									<Plus class="h-4 w-4" /> Agregar Registro Cliente
								</Button>
							</div>

							<div class="rounded-lg border overflow-hidden shadow-sm">
								<Table.Root>
									<Table.Header class="bg-muted/50">
										<Table.Row>
											<Table.Head>Número de parte</Table.Head>
											<Table.Head>Cliente</Table.Head>
											<Table.Head>Nombre parte cliente</Table.Head>
											<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
										</Table.Row>
									</Table.Header>
									<Table.Body>
										{#each formData.client_part_names as row, i}
											<Table.Row class="hover:bg-muted/30">
												<Table.Cell class="font-mono text-xs">{row.part_number}</Table.Cell>
												<Table.Cell class="font-medium">{row.client_name}</Table.Cell>
												<Table.Cell>{row.part_name}</Table.Cell>
												<Table.Cell class="text-right">
													<div class="flex justify-end gap-1">
														<Button variant="ghost" size="icon" onclick={() => openClientEdit(i)} class="h-8 w-8">
															<Edit2 class="h-4 w-4 text-primary" />
														</Button>
														<Button variant="ghost" size="icon" onclick={() => removeClientRow(i)} class="h-8 w-8">
															<Trash2 class="h-4 w-4 text-destructive" />
														</Button>
													</div>
												</Table.Cell>
											</Table.Row>
										{/each}
										{#if formData.client_part_names.length === 0}
											<Table.Row>
												<Table.Cell colspan={4} class="h-24 text-center text-muted-foreground italic">
													No hay registros asignados. Haga clic en agregar para comenzar.
												</Table.Cell>
											</Table.Row>
										{/if}
									</Table.Body>
								</Table.Root>
							</div>

							<div class="grid grid-cols-1 md:grid-cols-2 gap-4 pt-2">
								<div class="space-y-2">
									<Label>Resultado cálculo USMCA/T-MEC</Label>
									<select 
										bind:value={formData.nafta_result}
										class="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50"
									>
										<option value="APLICA_PORCENTAJE">Aplica por porcentaje</option>
										<option value="NO_APLICA">No aplica USMCA/T-MEC</option>
										<option value="SE_CONSIDERA">Se considera USMCA/T-MEC</option>
									</select>
								</div>
								<div class="space-y-2">
									<Label>Porcentaje cálculo USMCA/T-MEC</Label>
									<div class="flex items-center gap-2">
										<Input type="number" bind:value={formData.nafta_percentage} />
										<span class="font-bold text-muted-foreground">%</span>
									</div>
								</div>
							</div>
						</div>

						<Separator />

						<!-- SECCION 4: Referencia y Agencia -->
						<div class="space-y-6">
							<div class="space-y-2">
								<Label>Número de parte Ref</Label>
								<Input bind:value={formData.reference_number} />
							</div>

							<div class="space-y-3 p-4 rounded-xl border bg-muted/20 shadow-inner">
								<div class="flex items-center justify-between">
									<Label class="text-xs uppercase tracking-wider text-muted-foreground font-bold">Agency Tariff code Information</Label>
									<Badge variant="outline" class="gap-1 bg-background">
										<Info class="h-3 w-3" />
										Información de Referencia
									</Badge>
								</div>
								
								<div class="grid grid-cols-1 md:grid-cols-4 gap-4 items-end">
									<div class="space-y-2 md:col-span-2">
										<Label>Agency Tariff code</Label>
										<div class="flex gap-2">
											<Input 
												value={formData.agency_code_definition} 
												placeholder="Seleccione de catálogo..." 
												readonly 
												onclick={() => isAgencySelectorOpen = true}
												class="cursor-pointer hover:border-primary transition-colors"
											/>
											<Button variant="outline" size="icon" onclick={() => isAgencySelectorOpen = true}>
												<Search class="h-4 w-4" />
											</Button>
											<Button variant="outline" size="icon" onclick={() => {
												formData.agency_code_definition = '';
												formData.agency_info = { code: '', required: '', program: '', definition: '' };
											}}>
												<Trash2 class="h-4 w-4 text-destructive" />
											</Button>
										</div>
									</div>
									<div class="space-y-1">
										<span class="text-[10px] font-bold text-muted-foreground uppercase">Agency Code</span>
										<p class="text-sm font-semibold truncate border rounded-md px-3 py-2 bg-background min-h-[40px] flex items-center">{formData.agency_info.code}</p>
									</div>
									<div class="space-y-1">
										<span class="text-[10px] font-bold text-muted-foreground uppercase">Status</span>
										<p class="text-sm font-semibold truncate border rounded-md px-3 py-2 bg-background min-h-[40px] flex items-center">{formData.agency_info.required}</p>
									</div>
								</div>

								<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
									<div class="space-y-1">
										<span class="text-[10px] font-bold text-muted-foreground uppercase">Program Code</span>
										<p class="text-sm font-semibold truncate border rounded-md px-3 py-2 bg-background min-h-[40px] flex items-center">{formData.agency_info.program}</p>
									</div>
									<div class="space-y-1">
										<span class="text-[10px] font-bold text-muted-foreground uppercase">Definition</span>
										<p class="text-sm font-semibold truncate border rounded-md px-3 py-2 bg-background min-h-[40px] flex items-center">{formData.agency_info.definition}</p>
									</div>
								</div>
							</div>
						</div>

						<Separator />

						<!-- SECCION 5: Localización y Catálogos -->
						<div class="space-y-4">
							<div class="space-y-2">
								<Label>Descripción en español</Label>
								<Input bind:value={formData.description_spanish} />
							</div>

							<div class="grid grid-cols-1 md:grid-cols-2 gap-6">
								<div class="space-y-2">
									<Label>Identificador (Apéndice 8)</Label>
									<div class="flex gap-2">
										<Input 
											value={formData.part_identifiers[0]?.clave || ''} 
											placeholder="Seleccionar identificador..." 
											readonly 
											onclick={() => isIdentifierSelectorOpen = true}
											class="cursor-pointer font-bold text-primary font-mono"
										/>
										<Button variant="outline" size="icon" onclick={() => isIdentifierSelectorOpen = true}>
											<Search class="h-4 w-4" />
										</Button>
										{#if formData.part_identifiers.length > 0}
											<Button variant="outline" size="icon" onclick={clearIdentifier}>
												<Trash2 class="h-4 w-4 text-destructive" />
											</Button>
										{/if}
									</div>
									{#if formData.part_identifiers[0]}
										<p class="text-[10px] text-muted-foreground italic px-1 truncate">
											{formData.part_identifiers[0].descripcion}
										</p>
									{/if}
								</div>

								<div class="space-y-2">
									<Label>Carta porte</Label>
									<div class="flex gap-2">
										<Input 
											value={formData.carta_porte} 
											placeholder="Código SAT..." 
											readonly 
											onclick={() => isCartaPorteSelectorOpen = true}
											class="cursor-pointer font-mono"
										/>
										<Button variant="outline" size="icon" onclick={() => isCartaPorteSelectorOpen = true}>
											<Layers class="h-4 w-4" />
										</Button>
										{#if formData.carta_porte}
											<Button variant="outline" size="icon" onclick={() => formData.carta_porte = ''}>
												<Trash2 class="h-4 w-4 text-destructive" />
											</Button>
										{/if}
									</div>
								</div>
							</div>
						</div>

						<Separator />

						<!-- SECCION 6: Reglas Especiales -->
						<div class="rounded-lg border p-4 bg-primary/5 border-primary/20 shadow-sm">
							<div class="flex items-center justify-between">
								<div class="space-y-1">
									<h4 class="text-sm font-bold flex items-center gap-2">
										<div class="h-2 w-2 rounded-full bg-primary animate-pulse"></div>
										Sugerencia de regla octava
									</h4>
									<p class="text-xs text-muted-foreground">Habilitar sugerencia automática para esta parte según criterios aduanales.</p>
								</div>
								<Switch bind:checked={formData.use_rule_8} />
							</div>
						</div>
					</Card.Content>
				</Card.Root>
			</Tabs.Content>

			<Tabs.Content value="continuacion" class="animate-in fade-in duration-300">
				<Card.Root>
					<Card.Header>
						<Card.Title class="flex items-center gap-2">
							<FileText class="h-5 w-5 text-primary" />
							Continuación de Datos
						</Card.Title>
						<Card.Description>
							Gestión de partes sustitutas y datos adicionales.
						</Card.Description>
					</Card.Header>
					<Card.Content class="p-6 space-y-8">
						<!-- Partes Sustitutas -->
						<div class="space-y-4">
							<div class="flex items-center justify-between">
								<Label class="text-base font-bold text-primary">Partes Sustitutas</Label>
								<Button variant="outline" size="sm" onclick={openSubstituteAdd} class="gap-2">
									<Plus class="h-4 w-4" /> Agregar Sustituto
								</Button>
							</div>

							<div class="rounded-lg border overflow-hidden shadow-sm">
								<Table.Root>
									<Table.Header class="bg-muted/50">
										<Table.Row>
											<Table.Head>Número de parte sustituto</Table.Head>
											<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
										</Table.Row>
									</Table.Header>
									<Table.Body>
										{#each formData.substitute_parts as row, i}
											<Table.Row class="hover:bg-muted/30">
												<Table.Cell class="font-mono">{row.substitute_part_number}</Table.Cell>
												<Table.Cell class="text-right">
													<div class="flex justify-end gap-1">
														<Button variant="ghost" size="icon" onclick={() => openSubstituteEdit(i)} class="h-8 w-8">
															<Edit2 class="h-4 w-4 text-primary" />
														</Button>
														<Button variant="ghost" size="icon" onclick={() => removeSubstituteRow(i)} class="h-8 w-8">
															<Trash2 class="h-4 w-4 text-destructive" />
														</Button>
													</div>
												</Table.Cell>
											</Table.Row>
										{/each}
										{#if formData.substitute_parts.length === 0}
											<Table.Row>
												<Table.Cell colspan={2} class="h-24 text-center text-muted-foreground italic">
													No hay partes sustitutas asignadas.
												</Table.Cell>
											</Table.Row>
										{/if}
									</Table.Body>
								</Table.Root>
							</div>
						</div>

						<Separator />

						<!-- Sección Aphis -->
						<div class="space-y-4">
							<Label class="text-base font-bold text-primary">Aphis</Label>
							<div class="flex items-center gap-2">
								<div class="flex-1 space-y-1">
									<Label class="text-xs text-muted-foreground">Código interno</Label>
									<Input bind:value={formData.aphis_data.input1} placeholder="..." />
								</div>
								<div class="flex-1 space-y-1">
									<Label class="text-xs text-muted-foreground">Program Code (del catálogo)</Label>
									<Input bind:value={formData.aphis_data.input2} placeholder="Selecciona del catálogo..." readonly class="bg-muted/40 cursor-default" />
								</div>
								<div class="flex flex-col justify-end">
									<Label class="text-xs text-muted-foreground invisible">.</Label>
									<Button variant="outline" size="icon" onclick={() => isAphisDialogOpen = true} title="Ver catálogo Aphis">
										<Folder class="h-4 w-4 text-primary" />
									</Button>
								</div>
							</div>
						</div>
					</Card.Content>
				</Card.Root>
			</Tabs.Content>
		</div>
	</Tabs.Root>
</div>

<!-- Diálogo de Gestión de Cliente -->
<Dialog.Root bind:open={isClientDialogOpen}>
	<Dialog.Content class="sm:max-w-[425px] z-[50]">
		<Dialog.Header>
			<Dialog.Title>{editingClientIndex !== null ? 'Editar Registro de Cliente' : 'Agregar Registro de Cliente'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles de la parte para el cliente seleccionado.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid gap-4 py-4">
			<div class="grid gap-2">
				<Label for="client-part">Número de parte (Interno)</Label>
				<Input id="client-part" bind:value={clientFormData.part_number} placeholder="Ej: P-12345" />
			</div>
			
			<div class="grid gap-2">
				<Label for="client-search" class="required">Cliente</Label>
				<div class="flex gap-2">
					<Input 
						id="client-search" 
						bind:value={clientFormData.client_name} 
						placeholder="Seleccione un cliente..." 
						readonly 
						onclick={() => isClientSearchOpen = true}
						class="cursor-pointer bg-muted/30"
					/>
					<Button variant="outline" size="icon" onclick={() => isClientSearchOpen = true}>
						<Search class="h-4 w-4" />
					</Button>
				</div>
			</div>
			
			<div class="grid gap-2">
				<Label for="part-name">Nombre de parte cliente</Label>
				<Input id="part-name" bind:value={clientFormData.part_name} placeholder="Descripción para el cliente" />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isClientDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveClientRow}>Guardar Registro</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo de Gestión de Sustitutos -->
<Dialog.Root bind:open={isSubstituteDialogOpen}>
	<Dialog.Content class="sm:max-w-[425px] z-[50]">
		<Dialog.Header>
			<Dialog.Title>{editingSubstituteIndex !== null ? 'Editar Parte Sustituta' : 'Agregar Parte Sustituta'}</Dialog.Title>
			<Dialog.Description>
				Vincule una parte existente como sustituta de la original.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid gap-6 py-4">
			<div class="space-y-1 p-3 rounded-lg bg-muted/50 border border-dashed text-center">
				<span class="text-[10px] uppercase font-bold text-muted-foreground tracking-widest">Número de parte original</span>
				<p class="text-lg font-mono font-bold text-primary">{formData.part_number || 'SIN DEFINIR'}</p>
			</div>

			<div class="grid gap-2">
				<Label for="substitute-part">Número de parte sustituto</Label>
				<div class="flex gap-2">
					<Input id="substitute-part" bind:value={substituteFormData.substitute_part_number} placeholder="Buscar o ingresar..." />
					<Button variant="outline" size="icon" onclick={() => isPartSelectorOpen = true}>
						<Search class="h-4 w-4" />
					</Button>
				</div>
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isSubstituteDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveSubstituteRow}>Guardar Sustituto</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS (Tabla Resumen) -->
<Dialog.Root bind:open={isAphisDialogOpen}>
	<Dialog.Content class="max-w-[95vw] sm:max-w-7xl h-[80vh] flex flex-col z-[50]">
		<Dialog.Header>
			<div class="flex items-center justify-between">
				<div>
					<Dialog.Title>Catálogo Aphis</Dialog.Title>
					<Dialog.Description>
						Gestiona tus registros Aphis. Al seleccionar uno, se usará su <strong>Program Code</strong> en el formulario.
					</Dialog.Description>
				</div>
				<Button variant="outline" size="sm" onclick={openAphisAdd} class="gap-2">
					<Plus class="h-4 w-4" /> Agregar Nuevo Registro
				</Button>
			</div>
		</Dialog.Header>
		
		<div class="flex-1 overflow-auto py-4">
			<div class="rounded-lg border shadow-sm">
				<Table.Root>
					<Table.Header class="bg-muted/50 sticky top-0 z-10">
						<Table.Row>
							<Table.Head>Program Code</Table.Head>
							<Table.Head>Processing code</Table.Head>
							<Table.Head>Aphis type</Table.Head>
							<Table.Head>Disclaimer</Table.Head>
							<Table.Head>Electronic Image</Table.Head>
							<Table.Head>Confidential</Table.Head>
							<Table.Head>Global product id</Table.Head>
							<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
						</Table.Row>
					</Table.Header>
					<Table.Body>
						{#each aphisCatalogRecords as row, i}
							<Table.Row class="hover:bg-muted/30">
								<Table.Cell class="font-semibold">{row.program_code || '-'}</Table.Cell>
								<Table.Cell>{row.processing_code || '-'}</Table.Cell>
								<Table.Cell>{row.aphis_type || '-'}</Table.Cell>
								<Table.Cell>{row.disclaimer || '-'}</Table.Cell>
								<Table.Cell>{row.electronic_image || '-'}</Table.Cell>
								<Table.Cell>{row.confidential || '-'}</Table.Cell>
								<Table.Cell>{row.global_product_id || '-'}</Table.Cell>
								<Table.Cell class="text-right">
									<div class="flex justify-end gap-1">
										<Button
											variant="default"
											size="sm"
											class="h-8 px-2 text-xs"
											onclick={() => {
												formData.aphis_data.input2 = row.program_code || '';
												isAphisDialogOpen = false;
												toast.success(`Program Code seleccionado: ${row.program_code}`);
											}}
										>
											Seleccionar
										</Button>
										<Button variant="ghost" size="icon" onclick={() => openAphisEdit(i)} class="h-8 w-8">
											<Edit2 class="h-4 w-4 text-primary" />
										</Button>
										<Button variant="ghost" size="icon" onclick={() => removeAphisRow(i)} class="h-8 w-8">
											<Trash2 class="h-4 w-4 text-destructive" />
										</Button>
									</div>
								</Table.Cell>
							</Table.Row>
						{:else}
							<Table.Row>
								<Table.Cell colspan={8} class="h-48 text-center text-muted-foreground italic">
									No hay registros Aphis. Haga clic en agregar para comenzar.
								</Table.Cell>
							</Table.Row>
						{/each}
					</Table.Body>
				</Table.Root>
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisDialogOpen = false}>Cerrar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS DETALLE (7 TABS) -->
<Dialog.Root bind:open={isAphisDetailDialogOpen}>
	<Dialog.Content class="max-w-[95vw] sm:max-w-6xl h-[85vh] flex flex-col z-[60]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisIndex !== null ? 'Editar Detalle Aphis' : 'Nuevo Registro Aphis'}</Dialog.Title>
			<Dialog.Description>
				Complete la información técnica en cada una de las pestañas.
			</Dialog.Description>
		</Dialog.Header>

		<div class="flex-1 overflow-hidden py-4 text-sm">
			<Tabs.Root bind:value={aphisActiveDetailTab} class="h-full flex flex-col">
				<Tabs.List class="grid w-full grid-cols-4 md:grid-cols-7 h-auto p-1 bg-muted/50 rounded-lg">
					<Tabs.Trigger value="general" class="text-[10px] sm:text-xs py-2 px-1 gap-1">
						<Settings2 class="h-3 w-3" /> <span class="hidden sm:inline">General</span>
					</Tabs.Trigger>
					<Tabs.Trigger value="characteristic" class="text-[10px] sm:text-xs py-2 px-1 gap-1" disabled={!aphisFormData.general.program_code}>
						<Info class="h-3 w-3" /> <span class="hidden sm:inline">Char</span>
					</Tabs.Trigger>
					<Tabs.Trigger value="stype_pitems" class="text-[10px] sm:text-xs py-2 px-1 gap-1" disabled={!aphisFormData.general.program_code}>
						<Layers class="h-3 w-3" /> <span class="hidden sm:inline">Stype</span>
					</Tabs.Trigger>
					<Tabs.Trigger value="lpcos" class="text-[10px] sm:text-xs py-2 px-1 gap-1" disabled={!aphisFormData.general.program_code}>
						<ShieldCheck class="h-3 w-3" /> <span class="hidden sm:inline">LPCOs</span>
					</Tabs.Trigger>
					<Tabs.Trigger value="entities" class="text-[10px] sm:text-xs py-2 px-1 gap-1" disabled={!aphisFormData.general.program_code}>
						<UserCircle2 class="h-3 w-3" /> <span class="hidden sm:inline">Entities</span>
					</Tabs.Trigger>
					<Tabs.Trigger value="containers" class="text-[10px] sm:text-xs py-2 px-1 gap-1" disabled={!aphisFormData.general.program_code}>
						<Container class="h-3 w-3" /> <span class="hidden sm:inline">Conts</span>
					</Tabs.Trigger>
					<Tabs.Trigger value="routing" class="text-[10px] sm:text-xs py-2 px-1 gap-1" disabled={!aphisFormData.general.program_code}>
						<Navigation class="h-3 w-3" /> <span class="hidden sm:inline">Routing</span>
					</Tabs.Trigger>
				</Tabs.List>

				<div class="flex-1 overflow-auto mt-4 p-6 border rounded-xl bg-card shadow-inner space-y-8">
					<Tabs.Content value="general" class="space-y-8 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<!-- Grupos de campos para Información General -->
						<div class="space-y-6">
							<div class="flex items-center gap-2 text-primary font-bold border-b pb-2">
								<Settings2 class="h-4 w-4" /> Identificadores Base
							</div>
							<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Program Code</Label>
									<Input bind:value={aphisFormData.general.program_code} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Processing code</Label>
									<Input bind:value={aphisFormData.general.processing_code} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Aphis type</Label>
									<Input bind:value={aphisFormData.general.aphis_type} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Disclaimer</Label>
									<Input bind:value={aphisFormData.general.disclaimer} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Electronic Image</Label>
									<Input bind:value={aphisFormData.general.electronic_image} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Confidential</Label>
									<Input bind:value={aphisFormData.general.confidential} />
								</div>
								<div class="space-y-1.5 md:col-span-2">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Global product id</Label>
									<Input bind:value={aphisFormData.general.global_product_id} />
								</div>
							</div>
						</div>

						<div class="space-y-6">
							<div class="flex items-center gap-2 text-primary font-bold border-b pb-2">
								<Info class="h-4 w-4" /> Uso y Tipo de Item
							</div>
							<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Intended use code</Label>
									<Input bind:value={aphisFormData.general.intended_use_code} />
								</div>
								<div class="space-y-1.5 md:col-span-2">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Intended use description</Label>
									<Input bind:value={aphisFormData.general.intended_use_description} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Item type</Label>
									<Input bind:value={aphisFormData.general.item_type} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Product code</Label>
									<Input bind:value={aphisFormData.general.product_code} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Product code 2</Label>
									<Input bind:value={aphisFormData.general.product_code_2} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Product code 3</Label>
									<Input bind:value={aphisFormData.general.product_code_3} />
								</div>
							</div>
						</div>

						<div class="space-y-6">
							<div class="flex items-center gap-2 text-primary font-bold border-b pb-2">
								<FlaskConical class="h-4 w-4" /> Taxonomía y Nombres
							</div>
							<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Scientific genus name</Label>
									<Input bind:value={aphisFormData.general.scientific_genus_name} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Scientific species name</Label>
									<Input bind:value={aphisFormData.general.scientific_species_name} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Scientific sub specie name</Label>
									<Input bind:value={aphisFormData.general.scientific_sub_species_name} />
								</div>
								<div class="space-y-1.5 md:col-span-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Common name specific</Label>
									<Input bind:value={aphisFormData.general.common_name_specific} />
								</div>
								<div class="space-y-1.5 md:col-span-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Common name general</Label>
									<Input bind:value={aphisFormData.general.common_name_general} />
								</div>
							</div>
						</div>

						<div class="space-y-6">
							<div class="flex items-center gap-2 text-primary font-bold border-b pb-2">
								<FileText class="h-4 w-4" /> Documentación y Facturación
							</div>
							<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Signed doc</Label>
									<Input bind:value={aphisFormData.general.signed_doc} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Signed doc date</Label>
									<Input type="date" bind:value={aphisFormData.general.signed_doc_date} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Signed doc ID</Label>
									<Input bind:value={aphisFormData.general.signed_doc_id} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Invoice number</Label>
									<Input bind:value={aphisFormData.general.invoice_number} />
								</div>
							</div>
						</div>

						<div class="space-y-6">
							<div class="flex items-center gap-2 text-primary font-bold border-b pb-2">
								<Boxes class="h-4 w-4" /> Cantidades e Inspección
							</div>
							<div class="grid grid-cols-1 md:grid-cols-3 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Quantity 1</Label>
									<Input bind:value={aphisFormData.general.quantity_1} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Quantity 2</Label>
									<Input bind:value={aphisFormData.general.quantity_2} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Quantity 3</Label>
									<Input bind:value={aphisFormData.general.quantity_3} />
								</div>
							</div>
							<div class="grid grid-cols-1 md:grid-cols-4 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Inspection</Label>
									<Input bind:value={aphisFormData.general.inspection} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Inspection date</Label>
									<Input type="date" bind:value={aphisFormData.general.inspection_date} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Insp. Loc. Date</Label>
									<Input type="date" bind:value={aphisFormData.general.inspection_loc_date} />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Inspection Location</Label>
									<Input bind:value={aphisFormData.general.inspection_location} />
								</div>
							</div>
						</div>

						<div class="space-y-6">
							<div class="flex items-center gap-2 text-primary font-bold border-b pb-2">
								<Layers class="h-4 w-4" /> Origen de la Mercancía
							</div>
							<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Country Production (Ctry Prod)</Label>
									<Input bind:value={aphisFormData.general.country_production} maxlength={3} placeholder="MÉX" />
								</div>
								<div class="space-y-1.5">
									<Label class="text-xs uppercase text-muted-foreground font-bold">Country Source (Ctry Src)</Label>
									<Input bind:value={aphisFormData.general.country_source} maxlength={3} placeholder="USA" />
								</div>
							</div>
						</div>
					</Tabs.Content>

					<Tabs.Content value="characteristic" class="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<div class="flex items-center justify-between">
							<div class="font-bold text-primary flex items-center gap-2">
								<Info class="h-4 w-4" /> Item Characteristic
							</div>
							<Button variant="outline" size="sm" onclick={openAphisCharacteristicAdd} class="gap-2" disabled={!aphisFormData.general.program_code}>
								<Plus class="h-4 w-4" /> Agregar Característica
							</Button>
						</div>
						{#if !aphisFormData.general.program_code}
							<div class="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
								<Info class="h-4 w-4" /> Es necesario capturar el <strong>Program Code</strong> en la pestaña General antes de agregar detalles.
							</div>
						{/if}
						<div class="rounded-lg border overflow-hidden shadow-sm">
							<Table.Root>
								<Table.Header class="bg-muted/50">
									<Table.Row>
										<Table.Head>Item ID</Table.Head>
										<Table.Head>Number from</Table.Head>
										<Table.Head>Number to</Table.Head>
										<Table.Head>Category type</Table.Head>
										<Table.Head>Commodity qua</Table.Head>
										<Table.Head>Comm char qua</Table.Head>
										<Table.Head>Description</Table.Head>
										<Table.Head>Category code</Table.Head>
										<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#each aphisFormData.characteristics as row, i}
										<Table.Row class="hover:bg-muted/30">
											<Table.Cell>{row.item_id || '-'}</Table.Cell>
											<Table.Cell>{row.number_from || '-'}</Table.Cell>
											<Table.Cell>{row.number_to || '-'}</Table.Cell>
											<Table.Cell>{row.category_type || '-'}</Table.Cell>
											<Table.Cell>{row.commodity_qua || '-'}</Table.Cell>
											<Table.Cell>{row.commodity_char_qua || '-'}</Table.Cell>
											<Table.Cell>{row.description || '-'}</Table.Cell>
											<Table.Cell>{row.category_code || '-'}</Table.Cell>
											<Table.Cell class="text-right">
												<div class="flex justify-end gap-1">
													<Button variant="ghost" size="icon" onclick={() => openAphisCharacteristicEdit(i)} class="h-8 w-8">
														<Edit2 class="h-4 w-4 text-primary" />
													</Button>
													<Button variant="ghost" size="icon" onclick={() => removeAphisCharacteristicRow(i)} class="h-8 w-8">
														<Trash2 class="h-4 w-4 text-destructive" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										<Table.Row>
											<Table.Cell colspan={9} class="h-24 text-center text-muted-foreground italic">
												No hay características asignadas a este registro.
											</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					</Tabs.Content>
					<Tabs.Content value="stype_pitems" class="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<div class="flex items-center justify-between">
							<div class="font-bold text-primary flex items-center gap-2">
								<Layers class="h-4 w-4" /> Stype_Pitems
							</div>
							<Button variant="outline" size="sm" onclick={openAphisStypeAdd} class="gap-2" disabled={!aphisFormData.general.program_code}>
								<Plus class="h-4 w-4" /> Agregar Stype
							</Button>
						</div>
						{#if !aphisFormData.general.program_code}
							<div class="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
								<Info class="h-4 w-4" /> Es necesario capturar el <strong>Program Code</strong> en la pestaña General antes de agregar detalles.
							</div>
						{/if}
						<div class="rounded-lg border overflow-hidden shadow-sm">
							<Table.Root>
								<Table.Header class="bg-muted/50">
									<Table.Row>
										<Table.Head>Source type</Table.Head>
										<Table.Head>Country</Table.Head>
										<Table.Head>Geo location</Table.Head>
										<Table.Head>Start</Table.Head>
										<Table.Head>End</Table.Head>
										<Table.Head>Processing type</Table.Head>
										<Table.Head>Description</Table.Head>
										<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#each aphisFormData.stype_pitems as row, i}
										<Table.Row class="hover:bg-muted/30">
											<Table.Cell>{row.source_type_code || '-'}</Table.Cell>
											<Table.Cell>{row.country_code || '-'}</Table.Cell>
											<Table.Cell>{row.geo_location || '-'}</Table.Cell>
											<Table.Cell>{row.processing_start || '-'}</Table.Cell>
											<Table.Cell>{row.processing_end || '-'}</Table.Cell>
											<Table.Cell>{row.processing_type || '-'}</Table.Cell>
											<Table.Cell>{row.processing_desc || '-'}</Table.Cell>
											<Table.Cell class="text-right">
												<div class="flex justify-end gap-1">
													<Button variant="ghost" size="icon" onclick={() => openAphisStypeEdit(i)} class="h-8 w-8">
														<Edit2 class="h-4 w-4 text-primary" />
													</Button>
													<Button variant="ghost" size="icon" onclick={() => removeAphisStypeRow(i)} class="h-8 w-8">
														<Trash2 class="h-4 w-4 text-destructive" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										<Table.Row>
											<Table.Cell colspan={8} class="h-24 text-center text-muted-foreground italic">
												No hay registros de stype asignados.
											</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					</Tabs.Content>
					<Tabs.Content value="lpcos" class="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<div class="flex items-center justify-between">
							<div class="font-bold text-primary flex items-center gap-2">
								<FileText class="h-4 w-4" /> LPCO Details
							</div>
							<Button variant="outline" size="sm" onclick={openAphisLpcoAdd} class="gap-2" disabled={!aphisFormData.general.program_code}>
								<Plus class="h-4 w-4" /> Agregar LPCO
							</Button>
						</div>
						{#if !aphisFormData.general.program_code}
							<div class="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
								<Info class="h-4 w-4" /> Es necesario capturar el <strong>Program Code</strong> en la pestaña General antes de agregar detalles.
							</div>
						{/if}
						<div class="rounded-lg border overflow-hidden shadow-sm">
							<Table.Root>
								<Table.Header class="bg-muted/50">
									<Table.Row>
										<Table.Head>Issuer</Table.Head>
										<Table.Head>Loc Qua</Table.Head>
										<Table.Head>Loc</Table.Head>
										<Table.Head>Loc Desc</Table.Head>
										<Table.Head>Type</Table.Head>
										<Table.Head>Number</Table.Head>
										<Table.Head>Txn Type</Table.Head>
										<Table.Head>UOM</Table.Head>
										<Table.Head>Date Qual</Table.Head>
										<Table.Head>Date</Table.Head>
										<Table.Head>Qty</Table.Head>
										<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#each aphisFormData.lpcos as row, i}
										<Table.Row class="hover:bg-muted/30">
											<Table.Cell>{row.issuer || '-'}</Table.Cell>
											<Table.Cell>{row.issuer_loc_qua || '-'}</Table.Cell>
											<Table.Cell>{row.issuer_loc || '-'}</Table.Cell>
											<Table.Cell>{row.issuer_loc_desc || '-'}</Table.Cell>
											<Table.Cell>{row.type || '-'}</Table.Cell>
											<Table.Cell>{row.number || '-'}</Table.Cell>
											<Table.Cell>{row.txn_type || '-'}</Table.Cell>
											<Table.Cell>{row.uom || '-'}</Table.Cell>
											<Table.Cell>{row.date_qual || '-'}</Table.Cell>
											<Table.Cell>{row.date || '-'}</Table.Cell>
											<Table.Cell>{row.qty || '-'}</Table.Cell>
											<Table.Cell class="text-right">
												<div class="flex justify-end gap-1">
													<Button variant="ghost" size="icon" onclick={() => openAphisLpcoEdit(i)} class="h-8 w-8">
														<Edit2 class="h-4 w-4 text-primary" />
													</Button>
													<Button variant="ghost" size="icon" onclick={() => removeAphisLpcoRow(i)} class="h-8 w-8">
														<Trash2 class="h-4 w-4 text-destructive" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										<Table.Row>
											<Table.Cell colspan={12} class="h-24 text-center text-muted-foreground italic">
												No hay registros LPCO asignados.
											</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					</Tabs.Content>
					<Tabs.Content value="entities" class="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<div class="flex items-center justify-between">
							<div class="font-bold text-primary flex items-center gap-2">
								<Users class="h-4 w-4" /> Entities
							</div>
							<Button variant="outline" size="sm" onclick={openAphisEntitiesAdd} class="gap-2" disabled={!aphisFormData.general.program_code}>
								<Plus class="h-4 w-4" /> Agregar Entidad
							</Button>
						</div>
						{#if !aphisFormData.general.program_code}
							<div class="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
								<Info class="h-4 w-4" /> Es necesario capturar el <strong>Program Code</strong> en la pestaña General antes de agregar detalles.
							</div>
						{/if}
						<div class="rounded-lg border overflow-hidden shadow-sm">
							<Table.Root>
								<Table.Header class="bg-muted/50">
									<Table.Row>
										<Table.Head>Consignee Key</Table.Head>
										<Table.Head>Broker Key</Table.Head>
										<Table.Head>LPCO Auth Party Key</Table.Head>
										<Table.Head>Grower Key</Table.Head>
										<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#each aphisFormData.entities as row, i}
										<Table.Row class="hover:bg-muted/30">
											<Table.Cell>{row.consignee_key || '-'}</Table.Cell>
											<Table.Cell>{row.broker_key || '-'}</Table.Cell>
											<Table.Cell>{row.lpco_auth_party_key || '-'}</Table.Cell>
											<Table.Cell>{row.grower_key || '-'}</Table.Cell>
											<Table.Cell class="text-right">
												<div class="flex justify-end gap-1">
													<Button variant="ghost" size="icon" onclick={() => openAphisEntitiesEdit(i)} class="h-8 w-8">
														<Edit2 class="h-4 w-4 text-primary" />
													</Button>
													<Button variant="ghost" size="icon" onclick={() => removeAphisEntitiesRow(i)} class="h-8 w-8">
														<Trash2 class="h-4 w-4 text-destructive" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										<Table.Row>
											<Table.Cell colspan={5} class="h-24 text-center text-muted-foreground italic">
												No hay entidades asignadas.
											</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					</Tabs.Content>
					<Tabs.Content value="containers" class="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<div class="flex items-center justify-between">
							<div class="font-bold text-primary flex items-center gap-2">
								<Container class="h-4 w-4" /> Containers
							</div>
							<Button variant="outline" size="sm" onclick={openAphisContainersAdd} class="gap-2" disabled={!aphisFormData.general.program_code}>
								<Plus class="h-4 w-4" /> Agregar Contenedor
							</Button>
						</div>
						{#if !aphisFormData.general.program_code}
							<div class="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
								<Info class="h-4 w-4" /> Es necesario capturar el <strong>Program Code</strong> en la pestaña General antes de agregar detalles.
							</div>
						{/if}
						<div class="rounded-lg border overflow-hidden shadow-sm">
							<Table.Root>
								<Table.Header class="bg-muted/50">
									<Table.Row>
										<Table.Head>Container Number</Table.Head>
										<Table.Head>Length</Table.Head>
										<Table.Head>Type</Table.Head>
										<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#each aphisFormData.containers as row, i}
										<Table.Row class="hover:bg-muted/30">
											<Table.Cell>{row.container_number || '-'}</Table.Cell>
											<Table.Cell>{row.length || '-'}</Table.Cell>
											<Table.Cell>{row.type || '-'}</Table.Cell>
											<Table.Cell class="text-right">
												<div class="flex justify-end gap-1">
													<Button variant="ghost" size="icon" onclick={() => openAphisContainersEdit(i)} class="h-8 w-8">
														<Edit2 class="h-4 w-4 text-primary" />
													</Button>
													<Button variant="ghost" size="icon" onclick={() => removeAphisContainersRow(i)} class="h-8 w-8">
														<Trash2 class="h-4 w-4 text-destructive" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										<Table.Row>
											<Table.Cell colspan={4} class="h-24 text-center text-muted-foreground italic">
												No hay contenedores asignados.
											</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					</Tabs.Content>
					<Tabs.Content value="routing" class="space-y-6 animate-in fade-in slide-in-from-bottom-2 duration-300">
						<div class="flex items-center justify-between">
							<div class="font-bold text-primary flex items-center gap-2">
								<Navigation class="h-4 w-4" /> Routing
							</div>
							<Button variant="outline" size="sm" onclick={openAphisRoutingAdd} class="gap-2" disabled={!aphisFormData.general.program_code}>
								<Plus class="h-4 w-4" /> Agregar Ruta
							</Button>
						</div>
						{#if !aphisFormData.general.program_code}
							<div class="px-4 py-3 rounded-lg bg-destructive/10 border border-destructive/20 text-destructive text-sm flex items-center gap-2">
								<Info class="h-4 w-4" /> Es necesario capturar el <strong>Program Code</strong> en la pestaña General antes de agregar detalles.
							</div>
						{/if}
						<div class="rounded-lg border overflow-hidden shadow-sm">
							<Table.Root>
								<Table.Header class="bg-muted/50">
									<Table.Row>
										<Table.Head>Type</Table.Head>
										<Table.Head>Country</Table.Head>
										<Table.Head>Name</Table.Head>
										<Table.Head class="w-[100px] text-right">Acciones</Table.Head>
									</Table.Row>
								</Table.Header>
								<Table.Body>
									{#each aphisFormData.routing as row, i}
										<Table.Row class="hover:bg-muted/30">
											<Table.Cell>{row.type || '-'}</Table.Cell>
											<Table.Cell>{row.country || '-'}</Table.Cell>
											<Table.Cell>{row.name || '-'}</Table.Cell>
											<Table.Cell class="text-right">
												<div class="flex justify-end gap-1">
													<Button variant="ghost" size="icon" onclick={() => openAphisRoutingEdit(i)} class="h-8 w-8">
														<Edit2 class="h-4 w-4 text-primary" />
													</Button>
													<Button variant="ghost" size="icon" onclick={() => removeAphisRoutingRow(i)} class="h-8 w-8">
														<Trash2 class="h-4 w-4 text-destructive" />
													</Button>
												</div>
											</Table.Cell>
										</Table.Row>
									{:else}
										<Table.Row>
											<Table.Cell colspan={4} class="h-24 text-center text-muted-foreground italic">
												No hay destinos/rutas asignados.
											</Table.Cell>
										</Table.Row>
									{/each}
								</Table.Body>
							</Table.Root>
						</div>
					</Tabs.Content>
				</div>
			</Tabs.Root>
		</div>

		<Dialog.Footer class="bg-muted/10 p-4 border-t">
			<Button variant="outline" onclick={() => isAphisDetailDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisDetail} class="gap-2">
				<Save class="h-4 w-4" /> Guardar Cambios Aphis
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Selector de Partes (Catálogo funcional) -->
<PartSelector 
	bind:open={isPartSelectorOpen} 
	onSelect={handlePartSelect} 
/>

<!-- Diálogo APHIS Characteristic -->
<Dialog.Root bind:open={isAphisCharacteristicDialogOpen}>
	<Dialog.Content class="sm:max-w-[500px] z-[70]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisCharacteristicIndex !== null ? 'Editar Característica' : 'Agregar Característica'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles de la característica para este registro Aphis.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid grid-cols-2 gap-4 py-4 text-sm">
			<div class="space-y-2">
				<Label>Item ID</Label>
				<Input bind:value={aphisCharacteristicFormData.item_id} />
			</div>
			<div class="space-y-2">
				<Label>Category type</Label>
				<Input bind:value={aphisCharacteristicFormData.category_type} />
			</div>
			<div class="space-y-2">
				<Label>Number from</Label>
				<Input bind:value={aphisCharacteristicFormData.number_from} />
			</div>
			<div class="space-y-2">
				<Label>Number to</Label>
				<Input bind:value={aphisCharacteristicFormData.number_to} />
			</div>
			<div class="space-y-2">
				<Label>Commodity qua</Label>
				<Input bind:value={aphisCharacteristicFormData.commodity_qua} />
			</div>
			<div class="space-y-2">
				<Label>Commodity char qua</Label>
				<Input bind:value={aphisCharacteristicFormData.commodity_char_qua} />
			</div>
			<div class="space-y-2 col-span-2">
				<Label>Category code</Label>
				<Input bind:value={aphisCharacteristicFormData.category_code} />
			</div>
			<div class="space-y-2 col-span-2">
				<Label>Description</Label>
				<Input bind:value={aphisCharacteristicFormData.description} />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisCharacteristicDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisCharacteristicRow}>Guardar Característica</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS Stype Pitems -->
<Dialog.Root bind:open={isAphisStypeDialogOpen}>
	<Dialog.Content class="sm:max-w-[500px] z-[70]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisStypeIndex !== null ? 'Editar Stype Pitems' : 'Agregar Stype Pitems'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles de procesamiento para este registro Aphis.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid grid-cols-2 gap-4 py-4 text-sm">
			<div class="space-y-2">
				<Label>Source type code</Label>
				<Input bind:value={aphisStypeFormData.source_type_code} />
			</div>
			<div class="space-y-2">
				<Label>Country code</Label>
				<Input bind:value={aphisStypeFormData.country_code} placeholder="USA" maxlength={3} />
			</div>
			<div class="space-y-2 col-span-2">
				<Label>Geo location</Label>
				<Input bind:value={aphisStypeFormData.geo_location} />
			</div>
			<div class="space-y-2">
				<Label>Processing start</Label>
				<Input type="date" bind:value={aphisStypeFormData.processing_start} />
			</div>
			<div class="space-y-2">
				<Label>Processing end</Label>
				<Input type="date" bind:value={aphisStypeFormData.processing_end} />
			</div>
			<div class="space-y-2 col-span-2">
				<Label>Processing type</Label>
				<Input bind:value={aphisStypeFormData.processing_type} />
			</div>
			<div class="space-y-2 col-span-2">
				<Label>Processing desc</Label>
				<Input bind:value={aphisStypeFormData.processing_desc} />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisStypeDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisStypeRow}>Guardar Stype</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS LPCO -->
<Dialog.Root bind:open={isAphisLpcoDialogOpen}>
	<Dialog.Content class="sm:max-w-[600px] z-[70]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisLpcoIndex !== null ? 'Editar LPCO' : 'Agregar LPCO'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles del documento LPCO para este registro Aphis.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid grid-cols-2 gap-4 py-4 text-sm">
			<div class="space-y-2 col-span-2">
				<Label>Issuer</Label>
				<Input bind:value={aphisLpcoFormData.issuer} />
			</div>
			<div class="space-y-2">
				<Label>Issuer loc qua</Label>
				<Input bind:value={aphisLpcoFormData.issuer_loc_qua} />
			</div>
			<div class="space-y-2">
				<Label>Issuer loc</Label>
				<Input bind:value={aphisLpcoFormData.issuer_loc} />
			</div>
			<div class="space-y-2 col-span-2">
				<Label>Issuer loc desc</Label>
				<Input bind:value={aphisLpcoFormData.issuer_loc_desc} />
			</div>
			<div class="space-y-2">
				<Label>Type</Label>
				<Input bind:value={aphisLpcoFormData.type} />
			</div>
			<div class="space-y-2">
				<Label>Number</Label>
				<Input bind:value={aphisLpcoFormData.number} />
			</div>
			<div class="space-y-2">
				<Label>Txn type</Label>
				<Input bind:value={aphisLpcoFormData.txn_type} />
			</div>
			<div class="space-y-2">
				<Label>UOM</Label>
				<Input bind:value={aphisLpcoFormData.uom} />
			</div>
			<div class="space-y-2">
				<Label>Date qual</Label>
				<Input bind:value={aphisLpcoFormData.date_qual} />
			</div>
			<div class="space-y-2">
				<Label>Date</Label>
				<Input type="date" bind:value={aphisLpcoFormData.date} />
			</div>
			<div class="space-y-2">
				<Label>Qty</Label>
				<Input bind:value={aphisLpcoFormData.qty} />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisLpcoDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisLpcoRow}>Guardar LPCO</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS Entities -->
<Dialog.Root bind:open={isAphisEntitiesDialogOpen}>
	<Dialog.Content class="sm:max-w-[500px] z-[70]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisEntitiesIndex !== null ? 'Editar Entidad' : 'Agregar Entidad'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles de las entidades relacionadas para este registro Aphis.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid grid-cols-1 gap-4 py-4 text-sm">
			<div class="space-y-2">
				<Label>Consignee key</Label>
				<Input bind:value={aphisEntitiesFormData.consignee_key} />
			</div>
			<div class="space-y-2">
				<Label>Broker key</Label>
				<Input bind:value={aphisEntitiesFormData.broker_key} />
			</div>
			<div class="space-y-2">
				<Label>LPCO Auth Party key</Label>
				<Input bind:value={aphisEntitiesFormData.lpco_auth_party_key} />
			</div>
			<div class="space-y-2">
				<Label>Grower key</Label>
				<Input bind:value={aphisEntitiesFormData.grower_key} />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisEntitiesDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisEntitiesRow}>Guardar Entidad</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS Containers -->
<Dialog.Root bind:open={isAphisContainersDialogOpen}>
	<Dialog.Content class="sm:max-w-[450px] z-[70]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisContainersIndex !== null ? 'Editar Contenedor' : 'Agregar Contenedor'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles del contenedor para este registro Aphis.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid grid-cols-1 gap-4 py-4 text-sm">
			<div class="space-y-2">
				<Label>Container number</Label>
				<Input bind:value={aphisContainersFormData.container_number} />
			</div>
			<div class="space-y-2">
				<Label>Length</Label>
				<Input bind:value={aphisContainersFormData.length} />
			</div>
			<div class="space-y-2">
				<Label>Type</Label>
				<Input bind:value={aphisContainersFormData.type} />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisContainersDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisContainersRow}>Guardar Contenedor</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<!-- Diálogo APHIS Routing -->
<Dialog.Root bind:open={isAphisRoutingDialogOpen}>
	<Dialog.Content class="sm:max-w-[450px] z-[70]">
		<Dialog.Header>
			<Dialog.Title>{editingAphisRoutingIndex !== null ? 'Editar Ruta' : 'Agregar Ruta'}</Dialog.Title>
			<Dialog.Description>
				Ingrese los detalles de la ruta para este registro Aphis.
			</Dialog.Description>
		</Dialog.Header>
		
		<div class="grid grid-cols-1 gap-4 py-4 text-sm">
			<div class="space-y-2">
				<Label>Type</Label>
				<Input bind:value={aphisRoutingFormData.type} />
			</div>
			<div class="space-y-2">
				<Label>Country</Label>
				<Input bind:value={aphisRoutingFormData.country} maxlength={2} placeholder="US" />
			</div>
			<div class="space-y-2">
				<Label>Name</Label>
				<Input bind:value={aphisRoutingFormData.name} />
			</div>
		</div>
		
		<Dialog.Footer>
			<Button variant="outline" onclick={() => isAphisRoutingDialogOpen = false}>Cancelar</Button>
			<Button type="submit" onclick={saveAphisRoutingRow}>Guardar Ruta</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<LicenseExceptionSelector bind:open={isLicenseSelectorOpen} onSelect={handleLicenseSelect} />
<AgencyTariffCodeSelector bind:open={isAgencySelectorOpen} onSelect={handleAgencySelect} />
<IdentifierSelector bind:open={isIdentifierSelectorOpen} onSelect={handleIdentifierSelect} />
<CartaPorteSelector bind:open={isCartaPorteSelectorOpen} onSelect={handleCartaPorteSelect} />
<PartSelector bind:open={isPartSelectorOpen} onSelect={handlePartSelect} />
<ClientSelectorDialog bind:open={isClientSearchOpen} onSelect={handleClientSelect} onClear={handleClientClear} />

