<script lang="ts">
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Dialog from '$lib/components/ui/dialog';
	import { Folder } from 'lucide-svelte';
	import { toast } from 'svelte-sonner';
	import {
		materialTypesApi,
		type MaterialType
	} from '$lib/api/dashboard/reference_data/material_types';
	import { unitsOfMeasureApi } from '$lib/api/dashboard/a76/units_of_measure';
	import {
		getTariffFractions,
		type TariffFraction
	} from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
	import {
		buildMexTariffDigitsFromCatalogRow,
		formatMexTariffDigitsForDisplay,
		normalizeMexTariffDigitsStored
	} from '$lib/utils/mexican-tariff-fraction';
	import {
		getDepreciationCatalog,
		type DepreciationCatalog
	} from '$lib/api/dashboard/a76/general_catalogs/depreciation-catalog';
	import {
		getFDACatalog,
		type FDACatalog
	} from '$lib/api/dashboard/a76/general_catalogs/fda-catalog';
	import { companyStore } from '$lib/stores/company.svelte';
	import * as RadioGroup from '$lib/components/ui/radio-group';

	interface Props {
		onSave?: (data: any) => void;
		onCancel?: () => void;
		initialData?: any;
		externalError?: string;
		onClearError?: () => void;
	}

	let { onSave, onCancel, initialData, externalError = '', onClearError }: Props = $props();

	// Tipo para unidad de medida con todos los campos
	interface UnitOfMeasure {
		code: string;
		description: string;
		descriptionEnglish: string;
		claveMexicana: string;
		claveAmericana: string;
		claveACE: string;
		claveOMA: string;
	}

	// Datos de unidades de medida (se cargan desde el API)
	let unitsOfMeasureData: UnitOfMeasure[] = $state([]);

	// Estado del formulario
	let formData = $state({
		class_code: initialData?.class_code || '',
		description_es: initialData?.description_es || '',
		description_en: initialData?.description_en || '',
		material_key: initialData?.material_key || '',
		unit_of_measure: initialData?.unit_of_measure || '',
		fraction: initialData?.fraction || '',
		us_fraction: initialData?.us_fraction || '',
		annual_depreciation_rate: initialData?.annual_depreciation_rate || '',
		fda_key: initialData?.fda_key || '',
		eccn_code: initialData?.eccn_code || '',
		iva_exempt_fraction: '',
		physical_review: initialData?.physical_review || false,
		carta_porte_code: initialData?.carta_porte_code || '',
		// Campos de tarifas de importación/exportación
		import_tariff_code: initialData?.import_tariff_code || '',
		import_tariff_type: initialData?.import_tariff_type || '',
		export_tariff_code: initialData?.export_tariff_code || '',
		export_tariff_type: initialData?.export_tariff_type || '',
		// Campos calculados/display
		material_description: '',
		unit_of_measure_description: '',
		unit_measure_key: '',
		fraction_umt: '',
		fraction_uma_key: '',
		us_fraction_ad_valorem: '',
		us_fraction_fixed_rate: ''
	});

	/** Sí / No (legacy); el valor persistido es `iva_exempt_fraction` (string máx. 4) */
	let ivaExemptChoice = $state<'no' | 'yes'>('no');

	function setIvaExemptChoice(choice: 'no' | 'yes') {
		ivaExemptChoice = choice;
		if (choice === 'no') {
			formData.iva_exempt_fraction = '';
		}
	}

	// Reactively update formData when initialData changes
	$effect(() => {
		if (initialData) {
			// Tomar snapshot para evitar referencias reactivas
			const snap = $state.snapshot(initialData);

			// Usar ?? para manejar null/undefined correctamente (evita que inputs pasen de controlado a no controlado)
			formData.class_code = snap.class_code ?? '';
			formData.description_es = snap.description_es ?? '';
			formData.description_en = snap.description_en ?? '';
			formData.material_key = snap.material_key ?? '';
			formData.unit_of_measure = snap.unit_of_measure ?? '';
			const mxDigits = normalizeMexTariffDigitsStored(
				snap.import_tariff_code || snap.fraction || ''
			);
			formData.fraction = mxDigits;
			formData.import_tariff_code = mxDigits;
			formData.fraction_uma_key = mxDigits.length === 10 ? mxDigits.slice(8, 10) : '';
			formData.us_fraction = snap.us_fraction ?? '';
			// Mapear depreciation_rate a annual_depreciation_rate si existe (números pueden ser null)
			formData.annual_depreciation_rate =
				snap.depreciation_rate ?? snap.annual_depreciation_rate ?? null;
			// Mapear fda_code a fda_key si existe
			formData.fda_key = snap.fda_code ?? snap.fda_key ?? '';
			formData.eccn_code = snap.eccn_code ?? '';
			const ivaRaw = snap.iva_exempt_fraction;
			const ivaStr =
				ivaRaw !== undefined && ivaRaw !== null && ivaRaw !== false && ivaRaw !== true
					? String(ivaRaw).trim().slice(0, 4)
					: '';
			formData.iva_exempt_fraction = ivaStr;
			ivaExemptChoice = ivaStr.length > 0 ? 'yes' : 'no';
			formData.physical_review =
				snap.physical_review === 1 ||
				snap.physical_review === true ||
				snap.physical_review === '1';
			formData.carta_porte_code = snap.carta_porte_code ?? '';
			formData.import_tariff_type = snap.import_tariff_type ?? '';
			formData.export_tariff_code = snap.export_tariff_code ?? '';
			formData.export_tariff_type = snap.export_tariff_type ?? '';
			formData.fraction_umt = snap.import_tariff_type ?? '';
			
			// Reiniciar banderas de error al cargar datos
			showErrors = false;
			validationErrors = {};
		} else {
			// Reset form when initialData is null (new class)
			formData.class_code = '';
			formData.description_es = '';
			formData.description_en = '';
			formData.material_key = '';
			formData.unit_of_measure = '';
			formData.fraction = '';
			formData.us_fraction = '';
			formData.annual_depreciation_rate = '';
			formData.fda_key = '';
			formData.eccn_code = '';
			formData.iva_exempt_fraction = '';
			ivaExemptChoice = 'no';
			formData.physical_review = false;
			formData.carta_porte_code = '';
			formData.import_tariff_code = '';
			formData.import_tariff_type = '';
			formData.export_tariff_code = '';
			formData.export_tariff_type = '';
			formData.unit_measure_key = '';
			formData.fraction_umt = '';
			formData.fraction_uma_key = '';
			formData.us_fraction_ad_valorem = '';
			formData.us_fraction_fixed_rate = '';
			
			// Reiniciar banderas de error al limpiar formulario
			showErrors = false;
			validationErrors = {};
		}
	});

	// Estado de validación
	let validationErrors = $state<Record<string, string>>({});
	let showErrors = $state(false);
	let isSubmitting = $state(false);

	// Estado de diálogos
	let showMaterialDialog = $state(false);
	let materialTypes = $state<MaterialType[]>([]);
	let searchMaterial = $state('');

	let showUnitDialog = $state(false);
	let searchUnit = $state('');

	import TariffFractionSelector from '$lib/components/dashboard/goods/modales/TariffFractionSelector.svelte';

	let showFractionDialog = $state(false);
	// Removing inline tariff fraction state
	// let tariffFractions = ...

	function openFractionSearch() {
		showFractionDialog = true;
	}

	let showUSFractionDialog = $state(false);
	// ...

	// loadFractions removed

	function selectFraction(fraction: TariffFraction) {
		const digits = buildMexTariffDigitsFromCatalogRow(fraction);
		formData.fraction = digits;
		formData.fraction_umt = (fraction.umt ?? '') as string;
		formData.fraction_uma_key = digits.slice(8, 10);
		formData.import_tariff_code = digits;
		formData.import_tariff_type = (fraction.umt ?? '') as string;
		showFractionDialog = false;
	}
	let usTariffFractions = $state<TariffFraction[]>([]);
	let searchUSFraction = $state('');
	let currentUSPage = $state(1);
	let totalUSFractions = $state(0);
	let hasMoreUSFractions = $state(true);
	let isLoadingUSFractions = $state(false);

	let showDepreciationDialog = $state(false);
	let depreciationCatalog = $state<DepreciationCatalog[]>([]);
	let searchDepreciation = $state('');
	let currentDepreciationPage = $state(1);
	let totalDepreciation = $state(0);
	let hasMoreDepreciation = $state(true);
	let isLoadingDepreciation = $state(false);

	let showFDADialog = $state(false);
	let fdaCatalog = $state<FDACatalog[]>([]);
	let searchFDA = $state('');
	let currentFDAPage = $state(1);
	let totalFDA = $state(0);
	let hasMoreFDA = $state(true);
	let isLoadingFDA = $state(false);

	let showCartaPorteDialog = $state(false);
	let cartaPorteCatalog = $state<any[]>([]);
	let searchCartaPorte = $state('');

	// Computed values
	let filteredMaterialTypes = $derived(
		searchMaterial
			? materialTypes.filter(
					(m) =>
						m.key.toLowerCase().includes(searchMaterial.toLowerCase()) ||
						m.description.toLowerCase().includes(searchMaterial.toLowerCase())
				)
			: materialTypes
	);

	let filteredUnits = $derived(
		searchUnit
			? unitsOfMeasureData.filter(
					(u) =>
						u.code.toLowerCase().includes(searchUnit.toLowerCase()) ||
						u.description.toLowerCase().includes(searchUnit.toLowerCase())
				)
			: unitsOfMeasureData
	);

	// Funciones
	async function loadUnitsOfMeasure() {
		if (unitsOfMeasureData.length > 0) return;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) return;
			const response = await unitsOfMeasureApi.list(companyId, 1, 100);
			if (response.data) {
				unitsOfMeasureData = response.data.items.map((item) => ({
					code: item.code,
					description: item.description || '',
					descriptionEnglish: item.description_en || '',
					claveMexicana: item.customs_code || '',
					claveAmericana: item.american_code || '',
					claveACE: item.ace_code || '',
					claveOMA: item.oma_code || ''
				}));
			}
		} catch (error) {
			console.error('Error cargando units of measure:', error);
		}
	}

	async function openMaterialSearch() {
		showMaterialDialog = true;
		searchMaterial = '';
		if (materialTypes.length === 0) {
			try {
				const companyId = companyStore.activeCompany?.id;
				if (!companyId) return;
				const response = await materialTypesApi.list(companyId, 1, 100, 'ACTIVO FIJO');
				if (response.data) {
					materialTypes = response.data.items;
				}
			} catch (error) {
				console.error('Error cargando material types:', error);
			}
		}
	}

	function selectMaterial(material: MaterialType) {
		formData.material_key = material.key;
		formData.material_description = material.description;
		showMaterialDialog = false;
		searchMaterial = '';
	}

	// Fix 1: Buscar descripción de Tipo de Activo Fijo al perder el foco
	async function handleMaterialBlur() {
		validateField('material_key');
		const code = formData.material_key?.trim().toUpperCase();
		if (!code) {
			formData.material_description = '';
			return;
		}
		// Primero buscar en la caché local (si ya se cargó el catálogo)
		if (materialTypes.length > 0) {
			const found = materialTypes.find((m) => m.key.toUpperCase() === code);
			if (found) {
				formData.material_key = found.key;
				formData.material_description = found.description;
				return;
			}
		}
		// Si no está en caché, consultar el API
		try {
			const response = await materialTypesApi.get(code);
			if (response.data) {
				formData.material_key = response.data.key;
				formData.material_description = response.data.description;
			} else {
				formData.material_description = '(Código no encontrado)';
			}
		} catch {
			formData.material_description = '(Código no encontrado)';
		}
	}

	async function openUnitOfMeasureSearch() {
		showUnitDialog = true;
		searchUnit = '';
		await loadUnitsOfMeasure();
	}

	function selectUnit(unit: UnitOfMeasure) {
		formData.unit_of_measure = unit.code;
		formData.unit_of_measure_description = unit.description;
		formData.unit_measure_key = unit.claveMexicana;
		showUnitDialog = false;
		searchUnit = '';
	}

	// Fix 1: Buscar descripción de U.M. Comercial al perder el foco
	async function handleUnitBlur() {
		validateField('unit_of_measure');
		const code = formData.unit_of_measure?.trim().toUpperCase();
		if (!code) {
			formData.unit_of_measure_description = '';
			return;
		}
		// Primero buscar en la caché local (si ya se cargó el catálogo)
		await loadUnitsOfMeasure();
		const found = unitsOfMeasureData.find((u) => u.code.toUpperCase() === code);
		if (found) {
			formData.unit_of_measure = found.code;
			formData.unit_of_measure_description = found.description;
			formData.unit_measure_key = found.claveMexicana;
		} else {
			formData.unit_of_measure_description = '(Código no encontrado)';
		}
	}

	// Fix 2: Máscara para Fracción Americana (formato 0000.00.00.00 = 13 chars)
	function formatUSFraction(event: Event) {
		const input = event.target as HTMLInputElement;
		// Extraer solo dígitos
		const digits = input.value.replace(/\D/g, '').slice(0, 10);
		// Construir la máscara insertando puntos en las posiciones correctas
		let masked = digits;
		if (digits.length > 4) masked = digits.slice(0, 4) + '.' + digits.slice(4);
		if (digits.length > 6) masked = digits.slice(0, 4) + '.' + digits.slice(4, 6) + '.' + digits.slice(6);
		if (digits.length > 8) masked = digits.slice(0, 4) + '.' + digits.slice(4, 6) + '.' + digits.slice(6, 8) + '.' + digits.slice(8);
		formData.us_fraction = masked;
	}

	async function openUSFractionSearch() {
		showUSFractionDialog = true;
		searchUSFraction = '';
		usTariffFractions = [];
		currentUSPage = 1;
		totalUSFractions = 0;
		hasMoreUSFractions = true;
		await loadUSFractions('', 1);
	}

	async function loadUSFractions(search: string, page: number = currentUSPage) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId || isLoadingUSFractions) return;

		isLoadingUSFractions = true;
		try {
			const filters: Record<string, string> = { catalog: 'american' };
			if (search?.trim()) filters.search = search.trim();
			const pageSize = 100;

			const response = await getTariffFractions(page, pageSize, companyId, filters);

			if (response.data) {
				if (page === 1) {
					usTariffFractions = [...response.data.items];
				} else {
					usTariffFractions = [...usTariffFractions, ...response.data.items];
				}

				totalUSFractions = response.data.total;
				currentUSPage = page;
				hasMoreUSFractions = usTariffFractions.length < response.data.total;
			}
		} catch (error) {
			console.error('Error cargando fracciones americanas:', error);
		} finally {
			isLoadingUSFractions = false;
		}
	}

	function selectUSFraction(fraction: TariffFraction) {
		formData.us_fraction = fraction.code || '';
		const advRaw = fraction.adv_impo;
		let advNum = 0;
		if (advRaw != null && String(advRaw).trim() !== '') {
			const n = parseFloat(String(advRaw).replace('%', '').trim());
			if (!Number.isNaN(n)) advNum = n;
		}
		formData.us_fraction_ad_valorem = advNum ? String(advNum) : '0.00';
		formData.us_fraction_fixed_rate = '0.00000000';
		// Actualizar tarifa de exportación
		formData.export_tariff_code = fraction.code || '';
		formData.export_tariff_type = 'HTS'; // Harmonized Tariff Schedule
		showUSFractionDialog = false;
		searchUSFraction = '';
	}

	async function openDepreciationSearch() {
		showDepreciationDialog = true;
		searchDepreciation = '';
		depreciationCatalog = [];
		currentDepreciationPage = 1;
		totalDepreciation = 0;
		hasMoreDepreciation = true;
		await loadDepreciation('', 1);
	}

	async function loadDepreciation(search: string, page: number = currentDepreciationPage) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId || isLoadingDepreciation) return;

		isLoadingDepreciation = true;
		try {
			const filters = search ? { search } : {};
			const pageSize = 100;

			const response = await getDepreciationCatalog(page, pageSize, companyId, filters);

			if (response.data) {
				if (page === 1) {
					depreciationCatalog = [...response.data.items];
				} else {
					depreciationCatalog = [...depreciationCatalog, ...response.data.items];
				}

				totalDepreciation = response.data.total;
				currentDepreciationPage = page;
				hasMoreDepreciation = depreciationCatalog.length < response.data.total;
			}
		} catch (error) {
			console.error('Error cargando catálogo de depreciación:', error);
		} finally {
			isLoadingDepreciation = false;
		}
	}

	function selectDepreciation(item: DepreciationCatalog) {
		formData.annual_depreciation_rate = item.depreciation_rate?.toString() || '';
		showDepreciationDialog = false;
		searchDepreciation = '';
	}

	async function openFDASearch() {
		showFDADialog = true;
		searchFDA = '';
		fdaCatalog = [];
		currentFDAPage = 1;
		totalFDA = 0;
		hasMoreFDA = true;
		await loadFDA('', 1);
	}

	async function loadFDA(search: string, page: number = currentFDAPage) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId || isLoadingFDA) return;

		isLoadingFDA = true;
		try {
			const filters = search ? { search } : {};
			const pageSize = 100;

			const response = await getFDACatalog(page, pageSize, companyId, filters);

			if (response.data) {
				if (page === 1) {
					fdaCatalog = [...response.data.items];
				} else {
					fdaCatalog = [...fdaCatalog, ...response.data.items];
				}

				totalFDA = response.data.total;
				currentFDAPage = page;
				hasMoreFDA = fdaCatalog.length < response.data.total;
			}
		} catch (error) {
			console.error('Error cargando catálogo FDA:', error);
		} finally {
			isLoadingFDA = false;
		}
	}

	function selectFDA(item: FDACatalog) {
		formData.fda_key = item.fda_key || '';
		showFDADialog = false;
		searchFDA = '';
	}

	async function openCartaPorteSearch() {
		showCartaPorteDialog = true;
		searchCartaPorte = '';
	}

	// Función de validación
	function validateForm(): boolean {
		const errors: Record<string, string> = {};

		if (!formData.class_code?.trim()) {
			errors.class_code = 'El código de clase es obligatorio';
		}

		if (!formData.description_es?.trim()) {
			errors.description_es = 'La descripción en español es obligatoria';
		}

		if (!formData.material_key?.trim()) {
			errors.material_key = 'El tipo de activo fijo es obligatorio';
		}

		if (!formData.unit_of_measure?.trim()) {
			errors.unit_of_measure = 'La unidad de medida comercial es obligatoria';
		}

		if (!formData.fraction?.trim()) {
			errors.fraction = 'La fracción arancelaria es obligatoria';
		}

		validationErrors = errors;
		return Object.keys(errors).length === 0;
	}

	// Validar campo individual (para validación en blur)
	function validateField(fieldName: string) {
		// Bloquear validación repetida si: a) no se ha intentado guardar o b) está guardando
		if (!showErrors || isSubmitting) return; 

		const errors = { ...validationErrors };

		switch (fieldName) {
			case 'class_code':
				if (!formData.class_code?.trim()) {
					errors.class_code = 'El código de clase es obligatorio';
				} else {
					delete errors.class_code;
				}
				break;
			case 'description_es':
				if (!formData.description_es?.trim()) {
					errors.description_es = 'La descripción en español es obligatoria';
				} else {
					delete errors.description_es;
				}
				break;
			case 'material_key':
				if (!formData.material_key?.trim()) {
					errors.material_key = 'El tipo de activo fijo es obligatorio';
				} else {
					delete errors.material_key;
				}
				break;
			case 'unit_of_measure':
				if (!formData.unit_of_measure?.trim()) {
					errors.unit_of_measure = 'La unidad de medida comercial es obligatoria';
				} else {
					delete errors.unit_of_measure;
				}
				break;
			case 'fraction':
				if (!formData.fraction?.trim()) {
					errors.fraction = 'La fracción arancelaria es obligatoria';
				} else {
					delete errors.fraction;
				}
				break;
		}

		validationErrors = errors;
	}

	async function handleSave() {
		// Validar formulario
		if (!validateForm()) {
			showErrors = true;
			toast.error('Por favor, complete todos los campos obligatorios');
			return;
		}

		// Activar bandera the submitting para que no se validen inputs al azar en el blur
		isSubmitting = true;
		
		// Tomamos una copia muerta de los datos actuales
		const dataToSave = $state.snapshot(formData);

		try {
			// Ejecutamos el onSave pasándole la copia. Await en caso de que devuelva promesa.
			if (onSave) {
				await onSave(dataToSave);
			}
		} finally {
			// Liberar el estado de subida solo después de que acabe todo el flujo
			isSubmitting = false;
		}
	}

	function handleCancel() {
		if (onCancel) {
			onCancel();
		}
	}

	// Escuchar el evento de guardado del padre
	import { onDestroy } from 'svelte';
	
	if (typeof document !== 'undefined') {
		document.addEventListener('save-form', handleSave);
	}

	onDestroy(() => {
		if (typeof document !== 'undefined') {
			document.removeEventListener('save-form', handleSave);
		}
	});
</script>

<div class="space-y-3">
	<!-- Clase y Requiere Revisión Física -->
	<div class="flex items-end gap-4">
		<div class="flex-1 space-y-2">
			<Label for="class_code" class="font-bold">
				Clase: <span class="text-red-500">*</span>
			</Label>
			<Input
				id="class_code"
				bind:value={formData.class_code}
				placeholder="Ingrese código de clase"
				class="uppercase {validationErrors.class_code
					? 'border-red-500 focus-visible:ring-red-500'
					: ''}"
				maxlength={8}
				oninput={() => {
					if (validationErrors.class_code) {
						const errors = { ...validationErrors };
						delete errors.class_code;
						validationErrors = errors;
					}
				}}
				onblur={() => validateField('class_code')}
			/>
			{#if validationErrors.class_code}
				<p class="mt-1 text-sm text-red-500">{validationErrors.class_code}</p>
			{/if}
		</div>

		<div class="space-y-2">
			<Label for="material_key" class="font-bold">
				Tipo de Activo Fijo: <span class="text-red-500">*</span>
			</Label>
			<div class="flex items-center gap-2">
				<Input
					id="material_key"
					bind:value={formData.material_key}
					placeholder="Código"
					class="flex-1 uppercase {validationErrors.material_key
						? 'border-red-500 focus-visible:ring-red-500'
						: ''}"
					maxlength={10}
					onblur={handleMaterialBlur}
				/>
				<Button type="button" variant="outline" size="icon" onclick={openMaterialSearch}>
					<Folder class="h-4 w-4" />
				</Button>
				<span class="cursor-pointer text-sm text-blue-600 hover:underline">
					{formData.material_description || ''}
				</span>
			</div>
			{#if validationErrors.material_key}
				<p class="mt-1 text-sm text-red-500">{validationErrors.material_key}</p>
			{/if}
		</div>
	</div>

	<!-- Descripciones -->
	<div class="space-y-4">
		<div class="space-y-2">
			<Label for="description_es" class="font-bold">
				Descripción en Español: <span class="text-red-500">*</span>
			</Label>
			<Input
				id="description_es"
				bind:value={formData.description_es}
				placeholder="Descripción en español"
				class={validationErrors.description_es ? 'border-red-500 focus-visible:ring-red-500' : ''}
				maxlength={500}
				onblur={() => validateField('description_es')}
			/>
			{#if validationErrors.description_es}
				<p class="mt-1 text-sm text-red-500">{validationErrors.description_es}</p>
			{/if}
		</div>

		<div class="space-y-2">
			<Label for="description_en">Descripción en Inglés:</Label>
			<Input
				id="description_en"
				bind:value={formData.description_en}
				placeholder="Descripción en inglés"
				maxlength={500}
			/>
		</div>
	</div>

	<!-- U.M. Comercial y Fracción Arancelaria -->
	<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
		<div class="space-y-2">
			<Label for="unit_of_measure" class="font-bold">
				U.M. Comercial: <span class="text-red-500">*</span>
			</Label>
			<div class="flex flex-wrap items-center gap-2">
				<Input
					id="unit_of_measure"
					bind:value={formData.unit_of_measure}
					placeholder="UM"
					class="min-w-[5rem] flex-1 uppercase {validationErrors.unit_of_measure
						? 'border-red-500 focus-visible:ring-red-500'
						: ''}"
					maxlength={5}
					onblur={handleUnitBlur}
				/>
				<Button type="button" variant="outline" size="icon" onclick={openUnitOfMeasureSearch}>
					<Folder class="h-4 w-4" />
				</Button>
				<span class="cursor-pointer text-sm text-blue-600 hover:underline">
					{formData.unit_of_measure_description || ''}
				</span>
				<span class="text-sm text-muted-foreground">
					Clave U.M.A:
					<span class="font-mono text-blue-600">{formData.unit_measure_key || '—'}</span>
				</span>
			</div>
			{#if validationErrors.unit_of_measure}
				<p class="mt-1 text-sm text-red-500">{validationErrors.unit_of_measure}</p>
			{/if}
		</div>

		<div class="space-y-2">
			<Label for="fraction" class="font-bold">
				Fracción Arancelaria: <span class="text-red-500">*</span>
			</Label>
			<div class="flex flex-wrap items-center gap-2">
				<Input
					id="fraction"
					value={formatMexTariffDigitsForDisplay(formData.fraction)}
					placeholder="Fracción"
					readonly
					class="min-w-[8rem] flex-1 cursor-pointer bg-muted/30 font-mono {validationErrors.fraction
						? 'border-red-500 focus-visible:ring-red-500'
						: ''}"
					onclick={openFractionSearch}
					onblur={() => validateField('fraction')}
				/>
				<Button type="button" variant="outline" size="icon" onclick={openFractionSearch}>
					<Folder class="h-4 w-4" />
				</Button>
			</div>
			<div class="flex flex-wrap gap-4 text-sm">
				<span class="text-muted-foreground"
					>U.M.T: <span class="font-mono text-blue-600">{formData.fraction_umt || '—'}</span></span
				>
				<span class="text-muted-foreground"
					>Clave U.M.A:
					<span class="font-mono text-blue-600">{formData.fraction_uma_key || '—'}</span></span
				>
			</div>
			{#if validationErrors.fraction}
				<p class="mt-1 text-sm text-red-500">{validationErrors.fraction}</p>
			{/if}
		</div>
	</div>

	<!-- Fracción Americana (con AdValorem / Tasa fija como en legacy) -->
	<div class="space-y-2">
		<Label for="us_fraction">Fracción Americana:</Label>
		<div class="flex flex-wrap items-center gap-2">
			<Input
				id="us_fraction"
				bind:value={formData.us_fraction}
				placeholder="0000.00.00.00"
				class="min-w-[10rem] flex-1 font-mono tracking-wider"
				maxlength={13}
				oninput={formatUSFraction}
			/>
			<Button type="button" variant="outline" size="icon" onclick={openUSFractionSearch}>
				<Folder class="h-4 w-4" />
			</Button>
			<span class="text-sm text-blue-600"
				>AdValorem: {formData.us_fraction_ad_valorem || '0.00'}</span
			>
			<span class="text-sm text-blue-600"
				>Tasa Fija: {formData.us_fraction_fixed_rate || '0.00000000'}</span
			>
		</div>
	</div>

	<!-- Tasa depreciación y ECCN (misma fila que en pantalla legacy) -->
	<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
		<div class="space-y-2">
			<Label for="annual_depreciation_rate">Tasa Anual de Depreciación:</Label>
			<div class="flex items-center gap-2">
				<Input
					id="annual_depreciation_rate"
					type="number"
					bind:value={formData.annual_depreciation_rate}
					placeholder="0.00"
					class="flex-1"
					step="0.01"
				/>
				<span class="text-sm">%</span>
				<Button type="button" variant="outline" size="icon" onclick={openDepreciationSearch}>
					<Folder class="h-4 w-4" />
				</Button>
			</div>
		</div>

		<div class="space-y-2">
			<Label for="eccn_code">ECCN:</Label>
			<Input
				id="eccn_code"
				bind:value={formData.eccn_code}
				placeholder="Código ECCN"
				class="w-full uppercase"
				maxlength={20}
			/>
		</div>
	</div>

	<!-- Clave FDA -->
	<div class="space-y-2">
		<Label for="fda_key">Clave FDA:</Label>
		<div class="flex items-center gap-2">
			<Input id="fda_key" bind:value={formData.fda_key} placeholder="Clave FDA" class="flex-1" />
			<Button type="button" variant="outline" size="icon" onclick={openFDASearch}>
				<Folder class="h-4 w-4" />
			</Button>
		</div>
	</div>

	<!-- Fracción exenta de IVA (Sí / No + código opcional máx. 4) -->
	<div class="space-y-2">
		<Label class="font-bold">Fracción exenta de IVA</Label>
		<div class="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-6">
			<RadioGroup.Root
				value={ivaExemptChoice}
				onValueChange={(v) => setIvaExemptChoice(v as 'no' | 'yes')}
				class="flex flex-wrap gap-6"
			>
				<div class="flex cursor-pointer items-center gap-2">
					<RadioGroup.Item value="no" id="iva-no" class="h-4 w-4 border-primary" />
					<Label for="iva-no" class="cursor-pointer font-normal">No</Label>
				</div>
				<div class="flex cursor-pointer items-center gap-2">
					<RadioGroup.Item value="yes" id="iva-yes" class="h-4 w-4 border-primary" />
					<Label for="iva-yes" class="cursor-pointer font-normal">Sí</Label>
				</div>
			</RadioGroup.Root>
			{#if ivaExemptChoice === 'yes'}
				<div class="flex max-w-xs flex-1 items-center gap-2">
					<Label for="iva_exempt_code" class="text-muted-foreground shrink-0 text-sm">Código</Label>
					<Input
						id="iva_exempt_code"
						bind:value={formData.iva_exempt_fraction}
						placeholder="Máx. 4"
						class="font-mono uppercase"
						maxlength={4}
					/>
				</div>
			{/if}
		</div>
	</div>

	<!-- Código Carta Porte -->
	<div class="space-y-2">
		<Label for="carta_porte_code">Código Carta Porte:</Label>
		<div class="flex items-center gap-2">
			<Input
				id="carta_porte_code"
				bind:value={formData.carta_porte_code}
				placeholder="Código"
				class="flex-1"
			/>
			<Button type="button" variant="outline" size="icon" onclick={openCartaPorteSearch}>
				<Folder class="h-4 w-4" />
			</Button>
		</div>
	</div>

	<!-- Diálogos -->
	<!-- Dialog: Material Types -->
	<Dialog.Root bind:open={showMaterialDialog}>
		<Dialog.Content class="max-w-2xl">
			<Dialog.Header>
				<Dialog.Title>CATALOGO DE ACTIVO FIJO</Dialog.Title>
			</Dialog.Header>
			<div class="space-y-4">
				<div>
					<Label for="search_material">Buscando:</Label>
					<Input
						id="search_material"
						bind:value={searchMaterial}
						placeholder="Buscar por clave o descripción..."
						class="mt-1"
					/>
				</div>
				<div class="max-h-96 overflow-auto rounded-md border">
					<table class="w-full">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="px-4 py-2 text-left font-semibold">Clave</th>
								<th class="px-4 py-2 text-left font-semibold">Descripción</th>
							</tr>
						</thead>
						<tbody>
							{#each filteredMaterialTypes as material (material.key)}
								<tr
									class="cursor-pointer border-b transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
									onclick={() => selectMaterial(material)}
								>
									<td class="px-4 py-2">{material.key}</td>
									<td class="px-4 py-2">{material.description}</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showMaterialDialog = false)}>Cerrar</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<!-- Dialog: Unidades de Medida -->
	<Dialog.Root bind:open={showUnitDialog}>
		<Dialog.Content class="max-w-4xl">
			<Dialog.Header>
				<Dialog.Title>UNIDADES DE MEDIDA</Dialog.Title>
			</Dialog.Header>
			<div class="space-y-4">
				<div>
					<Label for="search_unit">Buscando:</Label>
					<Input
						id="search_unit"
						bind:value={searchUnit}
						placeholder="Buscar por código o descripción..."
						class="mt-1"
					/>
				</div>
				<div class="max-h-96 overflow-auto rounded-md border">
					<table class="w-full text-sm">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="px-3 py-2 text-left font-semibold">Código</th>
								<th class="px-3 py-2 text-left font-semibold">Descripción</th>
								<th class="px-3 py-2 text-left font-semibold">Description (English)</th>
								<th class="px-3 py-2 text-left font-semibold">Clave Mexicana</th>
							</tr>
						</thead>
						<tbody>
							{#each filteredUnits as unit (unit.code)}
								<tr
									class="cursor-pointer border-b transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
									onclick={() => selectUnit(unit)}
								>
									<td class="px-3 py-2">{unit.code}</td>
									<td class="px-3 py-2">{unit.description}</td>
									<td class="px-3 py-2">{unit.descriptionEnglish}</td>
									<td class="px-3 py-2">{unit.claveMexicana}</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showUnitDialog = false)}>Cerrar</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<!-- Dialog: Buscar fracción arancelaria -->
	<TariffFractionSelector bind:open={showFractionDialog} onSelect={selectFraction} />

	<!-- Dialog: Buscar fracción americana -->
	<Dialog.Root bind:open={showUSFractionDialog}>
		<Dialog.Content class="w-full max-w-4xl">
			<Dialog.Header>
				<Dialog.Title>CATALOGO DE FRACCIONES AMERICANAS</Dialog.Title>
			</Dialog.Header>
			<div class="space-y-4">
				<div>
					<Label for="search_us_fraction">Buscando:</Label>
					<Input
						id="search_us_fraction"
						bind:value={searchUSFraction}
						placeholder="Buscar por fracción, descripción..."
						class="mt-1"
					/>
				</div>
				<div class="max-h-[600px] overflow-x-auto overflow-y-auto rounded-md border">
					<table class="w-full">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="px-4 py-2 text-left font-semibold whitespace-nowrap">Clave</th>
								<th class="px-4 py-2 text-left font-semibold whitespace-nowrap">Fracción</th>
								<th class="px-4 py-2 text-left font-semibold whitespace-nowrap">Ad valorem</th>
								<th class="px-4 py-2 text-left font-semibold whitespace-nowrap">Costo Fijo</th>
								<th class="px-4 py-2 text-left font-semibold whitespace-nowrap">Descripción</th>
							</tr>
						</thead>
						<tbody>
							{#each usTariffFractions as fraction (fraction.id)}
								<tr
									class="cursor-pointer border-b transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
									onclick={() => selectUSFraction(fraction)}
								>
									<td class="px-4 py-2 whitespace-nowrap">{fraction.code || '—'}</td>
									<td class="px-4 py-2 whitespace-nowrap">{fraction.fraction || '—'}</td>
									<td class="px-4 py-2 whitespace-nowrap">{fraction.adv_impo ?? '—'}</td>
									<td class="px-4 py-2 whitespace-nowrap">{fraction.adv_expo ?? '—'}</td>
									<td class="px-4 py-2">{fraction.description || ''}</td>
								</tr>
							{:else}
								<tr>
									<td colspan="5" class="px-4 py-8 text-center text-muted-foreground">
										{#if isLoadingUSFractions}
											Cargando fracciones...
										{:else}
											No hay fracciones disponibles
										{/if}
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showUSFractionDialog = false)}>Cerrar</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<!-- Dialog: Buscar depreciación -->
	<Dialog.Root bind:open={showDepreciationDialog}>
		<Dialog.Content class="w-full max-w-4xl">
			<Dialog.Header>
				<Dialog.Title>CATALOGO DE DEPRECIACION</Dialog.Title>
			</Dialog.Header>
			<div class="space-y-4">
				<div>
					<Label for="search_depreciation">Buscando:</Label>
					<Input
						id="search_depreciation"
						bind:value={searchDepreciation}
						placeholder="Buscar por fracción o descripción..."
						class="mt-1"
					/>
				</div>
				<div class="max-h-[600px] overflow-x-auto overflow-y-auto rounded-md border">
					<table class="w-full">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="px-4 py-2 text-left font-semibold">Fracción</th>
								<th class="px-4 py-2 text-left font-semibold">Descripción</th>
								<th class="px-4 py-2 text-left font-semibold">% Depreciación</th>
							</tr>
						</thead>
						<tbody>
							{#each depreciationCatalog as item (item.id)}
								<tr
									class="cursor-pointer border-b transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
									onclick={() => selectDepreciation(item)}
								>
									<td class="px-4 py-2">{item.fraction}</td>
									<td class="px-4 py-2">{item.description}</td>
									<td class="px-4 py-2">{item.depreciation_rate}%</td>
								</tr>
							{:else}
								<tr>
									<td colspan="3" class="px-4 py-8 text-center text-muted-foreground">
										{#if isLoadingDepreciation}
											Cargando...
										{:else}
											No hay registros disponibles
										{/if}
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showDepreciationDialog = false)}>Cerrar</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<!-- Dialog: Buscar FDA -->
	<Dialog.Root bind:open={showFDADialog}>
		<Dialog.Content class="w-full max-w-4xl">
			<Dialog.Header>
				<Dialog.Title>CATALOGO FDA</Dialog.Title>
			</Dialog.Header>
			<div class="space-y-4">
				<div>
					<Label for="search_fda">Buscando:</Label>
					<Input
						id="search_fda"
						bind:value={searchFDA}
						placeholder="Buscar por clave FDA o descripción..."
						class="mt-1"
					/>
				</div>
				<div class="max-h-[600px] overflow-x-auto overflow-y-auto rounded-md border">
					<table class="w-full">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="px-4 py-2 text-left font-semibold">Clave FDA</th>
								<th class="px-4 py-2 text-left font-semibold">Descripción</th>
							</tr>
						</thead>
						<tbody>
							{#each fdaCatalog as item (item.id)}
								<tr
									class="cursor-pointer border-b transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
									onclick={() => selectFDA(item)}
								>
									<td class="px-4 py-2">{item.fda_key}</td>
									<td class="px-4 py-2">{item.description}</td>
								</tr>
							{:else}
								<tr>
									<td colspan="2" class="px-4 py-8 text-center text-muted-foreground">
										{#if isLoadingFDA}
											Cargando...
										{:else}
											No hay registros disponibles
										{/if}
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showFDADialog = false)}>Cerrar</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<!-- Dialog: Buscar Carta Porte -->
	<Dialog.Root bind:open={showCartaPorteDialog}>
		<Dialog.Content class="w-full max-w-4xl">
			<Dialog.Header>
				<Dialog.Title>CATALOGO DE CARTA PORTE</Dialog.Title>
			</Dialog.Header>
			<div class="space-y-4">
				<div>
					<Label for="search_carta_porte">Buscando:</Label>
					<Input
						id="search_carta_porte"
						bind:value={searchCartaPorte}
						placeholder="Buscar por código..."
						class="mt-1"
					/>
				</div>
				<div class="max-h-[600px] overflow-x-auto overflow-y-auto rounded-md border">
					<table class="w-full">
						<thead class="border-b bg-white text-gray-900 dark:bg-black dark:text-white">
							<tr>
								<th class="px-4 py-2 text-left font-semibold">Código</th>
								<th class="px-4 py-2 text-left font-semibold">Descripción</th>
							</tr>
						</thead>
						<tbody>
							{#each cartaPorteCatalog as item (item.id)}
								<tr
									class="cursor-pointer border-b transition-colors hover:bg-gray-100 dark:hover:bg-gray-700"
									onclick={() => {
										formData.carta_porte_code = item.code;
										showCartaPorteDialog = false;
									}}
								>
									<td class="px-4 py-2">{item.code}</td>
									<td class="px-4 py-2">{item.description}</td>
								</tr>
							{:else}
								<tr>
									<td colspan="2" class="px-4 py-8 text-center text-muted-foreground">
										No hay registros disponibles
									</td>
								</tr>
							{/each}
						</tbody>
					</table>
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showCartaPorteDialog = false)}>Cerrar</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>
</div>
