<script lang="ts">
	import { goto } from '$app/navigation';

	// UI Components
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import { Textarea } from '$lib/components/ui/textarea';
	import * as Tabs from '$lib/components/ui/tabs';
	import * as Card from '$lib/components/ui/card';
	import * as Select from '$lib/components/ui/select';
	import { Switch } from '$lib/components/ui/switch';
	import { Separator } from '$lib/components/ui/separator';
	import { Badge } from '$lib/components/ui/badge';
	import { Checkbox } from '$lib/components/ui/checkbox';
	import * as Dialog from '$lib/components/ui/dialog';

	// Iconos
	import {
		ArrowLeft,
		LoaderCircle,
		Save,
		Package,
		DollarSign,
		FileText,
		Settings,
		Image as ImageIcon,
		FolderSearch,
		CheckCircle2,
		XCircle,
		Tag,
		Layers,
		Scale,
		Info,
		Briefcase,
		ShieldCheck,
		Globe,
		Calculator,
		Shirt,
		ClipboardList,
		Trash2,
		PlusSquare,
		UserMinus,
		PlusIcon,
		FileEdit,
		FileSpreadsheet,
		HelpCircle,
		Database
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';

	// Stores & APIs
	import { companyStore } from '$lib/stores/company.svelte';
	import { partsApi } from '$lib/api/dashboard/a76/parts';
	import { classesApi } from '$lib/api/dashboard/a76/classes';
	import { materialTypesApi } from '$lib/api/dashboard/a76/material-types';
	import { countriesApi } from '$lib/api/dashboard/reference_data/countries';

	// Modales
	import {
		getTariffFractions,
		type TariffFraction
	} from '$lib/api/dashboard/a76/general_catalogs/tariff-fractions';
	import {
		getSitarTLCS,
		getSitarPROSEC,
		getSitarALADI,
		type SitarTLCS,
		type SitarPROSEC,
		type SitarALADI
	} from '$lib/api/dashboard/a76/sitar';
	import {
		buildMexTariffDigitsFromCatalogRow,
		formatMexTariffDigitsForDisplay,
		normalizeMexTariffDigitsStored,
		splitMexTariffDigitsForSitar
	} from '$lib/utils/mexican-tariff-fraction';
	import ClientSelectorDialog from '$lib/components/dashboard/goods/modales/client-selector-dialog.svelte';
	import ClassSelectorDialog from '$lib/components/dashboard/goods/parts/class-selector-dialog.svelte';
	import MaterialTypeSelectorDialog from '$lib/components/dashboard/goods/modales/material-type-selector-dialog.svelte';
	import UnitMeasureSelectorDialog from '$lib/components/dashboard/goods/modales/unit-measure-dialog.svelte';
	import CountrySelectorDialog from '$lib/components/dashboard/goods/modales/country-selector-dialog.svelte';
	import FractionSelectorDialog from '$lib/components/dashboard/goods/modales/fraction-selector-dialog.svelte';
	import USFractionSelectorDialog from '$lib/components/dashboard/goods/modales/us-fraction-selector-dialog.svelte';
	import SectorSelectorDialog from '$lib/components/dashboard/shared/modals/sector-selector-dialog.svelte';
	import SubstitutePartSelectorDialog from './SubstitutePartSelectorDialog.svelte';
	import Fraction9801SelectorDialog from './Fraction9801SelectorDialog.svelte';
	import TextileProviderSelectorDialog from './TextileProviderSelectorDialog.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosFormularioMercancia } from '$lib/config/shortcuts/dashboard/goods/edit';
	import { sectorsApi, type Sector } from '$lib/api/dashboard/reference_data/sectors';

	// --- PROPS ---
	let {
		partId = null,
		formType = $bindable('fa')
	}: { partId?: number | null; formType?: 'inv' | 'fa' | 'both' } = $props();

	// --- LÓGICA DE ESTADO ---
	let isEdit = $derived(!!partId);
	let title = $derived(isEdit ? 'Editar Parte' : 'Nueva Parte');

	let loading = $state(false);
	let error = $state<string | null>(null);
	let activeTab = $state('general');

	// Solo dígitos y un único punto decimal — sin e/E, sin guiones, sin nada más.
	const ONLY_DECIMAL_RE = /^[0-9]*\.?[0-9]*$/;

	function sanitizeToDecimal(raw: string): string {
		const digits = raw.replace(/[^0-9.]/g, '');
		const dot = digits.indexOf('.');
		if (dot === -1) return digits;
		return digits.slice(0, dot + 1) + digits.slice(dot + 1).replace(/\./g, '');
	}

	function decimalKeydown(e: KeyboardEvent) {
		if (e.ctrlKey || e.metaKey) return;
		const nav = new Set(['Backspace','Delete','ArrowLeft','ArrowRight','Home','End','Tab','Enter']);
		if (nav.has(e.key)) return;
		if (!/^[0-9.]$/.test(e.key)) { e.preventDefault(); return; }
		if (e.key === '.') {
			const el = e.target as HTMLInputElement;
			const sel = el.value.slice(el.selectionStart ?? 0, el.selectionEnd ?? 0);
			if (el.value.includes('.') && !sel.includes('.')) e.preventDefault();
		}
	}

	function decimalBeforeInput(e: InputEvent) {
		const t = e.inputType ?? '';
		if (t.startsWith('delete') || t.startsWith('history')) return;
		const data = e.data ?? '';
		if (!data) return;
		if (!ONLY_DECIMAL_RE.test(data.replace(/[^0-9.]/g, ''))) { e.preventDefault(); return; }
		const el = e.target as HTMLInputElement;
		const v = el.value ?? '';
		const s = el.selectionStart ?? v.length;
		const en = el.selectionEnd ?? v.length;
		const next = v.slice(0, s) + data + v.slice(en);
		if (!ONLY_DECIMAL_RE.test(next)) e.preventDefault();
	}

	function decimalInput(e: Event, set: (n: number) => void) {
		const el = e.target as HTMLInputElement;
		const clean = sanitizeToDecimal(el.value ?? '');
		if (clean !== el.value) {
			const pos = el.selectionStart ?? clean.length;
			el.value = clean;
			el.setSelectionRange(pos, pos);
		}
		set(clean === '' || clean === '.' ? 0 : parseFloat(clean));
	}

	function decimalPaste(e: ClipboardEvent) {
		e.preventDefault();
		const el = e.target as HTMLInputElement;
		const pasted = sanitizeToDecimal(e.clipboardData?.getData('text') ?? '');
		const v = el.value ?? '';
		const s = el.selectionStart ?? v.length;
		const en = el.selectionEnd ?? v.length;
		el.value = sanitizeToDecimal(v.slice(0, s) + pasted + v.slice(en));
		el.dispatchEvent(new Event('input', { bubbles: true }));
	}

	function openOnEnterOrSpace(event: KeyboardEvent, action: () => void) {
		if (event.key === 'Enter' || event.key === ' ') {
			event.preventDefault();
			action();
		}
	}

	// Estado Modales
	let showClientModal = $state(false);
	let showClassModal = $state(false);
	let showMaterialModal = $state(false);
	let showUOMModal = $state(false);
	let showAltUOMModal = $state(false);
	let showCountryModal = $state(false);
	let showFractionModal = $state(false);
	let showUSFractionModal = $state(false);
	let showSectorModal = $state(false);
	let showSubstitutePartModal = $state(false);
	let showFraction9801Modal = $state(false);
	let showTextileProviderModal = $state(false);
	let showNonDischargeDialog = $state(false);

	// Descripciones Visuales
	let selectedClassDesc = $state('');
	let selectedCurrencyName = $state('');
	let selectedCountryName = $state('');
	let selectedMaterialDesc = $state('');
	let selectedSubstitutePartNumber = $state('');
	let selectedFraction9801 = $state('');
	let selectedTextileProviderName = $state('');
	let selectedSectorDesc = $state('');
	let currentTariffDetails = $state<TariffFraction | null>(null);
	let sitarTLCSData = $state<SitarTLCS[]>([]);
	let sitarPROSECData = $state<SitarPROSEC[]>([]);
	let sitarALADIData = $state<SitarALADI[]>([]);
	let activeCountryTab = $state('descripcion');
	let isLoadingSitar = $state(false);

	// Relaciones (BOM / Paises)
	let relationType = $state<'bom' | 'paises'>('bom');
	let bomData = $state<any[]>([]);
	let countriesData = $state<any[]>([]);
	let relationData = $derived(relationType === 'bom' ? bomData : countriesData);

	let showBOMDialog = $state(false);
	let showCountryRelDialog = $state(false);
	let currentEditIndex = $state<number | null>(null);
	let tempRelationItem = $state<any>({});
	let tempNonDischargeItem = $state<{ client_id: number; name: string; is_active: boolean }>({
		client_id: 0,
		name: '',
		is_active: true
	});
	let modalContext = $state<
		| 'main'
		| 'bom_uom'
		| 'rel_country'
		| 'rel_frac'
		| 'us_fraction_alt'
		| 'scrap_part'
		| 'waste_part'
		| 'scrap_exp_frac'
		| 'scrap_us_frac'
		| 'eq_uom_1'
		| 'eq_uom_2'
		| 'aux_uom'
		| 'non_discharge'
		| 'bom_component'
	>('main');

	function handleAddRelation() {
		currentEditIndex = null;

		// Validar que la parte maestra ya esté guardada antes de agregar relaciones (BOM o Países)
		if (!formData.id || !formData.part_number) {
			const typeLabel = relationType === 'bom' ? 'un BOM' : 'un País';
			toast.error('Acción no permitida', {
				description: `Debe guardar el registro de la parte principal antes de intentar agregarle ${typeLabel}.`
			});
			return;
		}

		if (relationType === 'bom') {
			// Validar que no exista más de un BOM por parte
			if (bomData.length > 0) {
				toast.error('Límite de BOM alcanzado', {
					description: 'Esta parte ya tiene un BOM configurado. Solo puedes editar o eliminarlo.'
				});
				return;
			}
			tempRelationItem = {
				component_part_id: 0,
				component_part_number: '',
				quantity: 1,
				uom_code: '',
				procedure_type: 'TEMPORAL',
				is_percentage: true,
				raw_material: 0,
				waste: 0,
				merma: 0
			};
			showBOMDialog = true;
		} else {
			tempRelationItem = {
				country_code: '',
				fraction: '',
				origin_type: 'P',
				preference: 'GENERAL',
				has_certificate: false,
				certificate_number: '',
				end_date: '',
				previous_fractions_7m: false,
				omission_import: false,
				omission_export: false,
				import_percentage: 0,
				export_percentage: 0,
				sector: ''
			};
			showCountryRelDialog = true;
		}
	}

	function handleEditRelation(index: number) {
		currentEditIndex = index;
		const source = relationType === 'bom' ? bomData : countriesData;
		tempRelationItem = { ...source[index] };
		if (relationType === 'bom') {
			showBOMDialog = true;
			// Si no hay detalles del componente cargados, obtenerlos del API
			if (
				tempRelationItem.component_part_id &&
				!tempRelationItem._component_details &&
				companyStore.activeCompany?.id
			) {
				const loadComponentDetails = async () => {
					try {
						const res = await partsApi.get(
							tempRelationItem.component_part_id,
							companyStore.activeCompany!.id
						);
						if (res.data) {
							tempRelationItem._component_details = {
								part_class: res.data.part_class,
								uom_class: res.data.unit_of_measure,
								part_type: res.data.inv_data?.part_type,
								unit_weight: res.data.unit_weight,
								weight_type: res.data.weight_type,
								unit_cost: res.data.unit_cost,
								currency_key: res.data.currency_key
							};
						}
					} catch (e) {
						console.error('Error loading component details:', e);
					}
				};
				loadComponentDetails();
			}
		} else {
			showCountryRelDialog = true;
		}
	}

	function handleDeleteRelation(index: number) {
		if (relationType === 'bom') {
			bomData = bomData.filter((_: any, i: number) => i !== index);
		} else {
			countriesData = countriesData.filter((_: any, i: number) => i !== index);
		}
	}

	function saveRelationItem() {
		if (relationType === 'bom') {
			// Validar que se haya seleccionado una parte componente
			if (!tempRelationItem.component_part_id || tempRelationItem.component_part_id === 0) {
				toast.error('Error', { description: 'Debe seleccionar un componente para el BOM' });
				return;
			}
			if (!tempRelationItem.uom_code) {
				toast.error('Error', { description: 'Debe seleccionar una unidad de medida' });
				return;
			}
			if (!tempRelationItem.quantity || tempRelationItem.quantity <= 0) {
				toast.error('Error', { description: 'La cantidad debe ser mayor a cero' });
				return;
			}

			if (currentEditIndex !== null) {
				bomData[currentEditIndex] = { ...tempRelationItem };
			} else {
				bomData = [...bomData, { ...tempRelationItem }];
			}
			showBOMDialog = false;
		} else {
			let itemToSave = { ...tempRelationItem };
			if (itemToSave.end_date === '') {
				itemToSave.end_date = null;
			}
			if (currentEditIndex !== null) {
				countriesData[currentEditIndex] = itemToSave;
			} else {
				countriesData = [...countriesData, itemToSave];
			}
			showCountryRelDialog = false;
		}
	}

	// Handlers Clientes que no descargan
	function handleAddNonDischarge() {
		currentEditIndex = null;
		tempNonDischargeItem = { client_id: 0, name: '', is_active: true };
		showNonDischargeDialog = true;
	}

	function handleEditNonDischarge(index: number) {
		currentEditIndex = index;
		tempNonDischargeItem = { ...formData.non_discharge_clients[index] };
		showNonDischargeDialog = true;
	}

	function handleDeleteNonDischarge(index: number) {
		formData.non_discharge_clients = formData.non_discharge_clients.filter(
			(_: any, i: number) => i !== index
		);
	}

	function saveNonDischargeItem() {
		if (currentEditIndex !== null) {
			formData.non_discharge_clients[currentEditIndex] = { ...tempNonDischargeItem };
		} else {
			formData.non_discharge_clients = [
				...formData.non_discharge_clients,
				{ ...tempNonDischargeItem }
			];
		}
		showNonDischargeDialog = false;
	}

	// Estado Formulario
	let formData = $state({
		id: 0,
		part_number: '',
		assigned_client: '',
		description_spanish: '',
		description_english: '',
		part_class: '',
		material_type: '',
		unit_of_measure: '',
		unit_weight: 0,
		weight_type: 'KG',
		unit_cost: 0,
		currency_type: 'EX',
		currency_key: 'USD' as string | null,
		added_value: 0,
		value_added_type: 'NA',
		us_fraction: '',
		supplier: '',
		fcc_key: '',
		part_photo: '',
		fda_key: '',
		commercial_part_number: '',
		alternate_unit_measure: '',
		fraction: '',
		eccn: '',
		license_code: '',
		export_code: '',
		exclusion_symbol: '',
		is_active: true,
		// --- CAMPOS ESPECIFICOS DE FA (Activos Fijos) ---
		origin_country: 'MEX',
		sector: '',
		fraction_type: '',
		// --- CAMPOS ESPECIFICOS DE INV (Inventarios) ---
		part_type: '',
		reference_number: '',
		flex_reference_number: '',
		equivalent_uom: '',
		conversion_factor: 0,
		stock_uom: '',
		alternate_uom: '',
		conversion_uom: '',
		supplier_code: '',
		is_textile: false,
		bom_version: 0,
		is_repair: 'N',
		is_hazardous: 'N',
		emergency_number: '',
		danger_class: '',
		packaging_group: '',
		// Campos solicitados recientemente
		substitute_part: '',
		complementary_part: '',
		preference_part: '',
		use_alternate_quantity: false,
		un_number: '',
		shipping_name: '',
		hazard_notes: '',
		repair_unit_cost: 0,
		repair_added_value: 0,
		fraction_9801: '',
		immex_type: '',
		disable_movements: false,
		pga_program_code: '',
		// Fin campos nuevos
		width: '',
		thickness: '',
		specification: '',
		total_value: 0,
		direct_labor: 0,
		general_expenses: 0,
		total_expenses: 0,
		depreciation: 0,
		tooling: 0,
		material_consumed: 0,
		profit: 0,
		us_fraction_alt: '',
		ca_fraction: '',
		ad_valorem_us: 0,
		nafta_result: '',
		nafta_percentage: 0,
		dta: '',
		dtb: '',
		dtg: '',
		// Campos Opcionales 2 (Nuevos solicitados)
		usmca_fraction: '',
		scrap_part_number: '',
		waste_part_number: '',
		scrap_description_en: '',
		scrap_description_es: '',
		scrap_export_fraction: '',
		scrap_us_fraction: '',
		equivalent_uom_2: '',
		conversion_factor_2: 0,
		has_auxiliary: false,
		auxiliary_uom: '',
		auxiliary_conversion: 0,
		auxiliary_unit_cost: 0,
		// Nuevos campos finales
		mex_packing: 0,
		sales_order: '',
		use_rule_8: false,
		non_discharge_clients: [] as { client_id: number; name: string; is_active: boolean }[]
	});

	// --- CARGA DE DATOS ---
	$effect(() => {
		if (companyStore.activeCompany?.id && partId) {
			loadPartData(partId, companyStore.activeCompany.id);
		}
	});

	async function loadPartData(id: number, companyId: number) {
		loading = true;
		try {
			const response = await partsApi.get(id, companyId);
			if (response.data) {
				const d = response.data;
				formData = {
					id: d.id,
					part_number: d.part_number,
					description_spanish: d.description_spanish || '',
					description_english: d.description_english || '',
					part_class: d.part_class || '',
					material_type: d.inv_data?.material_type || '',
					origin_country: d.inv_data?.origin_country || d.fa_data?.origin_country || 'MEX',
					unit_of_measure: d.unit_of_measure || '',
					fraction: normalizeMexTariffDigitsStored(d.fraction || ''),
					us_fraction: d.us_fraction || '',
					unit_weight: Number(d.unit_weight) || 0,
					weight_type: d.weight_type || 'KG',
					supplier: d.inv_data?.supplier_code || '',
					fda_key: d.fda_key || '',
					fcc_key: d.fcc_key || '',
					eccn: d.eccn || '',
					license_code: d.license_code || '',
					export_code: d.export_code || '',
					exclusion_symbol: d.exclusion_symbol || '',
					unit_cost: Number(d.unit_cost) || 0,
					currency_key: d.currency_key || 'USD',
					added_value: Number(d.inv_data?.added_value) || 0,
					value_added_type: d.inv_data?.added_value_type || 'NA',
					commercial_part_number: d.commercial_part_number || '',
					alternate_unit_measure: d.inv_data?.alternate_uom || '',
					part_photo: d.part_photo || '',
					is_active: d.is_active ?? true,
					assigned_client: d.inv_data?.assigned_client || '',
					sector: d.inv_data?.sector || d.fa_data?.sector || '',
					fraction_type: d.inv_data?.fraction_type || d.fa_data?.fraction_type || '',
					currency_type: '', // Initialize to match type

					// SCAI Fields
					part_type: d.inv_data?.part_type || '',
					reference_number: d.inv_data?.reference_number || '',
					flex_reference_number: d.inv_data?.flex_reference_number || '',
					equivalent_uom: d.inv_data?.equivalent_uom || '',
					conversion_factor: Number(d.inv_data?.conversion_factor) || 0,
					stock_uom: d.inv_data?.stock_uom || '',
					alternate_uom: d.inv_data?.alternate_uom || '',
					conversion_uom: d.inv_data?.conversion_uom || '',
					supplier_code: d.inv_data?.supplier_code || '',
					is_textile: d.inv_data?.is_textile === 'S',
					bom_version: d.inv_data?.bom_version || 0,
					is_repair: d.inv_data?.is_repair || 'N',
					is_hazardous: d.inv_data?.is_hazardous || 'N',
					emergency_number: d.inv_data?.emergency_number || '',
					danger_class: d.inv_data?.danger_class || '',
					packaging_group: d.inv_data?.packaging_group || '',

					// Campos solicitados recientemente
					substitute_part: d.inv_data?.substitute_part || '',
					complementary_part: d.inv_data?.complementary_part || '',
					preference_part: d.inv_data?.preference_part || '',
					use_alternate_quantity: d.inv_data?.use_alternate_quantity || false,
					un_number: d.inv_data?.un_number || '',
					shipping_name: d.inv_data?.shipping_name || '',
					hazard_notes: d.inv_data?.hazard_notes || '',
					repair_unit_cost: Number(d.inv_data?.repair_unit_cost) || 0,
					repair_added_value: Number(d.inv_data?.repair_added_value) || 0,
					fraction_9801: normalizeMexTariffDigitsStored(d.inv_data?.fraction_9801 || ''),
					immex_type: d.inv_data?.immex_type || '',
					disable_movements: d.inv_data?.disable_movements || false,
					pga_program_code: d.inv_data?.pga_program_code || '',
					width: d.inv_data?.width || '',
					thickness: d.inv_data?.thickness || '',
					specification: d.inv_data?.specification || '',
					total_value: Number(d.inv_data?.total_value) || 0,
					direct_labor: Number(d.inv_data?.direct_labor) || 0,
					general_expenses: Number(d.inv_data?.general_expenses) || 0,
					total_expenses: Number(d.inv_data?.total_expenses) || 0,
					depreciation: Number(d.inv_data?.depreciation) || 0,
					tooling: Number(d.inv_data?.tooling) || 0,
					material_consumed: Number(d.inv_data?.material_consumed) || 0,
					profit: Number(d.inv_data?.profit) || 0,
					us_fraction_alt: d.inv_data?.us_fraction_alt || '',
					ca_fraction: d.inv_data?.ca_fraction || '',
					ad_valorem_us: Number(d.inv_data?.ad_valorem_us) || 0,
					nafta_result: d.inv_data?.nafta_result || '',
					nafta_percentage: Number(d.inv_data?.nafta_percentage) || 0,
					dta: d.inv_data?.dta || '',
					dtb: d.inv_data?.dtb || '',
					dtg: d.inv_data?.dtg || '',

					// Campos Opcionales 2 y Extensión
					usmca_fraction: d.inv_data?.usmca_fraction || '',
					scrap_part_number: d.inv_data?.scrap_part_number || '',
					waste_part_number: d.inv_data?.waste_part_number || '',
					scrap_description_en: d.inv_data?.scrap_description_en || '',
					scrap_description_es: d.inv_data?.scrap_description_es || '',
					scrap_export_fraction: normalizeMexTariffDigitsStored(
						d.inv_data?.scrap_export_fraction || ''
					),
					scrap_us_fraction: d.inv_data?.scrap_us_fraction || '',
					equivalent_uom_2: d.inv_data?.equivalent_uom_2 || '',
					conversion_factor_2: Number(d.inv_data?.conversion_factor_2) || 0,
					has_auxiliary: d.inv_data?.has_auxiliary || false,
					auxiliary_uom: d.inv_data?.auxiliary_uom || '',
					auxiliary_conversion: Number(d.inv_data?.auxiliary_conversion) || 0,
					auxiliary_unit_cost: Number(d.inv_data?.auxiliary_unit_cost) || 0,
					mex_packing: Number(d.inv_data?.mex_packing) || 0,
					sales_order: d.inv_data?.sales_order || '',
					use_rule_8: d.inv_data?.use_rule_8 || false,
					non_discharge_clients: (d.inv_data?.non_discharge_clients || []) as { client_id: number; name: string; is_active: boolean }[]
				};

				// Relaciones BOM / Paises
				if (d.inv_data) {
					bomData = d.inv_data.bom_items || [];
					countriesData = (d.inv_data.countries || []).map((c: any) => ({
						...c,
						fraction: c.fraction ? normalizeMexTariffDigitsStored(c.fraction) : c.fraction
					}));
				}

				// Detectar tipo automáticamente al editar
				if (d.inv_data && d.fa_data) formType = 'both';
				else if (d.inv_data) formType = 'inv';
				else if (d.fa_data) formType = 'fa';
				// Currency policy on UI: only MXN/USD via Nacional/Extranjera selector
				if (d.currency_key === 'MXN') formData.currency_type = 'NA';
				else formData.currency_type = 'EX';

				if (d.part_class) await fetchClassDesc(d.part_class, companyId);
				if (d.inv_data?.material_type) await fetchMaterialName(d.inv_data.material_type);
				await fetchSectorDesc(formData.sector);
				if (formData.origin_country) await fetchCountryName(formData.origin_country);
			}
		} catch (e) {
			console.error(e);
		} finally {
			loading = false;
		}
	}

	// --- EFECTOS REACTIVOS ---
	$effect(() => {
		// Auto-set currency based on type selection
		if (formData.currency_type === 'NA') {
			formData.currency_key = 'MXN';
			selectedCurrencyName = 'MXN';
		} else if (formData.currency_type === 'EX') {
			formData.currency_key = 'USD';
			selectedCurrencyName = 'USD';
		}
	});

	// --- HELPERS VISUALES ---
	async function fetchClassDesc(code: string, companyId: number) {
		try {
			const res = await classesApi.list({ company_id: companyId, class_code: code });
			const data = (res as any).data || res;
			const list = data.items || data.classes || [];
			if (list.length > 0) {
				const found = list.find((i: any) => i.class_code === code) || list[0];
				selectedClassDesc = found.description_es || found.description_en || '';
			}
		} catch (e) {
			console.error('Error visual clase', e);
		}
	}

	async function fetchMaterialName(key: string) {
		try {
			const res = await materialTypesApi.list(1, 100);
			const data = (res as any).data || res;
			const list = data.items || [];
			const found = list.find((m: any) => m.key === key);
			if (found) selectedMaterialDesc = found.description;
		} catch (e) {
			console.error('Error visual material', e);
		}
	}

	async function fetchSectorDesc(key: string) {
		selectedSectorDesc = '';
		if (!key) return;
		const cId = companyStore.activeCompany?.id;
		if (!cId) return;
		try {
			const res = await sectorsApi.getByKey(key, cId);
			const item = res.data?.items?.[0];
			if (item?.description) selectedSectorDesc = item.description;
		} catch (e) {
			console.error('Error visual sector', e);
		}
	}

	async function fetchCountryName(code: string) {
		selectedCountryName = '';
		if (!code) return;
		try {
			const res = await countriesApi.get(code);
			if (res.data) {
				selectedCountryName = res.data.description_es || res.data.description_en || '';
			}
		} catch (e) {
			console.error('Error fetching country name', e);
		}
	}

	// --- HANDLERS ---
	function handleClientSelect(client: any) {
		if (modalContext === 'non_discharge') {
			tempNonDischargeItem.client_id = client.id;
			tempNonDischargeItem.name = client.name;
		}
		modalContext = 'main';
	}
	function handleClassSelect(item: any) {
		formData.part_class = item.class_code;
		selectedClassDesc = item.description_es || item.description_en || '';

		// En "Nueva Parte", autocompletar UM y fracción desde la clase seleccionada
		// (en edición no se toca para evitar cambios inesperados sobre datos existentes).
		if (!isEdit) {
			formData.unit_of_measure = item.unit_of_measure || '';
			formData.fraction = normalizeMexTariffDigitsStored(item.fraction || '');
		}
	}
	function handleMaterialSelect(item: any) {
		formData.material_type = item.key;
		selectedMaterialDesc = item.description;
	}
	function handleClientClear() {
		if (modalContext === 'non_discharge') {
			tempNonDischargeItem.client_id = 0;
			tempNonDischargeItem.name = '';
		}
		modalContext = 'main';
	}
	function handleClassClear() {
		formData.part_class = '';
		selectedClassDesc = '';
		if (!isEdit) {
			formData.unit_of_measure = '';
			formData.fraction = '';
		}
	}
	function handleMaterialClear() {
		formData.material_type = '';
		selectedMaterialDesc = '';
	}
	function handleUOMSelect(item: any) {
		if (modalContext === 'bom_uom') {
			tempRelationItem.uom_code = item.code;
		} else if (modalContext === 'eq_uom_1') {
			formData.equivalent_uom = item.code;
		} else if (modalContext === 'eq_uom_2') {
			formData.equivalent_uom_2 = item.code;
		} else if (modalContext === 'aux_uom') {
			formData.auxiliary_uom = item.code;
		} else {
			formData.unit_of_measure = item.code;
		}
		modalContext = 'main';
	}
	function handleAltUOMSelect(item: any) {
		formData.alternate_uom = item.code;
	}
	// Currency is driven by formData.currency_type (NA/EX) and auto-mapped to MXN/USD in $effect
	function handleCountrySelect(country: any) {
		const code = country.m3_key || country.country_key;
		if (modalContext === 'rel_country') {
			tempRelationItem.country_code = code;
		} else {
			formData.origin_country = code;
			selectedCountryName = country.description_es;
		}
		modalContext = 'main';
	}
	function handleFractionSelect(item: any) {
		const digits = buildMexTariffDigitsFromCatalogRow(item);
		if (modalContext === 'rel_frac') {
			tempRelationItem.fraction = digits;
		} else if (modalContext === 'scrap_exp_frac') {
			formData.scrap_export_fraction = digits;
		} else {
			formData.fraction = digits;
		}
		modalContext = 'main';
	}
	function handleUSFractionSelect(item: any) {
		if (modalContext === 'us_fraction_alt') {
			formData.us_fraction_alt = item.code;
		} else if (modalContext === 'scrap_us_frac') {
			formData.scrap_us_fraction = item.code;
		} else {
			formData.us_fraction = item.code;
		}
		modalContext = 'main';
	}

	function handleSubstitutePartSelect(part: any) {
		if (modalContext === 'scrap_part') {
			formData.scrap_part_number = part.part_number;
		} else if (modalContext === 'waste_part') {
			formData.waste_part_number = part.part_number;
		} else if (modalContext === 'bom_component') {
			tempRelationItem.component_part_id = part.id;
			tempRelationItem.component_part_number = part.part_number;
			// Default UOM from component if not set
			if (!tempRelationItem.uom_code && part.unit_of_measure) {
				tempRelationItem.uom_code = part.unit_of_measure;
			}
			tempRelationItem._component_details = {
				part_class: part.part_class,
				uom_class: part.unit_of_measure,
				part_type: part.inv_data?.part_type,
				unit_weight: part.unit_weight,
				weight_type: part.weight_type,
				unit_cost: part.unit_cost,
				currency_key: part.currency_key
			};
		} else {
			formData.substitute_part = part.part_number;
			selectedSubstitutePartNumber = part.part_number;
		}
		modalContext = 'main';
	}

	function handleFractionSelect9801(fraction: any) {
		formData.fraction_9801 = buildMexTariffDigitsFromCatalogRow(fraction);
		selectedFraction9801 = formatMexTariffDigitsForDisplay(formData.fraction_9801);
	}

	function handleTextileProviderSelect(provider: any) {
		formData.supplier = provider.rfc;
	}

	function handleSectorSelect(item: Sector) {
		formData.sector = item.key;
		selectedSectorDesc = item.description;
	}

	async function loadCurrentTariffDetails() {
		if (!formData.fraction || !companyStore.activeCompany?.id) return;
		try {
			const { fraccion8, nico2 } = splitMexTariffDigitsForSitar(formData.fraction);
			const res = await getTariffFractions(1, 1, companyStore.activeCompany.id, {
				fraction: fraccion8,
				nico: nico2
			});
			const list = (res as any).data?.items || [];
			if (list.length > 0) {
				currentTariffDetails = list[0];
			}
		} catch (e) {
			console.error('Error fetching tariff details:', e);
		}
	}

	async function loadSitarTabContent(tab: string) {
		const code8 = String(currentTariffDetails?.code ?? '')
			.replace(/\D/g, '')
			.slice(0, 8);
		const fromForm = splitMexTariffDigitsForSitar(formData.fraction).fraccion8;
		const fraccion = (code8 || fromForm).slice(0, 8);
		if (!fraccion) return;

		isLoadingSitar = true;
		try {
			if (tab === 'tlcs') {
				const res = await getSitarTLCS({ fraccion });
				sitarTLCSData = res.data || [];
			} else if (tab === 'prosec') {
				const res = await getSitarPROSEC({ fraccion });
				sitarPROSECData = res.data || [];
			} else if (tab === 'aladi') {
				const res = await getSitarALADI({ fraccion });
				sitarALADIData = res.data || [];
			}
		} catch (e) {
			console.error(`Error fetching SITAR ${tab}:`, e);
		} finally {
			isLoadingSitar = false;
		}
	}

	$effect(() => {
		if (showCountryRelDialog) {
			loadCurrentTariffDetails();
			activeCountryTab = 'descripcion';
			sitarTLCSData = [];
			sitarPROSECData = [];
			sitarALADIData = [];
		}
	});

	$effect(() => {
		if (showCountryRelDialog && activeCountryTab !== 'descripcion') {
			loadSitarTabContent(activeCountryTab);
		}
	});

	// --- SUBMIT ---
	async function handleSubmit() {
		error = null;
		const activeCompanyId = companyStore.activeCompany?.id;
		if (!activeCompanyId) {
			error = 'No hay una compañía activa seleccionada';
			return;
		}
		if (!formData.unit_of_measure) {
			error = 'Debe seleccionar una Unidad de Medida';
			return;
		}

		// Validar BOM items antes de guardar
		if (bomData && bomData.length > 0) {
			for (let i = 0; i < bomData.length; i++) {
				const item = bomData[i];
				if (!item.component_part_id || item.component_part_id === 0) {
					error = `BOM item ${i + 1}: Falta seleccionar el componente`;
					return;
				}
				if (!item.uom_code) {
					error = `BOM item ${i + 1}: Falta la unidad de medida`;
					return;
				}
				if (!item.quantity || item.quantity <= 0) {
					error = `BOM item ${i + 1}: La cantidad debe ser mayor a cero`;
					return;
				}
			}
		}

		loading = true;
		try {
			let commonData: any = { ...formData };
			commonData.fraction = normalizeMexTariffDigitsStored(commonData.fraction);
			commonData.fraction_9801 = normalizeMexTariffDigitsStored(commonData.fraction_9801);
			commonData.scrap_export_fraction = normalizeMexTariffDigitsStored(
				commonData.scrap_export_fraction
			);
			if (!commonData.currency_type || (commonData.currency_type !== 'NA' && commonData.currency_type !== 'EX')) {
				commonData.currency_type = 'EX';
			}
			if (!commonData.currency_key) {
				commonData.currency_key = commonData.currency_type === 'NA' ? 'MXN' : 'USD';
			}
			if (!commonData.currency_key || commonData.currency_key === 'USD') {
				commonData.currency_key = null;
			}
			if (formType === 'fa') {
				// SCAF only: send fa_data, no inv_data
				commonData.fa_data = {
					sector: formData.sector,
					fraction_type: formData.fraction_type,
					origin_country: formData.origin_country
				};
				delete commonData.sector;
				delete commonData.fraction_type;
				delete commonData.origin_country;
			} else {
				// SCAI or AMBOS: always send inv_data
				commonData.inv_data = {
					part_type: formData.part_type,
					material_type: formData.material_type,
					reference_number: formData.reference_number,
					flex_reference_number: formData.flex_reference_number,
					equivalent_uom: formData.equivalent_uom,
					conversion_factor: formData.conversion_factor,
					stock_uom: formData.stock_uom,
					alternate_uom: formData.alternate_uom,
					conversion_uom: formData.conversion_uom,
					added_value: formData.added_value,
					added_value_type: formData.value_added_type,
					assigned_client: formData.assigned_client,
					supplier_code: formData.supplier || formData.supplier_code,
					is_textile: formData.is_textile ? 'S' : 'N',
					bom_version: formData.bom_version,
					is_repair: formData.is_repair,
					is_hazardous: formData.is_hazardous,
					emergency_number: formData.emergency_number,
					danger_class: formData.danger_class,
					packaging_group: formData.packaging_group,
					width: formData.width,
					thickness: formData.thickness,
					specification: formData.specification,
					total_value: formData.total_value,
					direct_labor: formData.direct_labor,
					general_expenses: formData.general_expenses,
					total_expenses: formData.total_expenses,
					depreciation: formData.depreciation,
					tooling: formData.tooling,
					material_consumed: formData.material_consumed,
					profit: formData.profit,
					us_fraction_alt: formData.us_fraction_alt,
					ca_fraction: formData.ca_fraction,
					ad_valorem_us: formData.ad_valorem_us,
					nafta_result: formData.nafta_result,
					nafta_percentage: formData.nafta_percentage,
					dta: formData.dta,
					dtb: formData.dtb,
					dtg: formData.dtg,

					// Campos Opcionales 2 y Extensión
					usmca_fraction: formData.usmca_fraction,
					scrap_part_number: formData.scrap_part_number,
					waste_part_number: formData.waste_part_number,
					scrap_description_en: formData.scrap_description_en,
					scrap_description_es: formData.scrap_description_es,
					scrap_export_fraction: formData.scrap_export_fraction,
					scrap_us_fraction: formData.scrap_us_fraction,
					equivalent_uom_2: formData.equivalent_uom_2,
					conversion_factor_2: formData.conversion_factor_2,
					has_auxiliary: formData.has_auxiliary,
					auxiliary_uom: formData.auxiliary_uom,
					auxiliary_conversion: formData.auxiliary_conversion,
					auxiliary_unit_cost: formData.auxiliary_unit_cost,
					mex_packing: formData.mex_packing,
					sales_order: formData.sales_order,
					use_rule_8: formData.use_rule_8,
					non_discharge_clients: formData.non_discharge_clients,

					// Nuevos campos
					fraction_9801: formData.fraction_9801,
					fraction_type: formData.fraction_type,
					use_alternate_quantity: formData.use_alternate_quantity,
					repair_unit_cost: formData.repair_unit_cost,
					repair_added_value: formData.repair_added_value,
					sector: formData.sector,
					origin_country: formData.origin_country,
					hazard_notes: formData.hazard_notes,
					shipping_name: formData.shipping_name,
					un_number: formData.un_number,
					complementary_part: formData.complementary_part,
					preference_part: formData.preference_part,
					substitute_part: formData.substitute_part,
					immex_type: formData.immex_type,
					disable_movements: formData.disable_movements,
					pga_program_code: formData.pga_program_code,

					bom_items: bomData,
					countries: countriesData.map((c: any) => ({
						...c,
						fraction: c.fraction ? normalizeMexTariffDigitsStored(c.fraction) : c.fraction
					}))
				};
				// For 'both' mode, also include fa_data
				if (formType === 'both') {
					commonData.fa_data = {
						sector: formData.sector,
						fraction_type: formData.fraction_type,
						origin_country: formData.origin_country
					};
				}
			}

			if (isEdit && partId) {
				// TODO: Verify partId is number/string as expected
				const res = await partsApi.update(Number(partId), commonData, activeCompanyId);
				if (res.error) throw new Error(res.error);
			} else {
				const result = await partsApi.create(
					{ ...commonData, company_id: activeCompanyId },
					activeCompanyId
				);
				if (result.error) {
					error = result.error;
					return;
				}
			}
			toast.success(isEdit ? 'Parte actualizada' : 'Parte creada');
			goto('/dashboard/goods/parts');
		} catch (e: any) {
			console.error('Submit Error:', e);
			console.error(
				'Full error object:',
				JSON.stringify(
					{
						message: e.message,
						response: e.response?.data,
						status: e.response?.status
					},
					null,
					2
				)
			);

			// Tratar de extraer el mensaje de error más detallado
			let errorMsg = e.message || 'Error al guardar';
			if (e.response?.data?.detail) {
				errorMsg = e.response.data.detail;
			} else if (e.response?.data?.message) {
				errorMsg = e.response.data.message;
			} else if (e.response?.data?.error) {
				errorMsg = e.response.data.error;
			}

			error = errorMsg;
			toast.error(errorMsg);
		} finally {
			loading = false;
		}
	}
	// Shortcuts
	useShortcuts(
		'Part Form',
		obtenerAtajosFormularioMercancia({
			cambiarPestana: (pestana: string) => (activeTab = pestana),
			manejarGuardar: handleSubmit,
			manejarRegresar: () => goto('/dashboard/goods/parts')
		})
	);
</script>

<div class="space-y-4">
	<div class="flex items-center justify-between">
		<div class="space-y-1">
			<div class="flex items-center gap-3">
				<Button variant="ghost" size="icon" href="/dashboard/goods/parts">
					<ArrowLeft size={20} />
				</Button>
				<h1 class="text-3xl font-bold tracking-tight">{title}</h1>
				<Badge variant={isEdit ? 'secondary' : 'default'}>
					{isEdit ? 'Editar' : 'Nueva'}
				</Badge>

			</div>
		</div>
	</div>

	<Separator />
	{#if error}
		<div
			class="animate-in slide-in-from-top-2 rounded-md border border-destructive/20 bg-destructive/10 p-4 text-sm font-medium text-destructive"
		>
			⚠️ {error}
		</div>
	{/if}

	<div class="pb-48">
		{#if formType === 'fa'}
			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleSubmit();
				}}
				class="space-y-6"
			>
				<Card.Root class="shadow-sm">
					<Card.Content class="p-6">
						<Tabs.Root bind:value={activeTab} class="w-full">
							<div class="min-h-[500px]">
								<Tabs.Content
									value="general"
									class="animate-in fade-in space-y-8 pt-6 duration-300"
								>
									<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
										<div class="space-y-2 md:col-span-12">
											<Label for="fa_pn" class="required text-base font-semibold"
												>Número de Parte</Label
											>
											<div class="relative">
												<Package class="absolute top-2.5 left-3 h-5 w-5 text-muted-foreground" />
												<Input
													id="fa_pn"
													bind:value={formData.part_number}
													disabled={isEdit}
													maxlength={50}
													class="bg-muted/20 pl-10 font-mono text-lg"
													placeholder="Ej: MAQ-001"
												/>
											</div>
										</div>
									</div>

									<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
										<div class="space-y-2 md:col-span-6">
											<Label for="fa_desc_es" class="flex items-center gap-2"
												>Descripción Español <span class="text-xs font-normal text-muted-foreground"
													>(Requerido)</span
												></Label
											>
											<Textarea
												id="fa_desc_es"
												bind:value={formData.description_spanish}
												rows={3}
												class="resize-none"
												placeholder="Descripción detallada en español..."
											/>
										</div>
										<div class="space-y-2 md:col-span-6">
											<Label for="fa_desc_en" class="flex items-center gap-2"
												>Descripción Inglés</Label
											>
											<Textarea
												id="fa_desc_en"
												bind:value={formData.description_english}
												rows={3}
												class="resize-none"
												placeholder="English description..."
											/>
										</div>
									</div>

									<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
										<div class="space-y-2 md:col-span-4">
											<Label for="fa_class" class="required">Clase</Label>
											<div class="flex gap-2">
												<Input
													id="fa_class"
													bind:value={formData.part_class}
													readonly
													onclick={() => (showClassModal = true)}
													onkeydown={(event) =>
														openOnEnterOrSpace(event, () => (showClassModal = true))}
													tabindex="0"
													class="cursor-pointer font-mono"
													placeholder="Seleccione..."
												/>
												<Button
													variant="outline"
													size="icon"
													type="button"
													onclick={() => (showClassModal = true)}
													class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
											{#if selectedClassDesc}<p
													class="truncate px-1 text-[11px] text-muted-foreground"
												>
													{selectedClassDesc}
												</p>{/if}
										</div>

										<div class="space-y-2 md:col-span-4">
											<Label for="fa_uom" class="required">Unidad Medida</Label>
											<div class="flex gap-2">
												<div class="relative w-full">
													<Scale class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
													<Input
														id="fa_uom"
														bind:value={formData.unit_of_measure}
														readonly
														onclick={() => (showUOMModal = true)}
														onkeydown={(event) =>
															openOnEnterOrSpace(event, () => (showUOMModal = true))}
														tabindex="0"
														class="cursor-pointer pl-9 font-mono"
														placeholder="Seleccione..."
													/>
												</div>
												<Button
													variant="outline"
													size="icon"
													type="button"
													onclick={() => (showUOMModal = true)}
													class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
										</div>

										<div class="space-y-2 md:col-span-4">
											<div class="flex items-center">
												<Label for="fa_origin">País Origen</Label>
											</div>
											<div class="flex gap-2">
												<div class="relative w-full">
													<Globe class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
													<Input
														id="fa_origin"
														bind:value={selectedCountryName}
														readonly
														onclick={() => (showCountryModal = true)}
														onkeydown={(event) =>
															openOnEnterOrSpace(event, () => (showCountryModal = true))}
														tabindex="0"
														class="cursor-pointer pl-9"
														placeholder="Seleccione..."
													/>
												</div>
												<Button
													variant="outline"
													size="icon"
													type="button"
													onclick={() => (showCountryModal = true)}
													class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
												>
											</div>
										</div>
									</div>

									<div class="space-y-4 rounded-xl border bg-slate-50 p-5 dark:bg-slate-900/30">
										<h3 class="flex items-center gap-2 text-sm font-semibold text-primary">
											<DollarSign class="h-4 w-4" /> Información Financiera y Pesos
										</h3>
										<Separator class="bg-primary/10" />
										<div class="grid grid-cols-1 gap-6 pt-2 md:grid-cols-12">
											<div class="space-y-2 md:col-span-4">
												<Label for="fa_cost">Costo Unitario</Label>
												<div class="relative">
													<span
														class="absolute top-1/2 left-3 -translate-y-1/2 text-sm font-semibold text-muted-foreground"
														>$</span
													>
													<input
														type="text"
														inputmode="decimal"
														autocomplete="off"
														id="fa_cost"
														onkeydown={decimalKeydown}
														onbeforeinput={decimalBeforeInput}
														oninput={(e) => decimalInput(e, (n) => (formData.unit_cost = n))}
														onpaste={decimalPaste}
														value={String(formData.unit_cost ?? '')}
														class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-10 w-full min-w-0 rounded-md border px-3 py-1 pl-7 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
														placeholder="0.0000"
													/>
												</div>
											</div>

											<div class="space-y-2 md:col-span-4">
												<Label>Moneda</Label>
												<div class="space-y-2">
													<Select.Root
														type="single"
														value={formData.currency_type}
														onValueChange={(v) => (formData.currency_type = v)}
													>
														<Select.Trigger class="w-full">
															{formData.currency_type === 'NA'
																? 'Nacional'
																: formData.currency_type === 'EX'
																	? 'Extranjera'
																	: 'Seleccione...'}
														</Select.Trigger>
														<Select.Content>
															<Select.Item value="NA">Nacional</Select.Item>
															<Select.Item value="EX">Extranjera</Select.Item>
														</Select.Content>
													</Select.Root>
													<p class="text-xs text-muted-foreground">
														Moneda asignada: <span class="font-mono font-semibold">{selectedCurrencyName}</span>
													</p>
												</div>
											</div>

											<div class="space-y-2 md:col-span-4">
												<Label for="fa_weight">Peso Unitario</Label>
												<div class="flex gap-2">
													<input
														type="text"
														inputmode="decimal"
														autocomplete="off"
														id="fa_weight"
														onkeydown={decimalKeydown}
														onbeforeinput={decimalBeforeInput}
														oninput={(e) => decimalInput(e, (n) => (formData.unit_weight = n))}
														onpaste={decimalPaste}
														value={String(formData.unit_weight ?? '')}
														class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
														placeholder="0.0000"
													/>
													<Select.Root
														type="single"
														value={formData.weight_type}
														onValueChange={(v) => (formData.weight_type = v)}
													>
														<Select.Trigger class="w-[85px]">{formData.weight_type}</Select.Trigger>
														<Select.Content>
															<Select.Item value="KG">KG</Select.Item>
															<Select.Item value="LB">LB</Select.Item>
														</Select.Content>
													</Select.Root>
												</div>
											</div>
										</div>
									</div>

									<div class="space-y-4 rounded-xl border p-5">
										<h3 class="flex items-center gap-2 text-sm font-semibold text-muted-foreground">
											<Briefcase class="h-4 w-4" /> Clasificación Aduanera
										</h3>
										<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
											<div class="space-y-2 md:col-span-6">
												<Label for="fa_fraction">Fracción UMT (MX)</Label>
												<div class="flex gap-2">
													<Input
														id="fa_fraction"
														value={formatMexTariffDigitsForDisplay(formData.fraction)}
														readonly
														onclick={() => (showFractionModal = true)}
														onkeydown={(event) =>
															openOnEnterOrSpace(event, () => (showFractionModal = true))}
														tabindex="0"
														class="cursor-pointer font-mono"
														placeholder="Seleccione..."
													/>
													<Button
														variant="outline"
														size="icon"
														type="button"
														onclick={() => (showFractionModal = true)}
														class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
													>
												</div>
											</div>
											<div class="space-y-2 md:col-span-6">
												<Label for="fa_us_fraction">Fracción Americana</Label>
												<div class="flex gap-2">
													<Input
														id="fa_us_fraction"
														bind:value={formData.us_fraction}
														maxlength={10}
														class="cursor-pointer font-mono"
														placeholder="HTS Code"
														readonly
														onclick={() => (showUSFractionModal = true)}
														onkeydown={(event) =>
															openOnEnterOrSpace(event, () => (showUSFractionModal = true))}
														tabindex="0"
													/>
													<Button
														variant="outline"
														size="icon"
														type="button"
														onclick={() => (showUSFractionModal = true)}
														class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
													>
												</div>
											</div>
											<div class="space-y-2 md:col-span-6">
												<div class="flex items-center">
													<Label for="fa_sector">Sector</Label>
												</div>
												<div class="flex gap-2">
													<Input
														id="fa_sector"
														bind:value={formData.sector}
														readonly
														class="cursor-pointer font-mono"
														maxlength={8}
														placeholder="Seleccione..."
														onclick={() => (showSectorModal = true)}
														onkeydown={(event) =>
															openOnEnterOrSpace(event, () => (showSectorModal = true))}
														tabindex="0"
													/>
													<Button
														variant="outline"
														size="icon"
														type="button"
														onclick={() => (showSectorModal = true)}
														class="shrink-0"
													>
														<FolderSearch class="h-4 w-4" />
													</Button>
												</div>
												{#if selectedSectorDesc}
													<p class="text-xs text-muted-foreground">{selectedSectorDesc}</p>
												{/if}
											</div>
											<div class="space-y-2 md:col-span-6">
												<div class="flex items-center">
													<Label for="fa_fraction_type">Tipo Tarifa</Label>
												</div>
												<Select.Root
													type="single"
													value={formData.fraction_type}
													onValueChange={(v) => (formData.fraction_type = v)}
												>
													<Select.Trigger id="fa_fraction_type" class="w-full">
														{formData.fraction_type || 'Seleccione...'}
													</Select.Trigger>
													<Select.Content>
														<Select.Item value="GENERAL">GENERAL</Select.Item>
														<Select.Item value="PROSEC">PROSEC</Select.Item>
														<Select.Item value="ALADI">ALADI</Select.Item>
														<Select.Item value="TLCS">TLCS</Select.Item>
													</Select.Content>
												</Select.Root>
											</div>
										</div>
									</div>

									<div class="flex items-center gap-3 pt-2 pl-1">
										<Switch id="fa_is_active" bind:checked={formData.is_active} />
										<Label for="fa_is_active" class="cursor-pointer">Parte activa en sistema</Label>
									</div>
								</Tabs.Content>

								<Tabs.Content value="cont1" class="animate-in fade-in space-y-6 pt-6 duration-300">
									<div class="space-y-4 rounded-xl border p-6">
										<div class="mx-auto max-w-2xl space-y-4">
											<Label for="fa_photo" class="flex items-center gap-2 text-base">
												<ImageIcon class="h-5 w-5" /> URL Imagen de la parte
											</Label>
											<div class="flex gap-2">
												<Input
													id="fa_photo"
													bind:value={formData.part_photo}
													maxlength={255}
													placeholder="https://ejemplo.com/imagen.jpg"
												/>
												<Button variant="outline" class="shrink-0">Vista Previa</Button>
											</div>
											{#if formData.part_photo}
												<div
													class="mt-4 flex aspect-video items-center justify-center overflow-hidden rounded-lg border bg-muted"
												>
													<img
														src={formData.part_photo}
														alt="Vista previa"
														class="h-full w-full object-contain"
													/>
												</div>
											{/if}
										</div>
									</div>
								</Tabs.Content>

								<Tabs.Content value="cont2" class="animate-in fade-in space-y-6 pt-6 duration-300">
									<div class="grid grid-cols-1 gap-8 md:grid-cols-2">
										<div class="space-y-4 rounded-xl border p-5">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<ShieldCheck class="h-4 w-4" /> Control de Exportación
											</h3>
											<div class="grid gap-4">
												<div class="grid grid-cols-2 gap-4">
													<div class="space-y-2">
														<Label for="fa_lic">License Code</Label>
														<Input
															id="fa_lic"
															bind:value={formData.license_code}
															maxlength={3}
															class="font-mono"
														/>
													</div>
													<div class="space-y-2">
														<Label for="fa_exp">Export Code</Label>
														<Input
															id="fa_exp"
															bind:value={formData.export_code}
															maxlength={2}
															class="font-mono"
														/>
													</div>
												</div>
												<div class="space-y-2">
													<Label for="fa_eccn">ECCN</Label>
													<Input
														id="fa_eccn"
														bind:value={formData.eccn}
														maxlength={20}
														class="font-mono"
													/>
												</div>
												<div class="space-y-2">
													<Label for="fa_exc">Símbolo Excepción Licencia</Label>
													<Input
														id="fa_exc"
														bind:value={formData.exclusion_symbol}
														maxlength={19}
													/>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border p-5">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<Info class="h-4 w-4" /> Regulaciones Adicionales
											</h3>
											<div class="space-y-4">
												<div class="space-y-2">
													<Label for="fa_fda">Clave FDA</Label>
													<Input id="fa_fda" bind:value={formData.fda_key} maxlength={20} />
												</div>
												<div class="space-y-2">
													<Label for="fa_fcc">Clave FCC</Label>
													<Input id="fa_fcc" bind:value={formData.fcc_key} maxlength={30} />
												</div>
											</div>
										</div>
									</div>
								</Tabs.Content>
							</div>
						</Tabs.Root>
					</Card.Content>
				</Card.Root>
			</form>
		{:else}
			<form
				onsubmit={(e) => {
					e.preventDefault();
					handleSubmit();
				}}
				class="space-y-6"
			>
				<Card.Root class="shadow-sm">
					<Card.Content class="p-6">
						<Tabs.Root bind:value={activeTab} class="w-full">
							<div class="min-h-[500px]">
								<Tabs.Content
									value="general"
									class="animate-in fade-in space-y-6 pt-6 duration-300"
								>
									<div class="grid grid-cols-1 gap-8 lg:grid-cols-2">
										<div class="space-y-6">
											<div class="grid grid-cols-1 gap-4">
												<div class="space-y-2">
													<Label for="part_number" class="required text-base font-semibold"
														>Número de Parte</Label
													>
													<div class="relative">
														<Package
															class="absolute top-2.5 left-3 h-5 w-5 text-muted-foreground"
														/>
														<Input
															id="part_number"
															bind:value={formData.part_number}
															disabled={isEdit}
															maxlength={50}
															class="bg-muted/20 pl-10 font-mono text-lg"
															placeholder="Ej: 123-ABC-456"
														/>
													</div>
												</div>

											</div>

											<div class="space-y-3 rounded-xl border bg-slate-50 p-4 dark:bg-slate-900/30">
												<h4 class="flex items-center gap-2 text-sm font-semibold">
													<FileText class="h-4 w-4" /> Descripción
												</h4>
												<div class="space-y-2">
													<Label for="desc_es">Español</Label>
													<Textarea
														id="desc_es"
														bind:value={formData.description_spanish}
														rows={2}
														class="resize-none bg-background"
													/>
												</div>
												<div class="space-y-2">
													<Label for="desc_en">Inglés</Label>
													<Textarea
														id="desc_en"
														bind:value={formData.description_english}
														rows={2}
														class="resize-none bg-background"
													/>
												</div>
											</div>

											<div class="space-y-2">
												<Label for="part_class" class="font-semibold">Clase</Label>
												<div class="flex gap-2">
													<Input
														id="part_class"
														bind:value={formData.part_class}
														readonly
														onclick={() => (showClassModal = true)}
														onkeydown={(event) =>
															openOnEnterOrSpace(event, () => (showClassModal = true))}
														tabindex="0"
														class="cursor-pointer font-mono"
														placeholder="Seleccione clase..."
													/>
													<Button
														variant="outline"
														size="icon"
														type="button"
														onclick={() => (showClassModal = true)}
														class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
													>
												</div>
											</div>

											<div class="grid grid-cols-2 gap-4">
												<div class="space-y-2">
													<Label for="mat_type">Tipo de Material</Label>
													<div class="flex gap-2">
														<Input
															id="mat_type"
															bind:value={formData.material_type}
															readonly
															onclick={() => (showMaterialModal = true)}
															onkeydown={(event) =>
																openOnEnterOrSpace(event, () => (showMaterialModal = true))}
															tabindex="0"
															class="cursor-pointer font-mono"
															placeholder="Mat..."
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => (showMaterialModal = true)}
															class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
														>
													</div>
												</div>
												<div class="space-y-2">
													<Label for="uom">Unidad de Medida</Label>
													<div class="flex gap-2">
														<Input
															id="uom"
															bind:value={formData.unit_of_measure}
															readonly
															onclick={() => (showUOMModal = true)}
															onkeydown={(event) =>
																openOnEnterOrSpace(event, () => (showUOMModal = true))}
															tabindex="0"
															class="cursor-pointer font-mono"
															placeholder="UM..."
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => (showUOMModal = true)}
															class="shrink-0"><FolderSearch class="h-4 w-4" /></Button
														>
													</div>
												</div>

												<div class="space-y-2">
													<Label for="inv_origin" class="font-semibold">País Origen</Label>
													<div class="flex gap-2">
														<div class="relative w-full">
															<Globe class="absolute top-2.5 left-3 h-4 w-4 text-muted-foreground" />
															<Input
																id="inv_origin"
																bind:value={selectedCountryName}
																readonly
																onclick={() => (showCountryModal = true)}
																onkeydown={(event) =>
																	openOnEnterOrSpace(event, () => (showCountryModal = true))}
																tabindex="0"
																class="cursor-pointer pl-9 transition-colors hover:bg-muted/50"
																placeholder="Seleccione..."
															/>
														</div>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => (showCountryModal = true)}
															class="shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
											</div>

											<div
												class="space-y-4 rounded-xl border bg-green-50/30 p-4 dark:bg-green-900/10"
											>
												<h4
													class="flex items-center gap-2 text-sm font-semibold text-green-700 dark:text-green-400"
												>
													<DollarSign class="h-4 w-4" /> Costos y Pesos
												</h4>
												<div class="grid grid-cols-3 gap-3">
													<div class="space-y-2">
														<Label>Moneda</Label>
														<div class="space-y-2">
															<Select.Root
																type="single"
																value={formData.currency_type}
																onValueChange={(v) => (formData.currency_type = v)}
															>
																<Select.Trigger class="h-9 w-full text-xs">
																	{formData.currency_type === 'NA'
																		? 'Nacional'
																		: formData.currency_type === 'EX'
																			? 'Extranjera'
																			: 'Seleccione...'}
																</Select.Trigger>
																<Select.Content>
																	<Select.Item value="NA">Nacional</Select.Item>
																	<Select.Item value="EX">Extranjera</Select.Item>
																</Select.Content>
															</Select.Root>
															<p class="text-[10px] text-muted-foreground">
																Moneda: <span class="font-mono font-semibold">{selectedCurrencyName}</span>
															</p>
														</div>
													</div>
													<div class="space-y-2">
														<Label for="unit_cost">Costo Unit</Label>
														<input
															id="unit_cost"
															type="text"
															inputmode="decimal"
															autocomplete="off"
															onkeydown={decimalKeydown}
															onbeforeinput={decimalBeforeInput}
															oninput={(e) => decimalInput(e, (n) => (formData.unit_cost = n))}
															onpaste={decimalPaste}
															value={String(formData.unit_cost ?? '')}
															class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
														/>
													</div>
													<div class="space-y-2">
														<Label for="unit_weight">Peso Unit</Label>
														<input
															id="unit_weight"
															type="text"
															inputmode="decimal"
															autocomplete="off"
															onkeydown={decimalKeydown}
															onbeforeinput={decimalBeforeInput}
															oninput={(e) => decimalInput(e, (n) => (formData.unit_weight = n))}
															onpaste={decimalPaste}
															value={String(formData.unit_weight ?? '')}
															class="border-input bg-background selection:bg-primary dark:bg-input/30 selection:text-primary-foreground ring-offset-background placeholder:text-muted-foreground shadow-xs flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base outline-none transition-[color,box-shadow] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px]"
														/>
													</div>
												</div>
											</div>

											<div
												class="space-y-3 rounded-xl border bg-blue-50/30 p-4 dark:bg-blue-900/10"
											>
												<h4
													class="flex items-center gap-2 text-sm font-semibold text-blue-700 dark:text-blue-400"
												>
													<Layers class="h-4 w-4" /> Valor Agregado
												</h4>
												<div class="flex flex-wrap items-center gap-4">
													<label class="flex cursor-pointer items-center gap-2 text-xs">
														<input
															type="radio"
															name="va_type"
															value="EX"
															bind:group={formData.value_added_type}
														/> Extranjero
													</label>
													<label class="flex cursor-pointer items-center gap-2 text-xs">
														<input
															type="radio"
															name="va_type"
															value="NA"
															bind:group={formData.value_added_type}
														/> Nacional
													</label>
													<label class="flex cursor-pointer items-center gap-2 text-xs">
														<input
															type="radio"
															name="va_type"
															value="PR"
															bind:group={formData.value_added_type}
														/> Porcentaje %
													</label>
													<Input
														type="number"
														step="0.01"
														bind:value={formData.added_value}
														class="ml-auto h-8 w-24 text-right"
														placeholder="0.00"
													/>
												</div>
											</div>

											<div class="grid grid-cols-2 gap-4">
												<div class="space-y-2">
													<Label for="mex_fraction" class="font-semibold">Fracción MX</Label>
													<div class="flex gap-2">
														<Input
															id="mex_fraction"
															value={formatMexTariffDigitsForDisplay(formData.fraction)}
															placeholder="MX code..."
															readonly
															class="bg-muted/10 font-mono text-xs"
															onclick={() => (showFractionModal = true)}
															onkeydown={(event) =>
																openOnEnterOrSpace(event, () => (showFractionModal = true))}
															tabindex="0"
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => (showFractionModal = true)}
															class="h-9 w-9 shrink-0"><FolderSearch class="h-4 w-4" /></Button
														>
													</div>
												</div>
												<div class="space-y-2">
													<Label for="us_fraction" class="font-semibold">Fracción US</Label>
													<div class="flex gap-2">
														<Input
															id="us_fraction"
															bind:value={formData.us_fraction}
															placeholder="US code..."
															readonly
															class="bg-muted/10 font-mono text-xs"
															onclick={() => (showUSFractionModal = true)}
															onkeydown={(event) =>
																openOnEnterOrSpace(event, () => (showUSFractionModal = true))}
															tabindex="0"
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => (showUSFractionModal = true)}
															class="h-9 w-9 shrink-0"><FolderSearch class="h-4 w-4" /></Button
														>
													</div>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border bg-muted/5 p-4">
											<div class="flex items-center justify-between border-b pb-3">
												<div class="flex w-fit rounded-lg bg-muted p-0.5">
													<button
														type="button"
														class="rounded-md px-4 py-1.5 text-xs font-medium transition-all {relationType ===
														'bom'
															? 'bg-background shadow-sm'
															: 'text-muted-foreground hover:text-foreground'}"
														onclick={() => (relationType = 'bom')}
													>
														BOM
													</button>
													<button
														type="button"
														class="rounded-md px-4 py-1.5 text-xs font-medium transition-all {relationType ===
														'paises'
															? 'bg-background shadow-sm'
															: 'text-muted-foreground hover:text-foreground'}"
														onclick={() => (relationType = 'paises')}
													>
														PAISES
													</button>
												</div>
												<div class="flex gap-2">
													<Button
														variant="outline"
														size="sm"
														class="h-8 gap-1 text-[11px]"
														type="button"
														disabled={relationType === 'bom' && bomData.length > 0}
														title={relationType === 'bom' && bomData.length > 0
															? 'Esta parte ya tiene un BOM. Solo puedes editar o eliminarlo.'
															: ''}
														onclick={handleAddRelation}><Package class="h-3 w-3" /> Insertar</Button
													>
													<Button
														variant="outline"
														size="sm"
														class="h-8 gap-1 text-[11px]"
														type="button"
														disabled={currentEditIndex === null}
														onclick={() =>
															currentEditIndex !== null && handleEditRelation(currentEditIndex)}
														><Settings class="h-3 w-3" /> Editar</Button
													>
													<Button
														variant="destructive"
														size="sm"
														class="h-8 gap-1 text-[11px]"
														type="button"
														disabled={currentEditIndex === null}
														onclick={() =>
															currentEditIndex !== null && handleDeleteRelation(currentEditIndex)}
														><XCircle class="h-3 w-3" /> Borrar</Button
													>
												</div>
											</div>

											<div class="min-h-[400px] overflow-hidden rounded-lg border bg-background">
												<table class="w-full text-sm">
													<thead class="bg-muted/50">
														<tr>
															{#if relationType === 'bom'}
																<th class="p-3 text-left font-semibold">Componente</th>
																<th class="p-3 text-right font-semibold">Cantidad</th>
																<th class="p-3 text-center font-semibold">Tipo Proc.</th>
																<th class="p-3 text-left font-semibold">U.M.</th>
																<th class="p-3 text-right font-semibold">Distribución</th>
															{:else}
																<th class="p-3 text-center font-semibold">Omisión</th>
																<th class="p-3 text-left font-semibold">País</th>
																<th class="p-3 text-left font-semibold">Preferencia</th>
																<th class="p-3 text-center font-semibold">% Impo</th>
																<th class="p-3 text-center font-semibold">% Expo</th>
																<th class="p-3 text-center font-semibold">CO?</th>
																<th class="p-3 text-left font-semibold">Número CO</th>
																<th class="p-3 text-left font-semibold">Sector</th>
															{/if}
														</tr>
													</thead>
													<tbody class="divide-y text-xs">
														{#if relationData.length === 0}
															<tr>
																<td
																	colspan={relationType === 'bom' ? 5 : 8}
																	class="p-12 text-center text-muted-foreground italic"
																>
																	No hay datos registrados para {relationType === 'bom'
																		? 'BOM'
																		: 'Paises'}
																</td>
															</tr>
														{:else}
															{#each relationData as item, i}
																<tr
																	class="cursor-pointer transition-colors hover:bg-muted/50 {currentEditIndex ===
																	i
																		? 'bg-blue-50/50 dark:bg-blue-900/10'
																		: ''}"
																	onclick={() => (currentEditIndex = i)}
																>
																	{#if relationType === 'bom'}
																		<td class="p-3 font-medium">{item.component_part_number}</td>
																		<td class="p-3 text-right font-semibold">
																			<span class="text-base">{item.quantity}</span>
																			<span class="ml-1 text-[10px] font-normal">
																				{item.is_percentage ? '%' : 'U'}
																			</span>
																		</td>
																		<td class="p-3 text-center">
																			<span
																				class="rounded-md px-2 py-1 text-[10px] font-bold {item.procedure_type ===
																				'TEMPORAL'
																					? 'bg-blue-100 text-blue-700'
																					: item.procedure_type === 'DEFINITIVA'
																						? 'bg-green-100 text-green-700'
																						: 'bg-purple-100 text-purple-700'}"
																			>
																				{item.procedure_type || '-'}
																			</span>
																		</td>
																		<td class="p-3 font-mono font-semibold">{item.uom_code}</td>
																		<td class="p-3 text-right">
																			<div class="flex flex-col gap-0.5">
																				<div class="flex justify-end gap-1 text-[10px]">
																					<span class="font-semibold text-amber-600"
																						>MP: {item.raw_material}</span
																					>
																				</div>
																				<div class="flex justify-end gap-1 text-[10px]">
																					<span class="font-semibold text-red-600"
																						>D: {item.waste}</span
																					>
																				</div>
																				<div class="flex justify-end gap-1 text-[10px]">
																					<span class="font-semibold text-orange-600"
																						>M: {item.merma}</span
																					>
																				</div>
																			</div>
																		</td>
																	{:else}
																		<td class="p-3 text-center">
																			<div class="flex items-center justify-center gap-2">
																				<label
																					title="Importación"
																					class="flex cursor-pointer items-center gap-1"
																				>
																					<input
																						type="checkbox"
																						checked={item.omission_import}
																						disabled
																						class="h-3 w-3 accent-primary"
																					/>
																					<span class="text-[10px] font-medium">I</span>
																				</label>
																				<span class="text-muted-foreground/50">|</span>
																				<label
																					title="Exportación"
																					class="flex cursor-pointer items-center gap-1"
																				>
																					<input
																						type="checkbox"
																						checked={item.omission_export}
																						disabled
																						class="h-3 w-3 accent-primary"
																					/>
																					<span class="text-[10px] font-medium">E</span>
																				</label>
																			</div>
																		</td>
																		<td class="p-3 font-medium">{item.country_code || '-'}</td>
																		<td class="p-3">
																			<span
																				class="inline-block rounded px-2 py-1 text-[10px] font-semibold {item.preference ===
																				'PROSEC'
																					? 'bg-green-100 text-green-700'
																					: item.preference === 'ALADI'
																						? 'bg-blue-100 text-blue-700'
																						: item.preference === 'TLCS'
																							? 'bg-purple-100 text-purple-700'
																							: 'bg-gray-100 text-gray-700'}"
																			>
																				{item.preference || 'GENERAL'}
																			</span>
																		</td>
																		<td class="p-3 text-center font-mono text-sm font-semibold">
																			{item.import_percentage ? `${item.import_percentage}%` : '-'}
																		</td>
																		<td class="p-3 text-center font-mono text-sm font-semibold">
																			{item.export_percentage ? `${item.export_percentage}%` : '-'}
																		</td>
																		<td class="p-3 text-center">
																			<span
																				class="inline-block h-6 w-6 rounded-full {item.has_certificate
																					? 'flex items-center justify-center bg-green-100 text-green-700'
																					: 'flex items-center justify-center bg-gray-100 text-gray-700'}"
																			>
																				<span class="text-[11px] font-bold"
																					>{item.has_certificate ? '✓' : '✗'}</span
																				>
																			</span>
																		</td>
																		<td class="p-3 font-mono text-xs"
																			>{item.certificate_number || '-'}</td
																		>
																		<td class="p-3 text-sm font-medium">{item.sector || '-'}</td>
																	{/if}
																</tr>
															{/each}
														{/if}
													</tbody>
												</table>
											</div>
										</div>
									</div>
								</Tabs.Content>

								<Tabs.Content
									value="opcionales"
									class="animate-in fade-in space-y-6 pt-6 duration-300"
								>
									<div class="space-y-6">
										<div class="space-y-4 rounded-xl border p-6">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<Layers class="h-4 w-4" /> Partes Relacionadas
											</h3>
											<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
												<div class="space-y-2">
													<div class="flex items-center">
														<Label for="sub_part">Parte sustituto</Label>
													</div>
													<div class="flex gap-2">
														<Input
															id="sub_part"
															bind:value={formData.substitute_part}
															readonly
															class="bg-muted/10 font-mono text-xs"
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => (showSubstitutePartModal = true)}
															class="h-9 w-9 shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
												<div class="space-y-2">
													<div class="flex items-center">
														<Label for="comp_part">Parte complementaria</Label>
													</div>
													<Input
														id="comp_part"
														bind:value={formData.complementary_part}
														maxlength={30}
													/>
												</div>
												<div class="space-y-2">
													<div class="flex items-center">
														<Label for="pref_part">Parte de preferencia</Label>
													</div>
													<Input
														id="pref_part"
														bind:value={formData.preference_part}
														maxlength={30}
													/>
												</div>
												<div class="flex items-center gap-4 pt-8">
													<Switch id="use_alt_qty" bind:checked={formData.use_alternate_quantity} />
													<div class="flex items-center">
														<Label for="use_alt_qty" class="cursor-pointer"
															>Usar cantidad alterna</Label
														>
													</div>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border bg-red-50/30 p-6 dark:bg-red-950/10">
											<h3 class="flex items-center gap-2 text-sm font-semibold text-red-600">
												<ShieldCheck class="h-4 w-4" /> Material Peligroso / Seguridad
											</h3>
											<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
												<div class="space-y-2 md:col-span-4">
													<Label for="is_haz">¿Es material peligroso?</Label>
													<Select.Root
														type="single"
														value={formData.is_hazardous}
														onValueChange={(v) => (formData.is_hazardous = v)}
													>
														<Select.Trigger id="is_haz"
															>{formData.is_hazardous === 'S' ? 'Sí' : 'No'}</Select.Trigger
														>
														<Select.Content>
															<Select.Item value="S">Sí</Select.Item>
															<Select.Item value="N">No</Select.Item>
														</Select.Content>
													</Select.Root>
												</div>
												<div class="space-y-2 md:col-span-4">
													<div class="flex items-center">
														<Label for="un_num">Número UN</Label>
													</div>
													<Input id="un_num" bind:value={formData.un_number} maxlength={30} />
												</div>
												<div class="space-y-2 md:col-span-4">
													<div class="flex items-center">
														<Label for="ship_name">Nombre de embarque</Label>
													</div>
													<Input
														id="ship_name"
														bind:value={formData.shipping_name}
														maxlength={30}
													/>
												</div>
												<div class="space-y-2 md:col-span-4">
													<Label for="danger_cls">Clase de peligro</Label>
													<Input id="danger_cls" bind:value={formData.danger_class} maxlength={4} />
												</div>
												<div class="space-y-2 md:col-span-4">
													<Label for="pack_grp">Grupo de embalaje</Label>
													<Input
														id="pack_grp"
														bind:value={formData.packaging_group}
														maxlength={3}
													/>
												</div>
												<div class="space-y-2 md:col-span-4">
													<Label for="emerg_num">Número de emergencia</Label>
													<Input
														id="emerg_num"
														bind:value={formData.emergency_number}
														maxlength={30}
													/>
												</div>
												<div class="space-y-2 md:col-span-12">
													<div class="flex items-center">
														<Label for="haz_notes">Notas de peligro</Label>
													</div>
													<Input id="haz_notes" bind:value={formData.hazard_notes} maxlength={30} />
												</div>
											</div>
										</div>

										<div
											class="space-y-4 rounded-xl border bg-amber-50/30 p-6 dark:bg-amber-950/10"
										>
											<h3 class="flex items-center gap-2 text-sm font-semibold text-amber-600">
												<Settings class="h-4 w-4" /> Reparación
											</h3>
											<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
												<div class="space-y-2 md:col-span-4">
													<Label for="is_rep">¿Es reparación?</Label>
													<Select.Root
														type="single"
														value={formData.is_repair}
														onValueChange={(v) => (formData.is_repair = v)}
													>
														<Select.Trigger id="is_rep"
															>{formData.is_repair === 'S' ? 'Sí' : 'No'}</Select.Trigger
														>
														<Select.Content>
															<Select.Item value="S">Sí</Select.Item>
															<Select.Item value="N">No</Select.Item>
														</Select.Content>
													</Select.Root>
												</div>
												<div class="space-y-2 md:col-span-4">
													<div class="flex items-center">
														<Label for="rep_cost">Costo unitario de reparación</Label>
													</div>
													<Input
														type="number"
														step="0.01"
														id="rep_cost"
														bind:value={formData.repair_unit_cost}
													/>
												</div>
												<div class="space-y-2 md:col-span-4">
													<div class="flex items-center">
														<Label for="rep_val">Valor agregado de reparación</Label>
													</div>
													<Input
														type="number"
														step="0.01"
														id="rep_val"
														bind:value={formData.repair_added_value}
													/>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border p-6">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<ImageIcon class="h-4 w-4" /> Imagen del Producto
											</h3>
											<div class="grid grid-cols-1 gap-8 md:grid-cols-2">
												<div class="space-y-4">
													<div class="space-y-2">
														<Label for="photo_url">URL de la imagen</Label>
														<Input
															id="photo_url"
															bind:value={formData.part_photo}
															placeholder="https://..."
														/>
													</div>
												</div>
												<div
													class="flex aspect-video items-center justify-center overflow-hidden rounded-lg border bg-muted"
												>
													{#if formData.part_photo}
														<img
															src={formData.part_photo}
															alt="Vista previa"
															class="h-full w-full object-contain"
															onerror={(e) => ((e.currentTarget as HTMLImageElement).src = '')}
														/>
													{:else}
														<ImageIcon class="h-10 w-10 text-muted-foreground/20" />
													{/if}
												</div>
											</div>
										</div>
									</div>
								</Tabs.Content>

								<Tabs.Content
									value="opcionales2"
									class="animate-in fade-in space-y-6 pt-6 duration-300"
								>
									<div class="space-y-6">
										<div class="space-y-4 rounded-xl border p-6">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<Globe class="h-4 w-4" /> T-MEC / USMCA
											</h3>
											<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
												<div class="space-y-2">
													<div class="flex items-center">
														<Label for="usmca_frac">Fracción aplicable al T-MEC</Label>
													</div>
													<Input id="usmca_frac" bind:value={formData.usmca_fraction} />
												</div>
												<div class="space-y-2">
													<Label for="us_frac_alt">Fracción EUA (HTS USA)</Label>
													<div class="flex gap-2">
														<Input
															id="us_frac_alt"
															bind:value={formData.us_fraction_alt}
															readonly
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => {
																modalContext = 'us_fraction_alt';
																showUSFractionModal = true;
															}}
															class="shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
												<div class="space-y-2">
													<Label for="ca_frac">Fracción CAN (HTS CAN)</Label>
													<Input id="ca_frac" bind:value={formData.ca_fraction} />
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border bg-muted/5 p-6">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<ClipboardList class="h-4 w-4" /> FDA (Food and Drug Administration)
											</h3>
											<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
												<div class="space-y-2">
													<Label for="fda_key">Clave FDA</Label>
													<Input id="fda_key" bind:value={formData.fda_key} />
												</div>
												<div class="space-y-2">
													<Label for="sales_cost">Costo de venta (USD)</Label>
													<div class="relative">
														<span class="absolute top-2.5 left-3 text-sm text-muted-foreground"
															>$</span
														>
														<Input
															type="number"
															step="0.01"
															id="sales_cost"
															class="pl-7"
															bind:value={formData.total_value}
														/>
													</div>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border bg-red-50/20 p-6 dark:bg-red-950/5">
											<h3 class="flex items-center gap-2 text-sm font-medium text-red-600/80">
												<Trash2 class="h-4 w-4" /> Merma y Desperdicio
											</h3>
											<div class="grid grid-cols-1 gap-6 md:grid-cols-12">
												<div class="space-y-2 md:col-span-6">
													<div class="flex items-center">
														<Label for="scrap_part">Número de parte desperdicio</Label>
													</div>
													<div class="flex gap-2">
														<Input id="scrap_part" bind:value={formData.scrap_part_number} />
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => {
																modalContext = 'scrap_part';
																showSubstitutePartModal = true;
															}}
															class="shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
												<div class="space-y-2 md:col-span-6">
													<div class="flex items-center">
														<Label for="waste_part">Número de parte merma</Label>
													</div>
													<div class="flex gap-2">
														<Input id="waste_part" bind:value={formData.waste_part_number} />
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => {
																modalContext = 'waste_part';
																showSubstitutePartModal = true;
															}}
															class="shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
												<div class="space-y-2 md:col-span-6">
													<div class="flex items-center">
														<Label for="scrap_en">Nombre de la parte en inglés (Scrap)</Label>
													</div>
													<Input id="scrap_en" bind:value={formData.scrap_description_en} />
												</div>
												<div class="space-y-2 md:col-span-6">
													<div class="flex items-center">
														<Label for="scrap_es">Nombre de la parte en español (Scrap)</Label>
													</div>
													<Input id="scrap_es" bind:value={formData.scrap_description_es} />
												</div>
												<div class="space-y-2 md:col-span-6">
													<div class="flex items-center">
														<Label for="scrap_exp">Fracción de exportación (SITAR)</Label>
													</div>
													<div class="flex gap-2">
														<Input
															id="scrap_exp"
															value={formatMexTariffDigitsForDisplay(formData.scrap_export_fraction)}
															readonly
															class="bg-muted/10 font-mono text-xs"
															onclick={() => {
																modalContext = 'scrap_exp_frac';
																showFractionModal = true;
															}}
															onkeydown={(event) =>
																openOnEnterOrSpace(event, () => {
																	modalContext = 'scrap_exp_frac';
																	showFractionModal = true;
																})}
															tabindex="0"
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => {
																modalContext = 'scrap_exp_frac';
																showFractionModal = true;
															}}
															class="shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
												<div class="space-y-2 md:col-span-6">
													<div class="flex items-center">
														<Label for="scrap_us">Fracción Americana (Scrap)</Label>
													</div>
													<div class="flex gap-2">
														<Input id="scrap_us" bind:value={formData.scrap_us_fraction} />
														<Button
															variant="outline"
															size="icon"
															type="button"
															onclick={() => {
																modalContext = 'scrap_us_frac';
																showUSFractionModal = true;
															}}
															class="shrink-0"
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border p-6">
											<h3 class="flex items-center gap-2 text-sm font-medium text-muted-foreground">
												<Scale class="h-4 w-4" /> Unidades de Medida Equivalentes
											</h3>
											<div class="grid grid-cols-1 gap-x-12 gap-y-6 md:grid-cols-2">
												<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
													<div class="space-y-2">
														<Label for="eq_uom_1">Equivalente 1</Label>
														<div class="flex gap-2">
															<Input
																id="eq_uom_1"
																bind:value={formData.equivalent_uom}
																readonly
																class="bg-muted/10"
															/>
															<Button
																variant="outline"
																size="icon"
																type="button"
																onclick={() => {
																	modalContext = 'eq_uom_1';
																	showUOMModal = true;
																}}
															>
																<FolderSearch class="h-4 w-4" />
															</Button>
														</div>
													</div>
													<div class="space-y-2">
														<Label for="conv_f_1">Factor de conversión 1</Label>
														<Input
															type="number"
															step="0.00000001"
															id="conv_f_1"
															bind:value={formData.conversion_factor}
														/>
													</div>
												</div>
												<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
													<div class="space-y-2">
														<div class="flex items-center">
															<Label for="eq_uom_2">Equivalente 2</Label>
														</div>
														<div class="flex gap-2">
															<Input
																id="eq_uom_2"
																bind:value={formData.equivalent_uom_2}
																readonly
																class="bg-muted/10"
															/>
															<Button
																variant="outline"
																size="icon"
																type="button"
																onclick={() => {
																	modalContext = 'eq_uom_2';
																	showUOMModal = true;
																}}
															>
																<FolderSearch class="h-4 w-4" />
															</Button>
														</div>
													</div>
													<div class="space-y-2">
														<div class="flex items-center">
															<Label for="conv_f_2">Factor de conversión 2</Label>
														</div>
														<Input
															type="number"
															step="0.00000001"
															id="conv_f_2"
															bind:value={formData.conversion_factor_2}
														/>
													</div>
												</div>
											</div>
										</div>

										<div class="space-y-4 rounded-xl border bg-teal-50/20 p-6 dark:bg-teal-950/5">
											<h3 class="flex items-center gap-2 text-sm font-medium text-teal-600">
												<PlusSquare class="h-4 w-4" /> Campos Auxiliares / Importación
											</h3>
											<div class="grid grid-cols-1 items-end gap-6 md:grid-cols-12">
												<div class="flex items-center gap-3 pb-2 md:col-span-3">
													<Switch id="has_aux" bind:checked={formData.has_auxiliary} />
													<div class="flex items-center gap-1">
														<Label for="has_aux">Habilitar Auxiliar</Label>
													</div>
												</div>
												<div class="space-y-2 md:col-span-3">
													<div class="flex items-center">
														<Label for="aux_uom">Unidad de Medida</Label>
													</div>
													<div class="flex gap-2">
														<Input
															id="aux_uom"
															bind:value={formData.auxiliary_uom}
															disabled={!formData.has_auxiliary}
															readonly
															class="bg-muted/10"
														/>
														<Button
															variant="outline"
															size="icon"
															type="button"
															disabled={!formData.has_auxiliary}
															onclick={() => {
																modalContext = 'aux_uom';
																showUOMModal = true;
															}}
														>
															<FolderSearch class="h-4 w-4" />
														</Button>
													</div>
												</div>
												<div class="space-y-2 md:col-span-3">
													<div class="flex items-center">
														<Label for="aux_conv">Factor de conversión</Label>
													</div>
													<Input
														type="number"
														step="0.00000001"
														id="aux_conv"
														disabled={!formData.has_auxiliary}
														bind:value={formData.auxiliary_conversion}
													/>
												</div>
												<div class="space-y-2 md:col-span-3">
													<div class="flex items-center">
														<Label for="aux_cost">Costo Unitario</Label>
													</div>
													<Input
														type="number"
														step="0.01"
														id="aux_cost"
														disabled={!formData.has_auxiliary}
														bind:value={formData.auxiliary_unit_cost}
													/>
												</div>
											</div>
										</div>
									</div>
								</Tabs.Content>

								<Tabs.Content
									value="costos_am"
									class="animate-in fade-in space-y-6 pt-6 duration-300"
								>
									<div class="mx-auto max-w-md space-y-4 rounded-xl border bg-emerald-50/10 p-6">
										<h3 class="flex items-center gap-2 text-sm font-medium text-emerald-700">
											<DollarSign class="h-4 w-4" /> Costos Americanos
										</h3>
										<div class="space-y-2">
											<div class="flex items-center">
												<Label for="mex_packing">Valor del empaque Nac-Mex packing (dlls)</Label>
											</div>
											<div class="relative">
												<Input
													type="number"
													step="0.0001"
													id="mex_packing"
													bind:value={formData.mex_packing}
													class="h-11 pl-10 text-lg"
												/>
												<DollarSign class="absolute top-3 left-3 h-5 w-5 text-muted-foreground" />
											</div>
										</div>
									</div>
								</Tabs.Content>

								<Tabs.Content value="otros" class="animate-in fade-in space-y-6 pt-6 duration-300">
									<div class="flex items-center justify-between rounded-xl border bg-muted/30 p-4 shadow-sm">
										<div class="flex items-center gap-3">
											<div class="rounded-full bg-background p-2 shadow-inner">
												<Layers class="h-5 w-5 text-muted-foreground" />
											</div>
											<div>
												<h4 class="text-sm font-bold">Datos de Extensión</h4>
												<p class="text-xs text-muted-foreground">Configura datos adicionales, APHIS y certificaciones.</p>
											</div>
										</div>
										<Button
											variant="outline"
											size="sm"
											class="bg-background"
											href={`/dashboard/goods/parts/extension/${partId || 'new'}`}
										>
											<Layers class="mr-2 h-4 w-4" />
											Ir a Extensiones
										</Button>
									</div>

									<div class="grid grid-cols-1 gap-8 md:grid-cols-12">
										<div class="space-y-1 md:col-span-12">
											<h3 class="flex items-center gap-2 text-lg font-bold">
												<UserMinus class="h-5 w-5 text-destructive" /> Clientes que no descargan
											</h3>
											<p class="text-sm text-muted-foreground">
												Listado de clientes con restricción de descarga.
											</p>
										</div>

										<div class="overflow-hidden rounded-xl border shadow-sm md:col-span-12">
											<div class="flex items-center justify-between border-b bg-muted/30 p-4">
												<span class="text-sm font-semibold">Resumen de Clientes</span>
												<Button size="sm" onclick={handleAddNonDischarge} class="gap-1">
													<PlusIcon class="h-4 w-4" /> Agregar Cliente
												</Button>
											</div>
											<div class="overflow-x-auto">
												<table class="w-full text-sm">
													<thead class="border-b bg-muted/10">
														<tr>
															<th class="px-4 py-3 text-left font-medium">Cliente</th>
															<th class="px-4 py-3 text-left font-medium">Estatus</th>
															<th class="px-4 py-3 text-right font-medium">Acciones</th>
														</tr>
													</thead>
													<tbody class="divide-y">
														{#each formData.non_discharge_clients as item, i}
															<tr class="transition-colors hover:bg-muted/5">
																<td class="px-4 py-3 font-mono">{item.name}</td>
																<td class="px-4 py-3">
																	<Badge variant={item.is_active ? 'default' : 'secondary'}>
																		{item.is_active ? 'Activo' : 'Inactivo'}
																	</Badge>
																</td>
																<td class="px-4 py-3 text-right">
																	<div class="flex justify-end gap-1">
																		<Button
																			variant="ghost"
																			size="icon"
																			class="h-8 w-8 text-primary"
																			onclick={() => handleEditNonDischarge(i)}
																		>
																			<FileEdit class="h-4 w-4" />
																		</Button>
																		<Button
																			variant="ghost"
																			size="icon"
																			class="h-8 w-8 text-destructive"
																			onclick={() => handleDeleteNonDischarge(i)}
																		>
																			<Trash2 class="h-4 w-4" />
																		</Button>
																	</div>
																</td>
															</tr>
														{/each}
														{#if formData.non_discharge_clients.length === 0}
															<tr>
																<td
																	colspan="3"
																	class="px-4 py-8 text-center text-muted-foreground italic"
																>
																	No hay clientes registrados en esta lista.
																</td>
															</tr>
														{/if}
													</tbody>
												</table>
											</div>
										</div>

										<div class="space-y-6 md:col-span-6">
											<div class="space-y-4 rounded-xl border bg-muted/20 p-6">
												<h3 class="flex items-center gap-2 text-sm font-semibold">
													<Scale class="h-4 w-4" /> Datos de Conversión
												</h3>
												<div class="grid grid-cols-2 gap-4">
													<div class="space-y-2">
														<Label for="conv_u">UM Conversión</Label>
														<Input
															id="conv_u"
															bind:value={formData.conversion_uom}
															maxlength={9}
															disabled
															class="bg-muted/50"
														/>
													</div>
													<div class="space-y-2">
														<Label for="conv_f">Factor Conversión</Label>
														<Input
															type="number"
															step="0.0001"
															id="conv_f"
															bind:value={formData.conversion_factor}
															readonly
															class="bg-muted/50"
														/>
													</div>
												</div>
											</div>

											<div class="space-y-4 rounded-xl border p-6">
												<h3 class="flex items-center gap-2 text-sm font-semibold">
													<FileSpreadsheet class="h-4 w-4 text-blue-500" /> Otros Datos
												</h3>
												<div class="space-y-4">
													<div class="space-y-2">
														<div class="flex items-center">
															<Label for="sales_order">Orden de venta</Label>
														</div>
														<Input
															id="sales_order"
															bind:value={formData.sales_order}
															maxlength={50}
															placeholder="Ej: OV-2024-001"
														/>
													</div>
													<div
														class="flex items-center gap-3 rounded-xl border bg-orange-50/20 p-4"
													>
														<Switch id="rule_8" bind:checked={formData.use_rule_8} />
														<div class="flex items-center gap-2">
															<Label for="rule_8" class="cursor-pointer text-sm font-medium">
																Activar si el numero de parte usa regla octava
															</Label>
														</div>
													</div>
												</div>
											</div>
										</div>

										<div class="space-y-6 md:col-span-6">
											<div class="space-y-4 rounded-xl border bg-slate-50 p-6 dark:bg-slate-900/30">
												<h3 class="text-sm font-medium text-muted-foreground">Status de Parte</h3>
												<div class="flex items-center gap-3 rounded-xl border bg-background p-4">
													<Switch
														id="is_active_otros"
														bind:checked={formData.is_active}
														disabled={loading}
													/>
													<Label for="is_active_otros" class="cursor-pointer font-bold"
														>Parte Activa en Sistema</Label
													>
												</div>
											</div>
										</div>
									</div>
								</Tabs.Content>
							</div>
						</Tabs.Root>
					</Card.Content>
				</Card.Root>
			</form>
		{/if}
	</div>
</div>

<div
	class="fixed right-0 bottom-0 left-0 z-[5] ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
>
	<div class="mx-auto max-w-[1400px] space-y-4 px-4 py-4">
		<Tabs.Root bind:value={activeTab}>
			<div class="w-full overflow-x-auto pb-2">
				{#if formType === 'fa'}
					<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-3">
						<Tabs.Trigger value="general" class="whitespace-nowrap">
							<Package size={16} class="mr-2" />
							General
						</Tabs.Trigger>
						<Tabs.Trigger value="cont1" class="whitespace-nowrap">
							<FileText size={16} class="mr-2" />
							Opciones
						</Tabs.Trigger>
						<Tabs.Trigger value="cont2" class="whitespace-nowrap">
							<Settings size={16} class="mr-2" />
							Más...
						</Tabs.Trigger>
					</Tabs.List>
				{:else}
					<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-5">
						<Tabs.Trigger value="general" class="whitespace-nowrap">
							<Package size={16} class="mr-2" />
							General
						</Tabs.Trigger>
						<Tabs.Trigger value="opcionales" class="whitespace-nowrap">
							<Settings size={16} class="mr-2" />
							Opcionales
						</Tabs.Trigger>
						<Tabs.Trigger value="opcionales2" class="whitespace-nowrap">
							<FileText size={16} class="mr-2" />
							Opcionales 2
						</Tabs.Trigger>
						<Tabs.Trigger value="costos_am" class="whitespace-nowrap">
							<DollarSign size={16} class="mr-2" />
							Costos americanos
						</Tabs.Trigger>
						<Tabs.Trigger value="otros" class="whitespace-nowrap">
							<Layers size={16} class="mr-2" />
							Otros
						</Tabs.Trigger>
					</Tabs.List>
				{/if}
			</div>
		</Tabs.Root>

		<div class="flex justify-end gap-3">
			<Button type="button" variant="outline" href="/dashboard/goods/parts" disabled={loading}>
				Cancelar
			</Button>
			<Button type="button" onclick={handleSubmit} disabled={loading}>
				{#if loading}
					<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
					Guardando...
				{:else}
					<Save size={16} class="mr-2" />
					{isEdit ? 'Actualizar' : 'Guardar'}
				{/if}
			</Button>
		</div>
	</div>
</div>

<ClientSelectorDialog bind:open={showClientModal} onSelect={handleClientSelect} onClear={handleClientClear} />
<ClassSelectorDialog bind:open={showClassModal} onSelect={handleClassSelect} onClear={handleClassClear} />
<MaterialTypeSelectorDialog bind:open={showMaterialModal} onSelect={handleMaterialSelect} onClear={handleMaterialClear} />

<Dialog.Root bind:open={showNonDischargeDialog}>
	<Dialog.Content class="sm:max-w-[425px]">
		<Dialog.Header>
			<Dialog.Title>
				{currentEditIndex !== null ? 'Editar Cliente' : 'Agregar Cliente a Restricción'}
			</Dialog.Title>
			<Dialog.Description>
				Seleccione un cliente y defina si su restricción está activa.
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid gap-4 py-4">
			<div class="space-y-2">
				<Label for="nd_client" class="required">Cliente</Label>
				<div class="flex gap-2">
					<Input
						id="nd_client"
						bind:value={tempNonDischargeItem.name}
						placeholder="Seleccione un cliente..."
						readonly
						class="cursor-pointer bg-muted/30"
						onclick={() => {
							modalContext = 'non_discharge';
							showClientModal = true;
						}}
						onkeydown={(event) =>
							openOnEnterOrSpace(event, () => {
								modalContext = 'non_discharge';
								showClientModal = true;
							})}
						tabindex="0"
					/>
					<Button
						variant="outline"
						size="icon"
						onclick={() => {
							modalContext = 'non_discharge';
							showClientModal = true;
						}}
					>
						<FolderSearch class="h-4 w-4" />
					</Button>
				</div>
			</div>

			<div class="flex items-center justify-between rounded-xl border bg-muted/30 p-4">
				<div class="space-y-0.5">
					<Label for="nd_active" class="text-sm font-semibold">Estatus de Restricción</Label>
					<p class="text-xs text-muted-foreground italic">Permitir o denegar la descarga</p>
				</div>
				<Switch id="nd_active" bind:checked={tempNonDischargeItem.is_active} />
			</div>
		</div>

		<Dialog.Footer>
			<Button variant="outline" onclick={() => (showNonDischargeDialog = false)}>Cancelar</Button>
			<Button
				onclick={saveNonDischargeItem}
				disabled={!tempNonDischargeItem.client_id}
				class="gap-1"
			>
				<Save class="h-4 w-4" />
				{currentEditIndex !== null ? 'Actualizar' : 'Guardar'}
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>
<UnitMeasureSelectorDialog bind:open={showUOMModal} onSelect={handleUOMSelect} />
<UnitMeasureSelectorDialog bind:open={showAltUOMModal} onSelect={handleAltUOMSelect} />
<CountrySelectorDialog bind:open={showCountryModal} onSelect={handleCountrySelect} />
<FractionSelectorDialog bind:open={showFractionModal} onSelect={handleFractionSelect} />
<USFractionSelectorDialog bind:open={showUSFractionModal} onSelect={handleUSFractionSelect} />
<SectorSelectorDialog bind:open={showSectorModal} onSelect={handleSectorSelect} />
<SubstitutePartSelectorDialog
	bind:open={showSubstitutePartModal}
	onSelect={handleSubstitutePartSelect}
/>
<Fraction9801SelectorDialog bind:open={showFraction9801Modal} onSelect={handleFractionSelect9801} />
<TextileProviderSelectorDialog
	bind:open={showTextileProviderModal}
	onSelect={handleTextileProviderSelect}
/>

<Dialog.Root bind:open={showBOMDialog}>
	<Dialog.Content class="z-[500] sm:max-w-4xl">
		<Dialog.Header>
			<Dialog.Title>{currentEditIndex !== null ? 'Editar' : 'Insertar'} Componente BOM</Dialog.Title
			>
			<Dialog.Description>
				Ingrese los detalles del componente para la estructura de materiales.
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid grid-cols-1 gap-6 py-2 md:grid-cols-2">
			<div class="grid w-full gap-4">
				<div class="grid gap-2">
					<Label for="bom_comp">Componente <span class="text-red-600">*</span></Label>
					<div class="flex gap-2">
						<Input
							id="bom_comp"
							bind:value={tempRelationItem.component_part_number}
							placeholder="Seleccione componente..."
							readonly
							class={`cursor-pointer ${!tempRelationItem.component_part_id || tempRelationItem.component_part_id === 0 ? 'border-red-500 bg-red-50 dark:bg-red-950/20' : 'bg-muted/30'}`}
							onclick={() => {
								modalContext = 'bom_component';
								showSubstitutePartModal = true;
							}}
							onkeydown={(event) =>
								openOnEnterOrSpace(event, () => {
									modalContext = 'bom_component';
									showSubstitutePartModal = true;
								})}
							tabindex="0"
						/>
						<Button
							variant="outline"
							size="icon"
							onclick={() => {
								modalContext = 'bom_component';
								showSubstitutePartModal = true;
							}}
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
					{#if !tempRelationItem.component_part_id || tempRelationItem.component_part_id === 0}
						<p class="text-xs font-medium text-red-600 dark:text-red-400">
							Ingrese un componente para continuar
						</p>
					{/if}
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="grid gap-2">
						<Label for="bom_proc">Tipo de Procedencia</Label>
						<Select.Root
							type="single"
							value={tempRelationItem.procedure_type}
							onValueChange={(v) => (tempRelationItem.procedure_type = v)}
						>
							<Select.Trigger id="bom_proc">{tempRelationItem.procedure_type}</Select.Trigger>
							<Select.Content class="z-[400]">
								<Select.Item value="TEMPORAL">TEMPORAL</Select.Item>
								<Select.Item value="DEFINITIVA">DEFINITIVA</Select.Item>
								<Select.Item value="CTM">CTM</Select.Item>
							</Select.Content>
						</Select.Root>
					</div>
					<div class="grid gap-2">
						<Label for="bom_uom">U.M.</Label>
						<div class="flex gap-2">
							<Input id="bom_uom" bind:value={tempRelationItem.uom_code} readonly />
							<Button
								size="icon"
								variant="outline"
								onclick={() => {
									modalContext = 'bom_uom';
									showUOMModal = true;
								}}
							>
								<FolderSearch class="h-4 w-4" />
							</Button>
						</div>
					</div>
				</div>

				<div class="grid grid-cols-2 gap-4">
					<div class="grid gap-2">
						<Label for="bom_qty" class="font-semibold">Cantidad</Label>
						<Input
							id="bom_qty"
							type="number"
							step="0.0001"
							bind:value={tempRelationItem.quantity}
							class="text-base"
						/>
					</div>
					<div class="grid gap-2">
						<Label class="font-semibold">Tipo</Label>
						<div
							class="flex w-full cursor-pointer items-center justify-between rounded-lg border-2 bg-gradient-to-r from-blue-50 to-blue-50/50 p-3 transition-all hover:shadow-md dark:from-blue-950/20 dark:to-blue-950/10"
							role="switch"
							aria-checked={tempRelationItem.is_percentage}
							tabindex="0"
							onclick={() => (tempRelationItem.is_percentage = !tempRelationItem.is_percentage)}
							onkeydown={(e) => {
								if (e.key === ' ' || e.key === 'Enter') {
									e.preventDefault();
									tempRelationItem.is_percentage = !tempRelationItem.is_percentage;
								}
							}}
						>
							<span class="flex items-center gap-2 text-sm font-semibold">
								{#if tempRelationItem.is_percentage}
									<span class="rounded-md bg-blue-600 px-3 py-1.5 text-xs font-bold text-white"
										>%</span
									>
								{:else}
									<span class="rounded-md bg-gray-300 px-3 py-1.5 text-xs font-bold text-gray-700"
										>U</span
									>
								{/if}
							</span>
							<Switch bind:checked={tempRelationItem.is_percentage} class="pointer-events-none" />
						</div>
					</div>
				</div>

				<Separator class="my-2" />

				<div
					class="rounded-lg border-l-4 border-amber-400 bg-gradient-to-r from-amber-50 to-yellow-50 p-3 dark:from-amber-950/20 dark:to-yellow-950/20"
				>
					<p class="mb-3 text-xs font-semibold text-amber-900 dark:text-amber-200">
						Distribución de Componentes
					</p>
					<div class="grid grid-cols-3 gap-3">
						<div class="grid gap-2">
							<Label
								for="bom_raw"
								class="text-xs font-bold text-amber-700 uppercase dark:text-amber-300"
								>Materia Prima</Label
							>
							<div class="flex items-center gap-2">
								<Input
									id="bom_raw"
									type="number"
									step="0.000001"
									bind:value={tempRelationItem.raw_material}
									class="h-10 border-2 bg-white text-sm font-semibold dark:bg-slate-900"
									placeholder="0"
								/>
								<span class="w-6 text-center text-sm font-bold text-amber-700 dark:text-amber-300"
									>{tempRelationItem.is_percentage ? '%' : 'U'}</span
								>
							</div>
						</div>
						<div class="grid gap-2">
							<Label
								for="bom_waste"
								class="text-xs font-bold text-red-700 uppercase dark:text-red-300"
								>Desperdicio</Label
							>
							<div class="flex items-center gap-2">
								<Input
									id="bom_waste"
									type="number"
									step="0.000001"
									bind:value={tempRelationItem.waste}
									class="h-10 border-2 bg-white text-sm font-semibold dark:bg-slate-900"
									placeholder="0"
								/>
								<span class="w-6 text-center text-sm font-bold text-red-700 dark:text-red-300"
									>{tempRelationItem.is_percentage ? '%' : 'U'}</span
								>
							</div>
						</div>
						<div class="grid gap-2">
							<Label
								for="bom_merma"
								class="text-xs font-bold text-orange-700 uppercase dark:text-orange-300"
								>Merma</Label
							>
							<div class="flex items-center gap-2">
								<Input
									id="bom_merma"
									type="number"
									step="0.000001"
									bind:value={tempRelationItem.merma}
									class="h-10 border-2 bg-white text-sm font-semibold dark:bg-slate-900"
									placeholder="0"
								/>
								<span class="w-6 text-center text-sm font-bold text-orange-700 dark:text-orange-300"
									>{tempRelationItem.is_percentage ? '%' : 'U'}</span
								>
							</div>
						</div>
					</div>
				</div>
			</div>

			<div class="flex flex-col gap-4">
				<div class="overflow-hidden rounded-md border shadow-sm">
					<div
						class="bg-primary/95 px-3 py-1.5 text-xs font-bold tracking-wider text-primary-foreground uppercase"
					>
						Cantidades a Descargar
					</div>
					<div class="grid gap-2 bg-card p-3 text-sm">
						<div class="flex items-center justify-between">
							<span class="font-medium text-muted-foreground">Normal:</span>
							<div class="flex items-center gap-2 font-mono">
								<span>{Number(tempRelationItem.quantity || 0).toFixed(8)}</span>
								<span class="w-10 text-left font-bold text-primary"
									>{tempRelationItem.uom_code || 'PZA'}</span
								>
							</div>
						</div>
						<div class="flex items-center justify-between">
							<span class="font-medium text-muted-foreground">Desperdicio:</span>
							<div class="flex items-center gap-2 font-mono">
								<span>{Number(tempRelationItem.waste || 0).toFixed(8)}</span>
								<span class="w-10 text-left font-bold text-primary"
									>{tempRelationItem.uom_code || 'PZA'}</span
								>
							</div>
						</div>
						<div class="flex items-center justify-between">
							<span class="font-medium text-muted-foreground">Merma:</span>
							<div class="flex items-center gap-2 font-mono">
								<span>{Number(tempRelationItem.merma || 0).toFixed(8)}</span>
								<span class="w-10 text-left font-bold text-primary"
									>{tempRelationItem.uom_code || 'PZA'}</span
								>
							</div>
						</div>
					</div>
				</div>

				<div class="flex-1 overflow-hidden rounded-md border shadow-sm">
					<div
						class="bg-primary/95 px-3 py-1.5 text-xs font-bold tracking-wider text-primary-foreground uppercase"
					>
						Datos del Componente
					</div>
					<div class="flex h-[calc(100%-32px)] flex-col justify-between bg-card p-4 text-sm">
						<div class="grid gap-3">
							<div class="grid grid-cols-2 gap-4">
								<div class="flex flex-col">
									<span class="text-xs font-medium text-muted-foreground">Clase:</span>
									<span class="font-mono font-medium text-primary"
										>{tempRelationItem._component_details?.part_class || '-'}</span
									>
								</div>
								<div class="flex flex-col">
									<span class="text-xs font-medium text-muted-foreground">U.M.:</span>
									<span class="font-mono font-medium text-primary"
										>{tempRelationItem._component_details?.uom_class || '-'}</span
									>
								</div>
							</div>

							<div class="mt-2 grid grid-cols-[auto_1fr] gap-x-2 gap-y-1">
								<span class="font-medium text-muted-foreground">Peso Unitario:</span>
								<div class="font-mono font-medium text-primary">
									{Number(tempRelationItem._component_details?.unit_weight || 0).toFixed(8)}
									{tempRelationItem._component_details?.weight_type || ''}
								</div>

								<span class="font-medium text-muted-foreground">Costo Unitario:</span>
								<div class="font-mono font-medium text-primary">
									{Number(tempRelationItem._component_details?.unit_cost || 0).toFixed(8)}
									{tempRelationItem._component_details?.currency_key || ''}
								</div>
							</div>
						</div>

						<div class="mt-6 flex items-center gap-2">
							<input
								id="bom_scrap_dl"
								type="checkbox"
								bind:checked={tempRelationItem._download_scrap}
								class="h-4 w-4 rounded border-gray-300 text-primary focus:ring-primary"
							/>
							<Label for="bom_scrap_dl" class="cursor-pointer text-sm font-medium"
								>Descargar de Desperdicio apartado</Label
							>
						</div>
					</div>
				</div>
			</div>
		</div>
		<Dialog.Footer>
			<Button variant="outline" onclick={() => (showBOMDialog = false)}>Cancelar</Button>
			<Button onclick={saveRelationItem}>Guardar</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<Dialog.Root bind:open={showCountryRelDialog}>
	<Dialog.Content class="z-[200] sm:max-w-6xl">
		<Dialog.Header>
			<Dialog.Title>{currentEditIndex !== null ? 'Editar' : 'Insertar'} País</Dialog.Title>
			<Dialog.Description>
				Configure los detalles del país de origen, preferencia y certificados.
			</Dialog.Description>
		</Dialog.Header>

		<div class="grid max-h-[85vh] gap-6 overflow-y-auto px-1 py-4">
			<div class="rounded-xl border bg-slate-50 p-4 dark:bg-slate-900/30">
				<div class="grid grid-cols-1 gap-6 md:grid-cols-3">
					<div class="space-y-1">
						<span class="text-[10px] font-bold tracking-wider text-muted-foreground uppercase"
							>Producto</span
						>
						<div class="flex items-center gap-2">
							<Package class="h-4 w-4 text-primary" />
							<span class="font-mono text-lg font-bold">{formData.part_number}</span>
						</div>
					</div>
					<div class="space-y-1">
						<span class="text-[10px] font-bold tracking-wider text-muted-foreground uppercase"
							>Fracción Parte</span
						>
						<div class="flex items-center gap-2">
							<Tag class="h-4 w-4 text-primary" />
							<span class="font-mono text-lg font-bold"
								>{formatMexTariffDigitsForDisplay(formData.fraction)}</span
							>
						</div>
					</div>
					<div class="space-y-1">
						<span class="text-[10px] font-bold tracking-wider text-muted-foreground uppercase"
							>Pais por Omisión</span
						>
						<div class="flex gap-4 pt-1">
							<label class="flex items-center gap-2 opacity-70">
								<input
									type="checkbox"
									checked={tempRelationItem.omission_import}
									disabled
									class="h-4 w-4 accent-primary"
								/>
								<span class="text-xs font-semibold">entrada</span>
							</label>
							<label class="flex items-center gap-2 opacity-70">
								<input
									type="checkbox"
									checked={tempRelationItem.omission_export}
									disabled
									class="h-4 w-4 accent-primary"
								/>
								<span class="text-xs font-semibold">salida</span>
							</label>
						</div>
					</div>
				</div>
			</div>

			<div class="grid grid-cols-1 gap-8 lg:grid-cols-12">
				<div class="space-y-6 lg:col-span-4">
					<div class="space-y-4 rounded-xl border bg-card p-5 shadow-sm">
						<h3 class="mb-4 flex items-center gap-2 border-b pb-2 text-sm font-bold">
							<Globe class="h-4 w-4 text-blue-500" /> Datos de Origen
						</h3>

						<div class="grid gap-2">
							<Label for="rel_country" class="text-xs font-semibold">País de Origen</Label>
							<div class="flex gap-2">
								<Input
									id="rel_country"
									bind:value={tempRelationItem.country_code}
									readonly
									class="bg-muted/30 font-mono text-sm"
								/>
								<Button
									size="icon"
									variant="outline"
									class="shrink-0"
									onclick={() => {
										modalContext = 'rel_country';
										showCountryModal = true;
									}}
								>
									<FolderSearch class="h-4 w-4" />
								</Button>
							</div>
						</div>

						<div class="grid gap-2">
							<Label for="rel_preference" class="text-xs font-semibold">Preferencia</Label>
							<Select.Root
								type="single"
								value={tempRelationItem.preference}
								onValueChange={(v) => (tempRelationItem.preference = v)}
							>
								<Select.Trigger id="rel_preference" class="text-xs font-semibold"
									>{tempRelationItem.preference}</Select.Trigger
								>
								<Select.Content class="z-[410]">
									<Select.Item value="GENERAL">GENERAL</Select.Item>
									<Select.Item value="PROSEC">PROSEC</Select.Item>
									<Select.Item value="ALADI">ALADI</Select.Item>
									<Select.Item value="TLCS">TLCS</Select.Item>
								</Select.Content>
							</Select.Root>
						</div>

						<label
							class="group flex cursor-pointer items-center gap-3 rounded-lg border bg-orange-50/20 p-3 transition-colors hover:bg-orange-50/50 dark:bg-orange-950/10"
						>
							<input
								type="checkbox"
								bind:checked={tempRelationItem.previous_fractions_7m}
								class="h-4 w-4 accent-primary"
							/>
							<span class="text-[10px] font-bold text-orange-700 uppercase dark:text-orange-400"
								>Fracciones anteriores a 7 meses</span
							>
						</label>
					</div>

					<div class="space-y-4 rounded-xl border bg-green-50/10 p-5 dark:bg-green-950/5">
						<div class="mb-4 flex items-center justify-between border-b pb-2">
							<h3 class="flex items-center gap-2 text-sm font-bold">
								<ShieldCheck class="h-4 w-4 text-green-500" /> Certificado
							</h3>
							<Switch bind:checked={tempRelationItem.has_certificate} />
						</div>

						{#if tempRelationItem.has_certificate}
							<div class="animate-in slide-in-from-top-2 space-y-4 duration-300">
								<div class="grid gap-2">
									<Label for="rel_cert_num" class="text-xs font-semibold">Número CO</Label>
									<Input
										id="rel_cert_num"
										bind:value={tempRelationItem.certificate_number}
										placeholder="Ej: CO-2024-001"
										class="font-mono text-xs"
										maxlength={50}
									/>
								</div>
								<div class="grid gap-2">
									<Label for="rel_end_date" class="text-xs font-semibold">Fecha Vigencia</Label>
									<Input
										id="rel_end_date"
										type="date"
										bind:value={tempRelationItem.end_date}
										class="text-xs"
									/>
								</div>
							</div>
						{:else}
							<p class="py-4 text-center text-[11px] text-muted-foreground italic">
								No se requiere certificado para esta relación
							</p>
						{/if}
					</div>
				</div>

				<div class="space-y-6 lg:col-span-8">
					<div class="overflow-hidden rounded-xl border bg-card shadow-sm">
						<div class="border-b bg-muted/50 p-3">
							<h3 class="flex items-center gap-2 text-xs font-bold tracking-wider uppercase">
								<ClipboardList class="h-4 w-4" /> Información Arancelaria (Solo Consulta)
							</h3>
						</div>
						<div class="overflow-x-auto">
							<table class="w-full text-xs">
								<thead class="border-b bg-muted/30">
									<tr>
										<th class="px-4 py-2 text-left font-bold">Fracción</th>
										<th class="px-4 py-2 text-center font-bold">UMT</th>
										<th class="px-4 py-2 text-center font-bold">UM</th>
										<th class="px-4 py-2 text-center font-bold">Advalorem Impo</th>
										<th class="px-4 py-2 text-center font-bold">Advalorem Expo</th>
									</tr>
								</thead>
								<tbody class="divide-y">
									<tr>
										<td class="px-4 py-4 font-mono text-sm font-bold"
											>{currentTariffDetails
												? formatMexTariffDigitsForDisplay(
														buildMexTariffDigitsFromCatalogRow(currentTariffDetails)
													)
												: formatMexTariffDigitsForDisplay(formData.fraction)}</td
										>
										<td class="px-4 py-4 text-center">{currentTariffDetails?.umt || '-'}</td>
										<td class="px-4 py-4 text-center">{currentTariffDetails?.um_code || '-'}</td>
										<td class="px-4 py-4 text-center font-bold text-blue-600 dark:text-blue-400">
											{currentTariffDetails?.adv_impo || '-'}
										</td>
										<td
											class="px-4 py-4 text-center font-bold text-orange-600 dark:text-orange-400"
										>
											{currentTariffDetails?.adv_expo || '-'}
										</td>
									</tr>
								</tbody>
							</table>
						</div>
					</div>

					<Tabs.Root
						value={activeCountryTab}
						onValueChange={(v) => (activeCountryTab = v)}
						class="w-full"
					>
						<Tabs.List class="mb-4 grid w-full grid-cols-4">
							<Tabs.Trigger value="descripcion" class="text-[10px] font-bold uppercase"
								>Descripción</Tabs.Trigger
							>
							<Tabs.Trigger value="tlcs" class="text-[10px] font-bold uppercase">TLCS</Tabs.Trigger>
							<Tabs.Trigger value="prosec" class="text-[10px] font-bold uppercase"
								>PROSEC</Tabs.Trigger
							>
							<Tabs.Trigger value="aladi" class="text-[10px] font-bold uppercase"
								>ALADI</Tabs.Trigger
							>
						</Tabs.List>

						<Tabs.Content value="descripcion">
							<div
								class="animate-in fade-in-50 min-h-[150px] space-y-3 rounded-xl border bg-slate-50/50 p-5 duration-300 dark:bg-slate-900/10"
							>
								<h3
									class="flex items-center gap-2 text-xs font-bold tracking-wider text-muted-foreground uppercase"
								>
									<FileText class="h-4 w-4" /> Descripción de la Fracción
								</h3>
								<div
									class="text-sm leading-relaxed font-medium whitespace-pre-wrap text-slate-600 dark:text-slate-400"
								>
									{currentTariffDetails?.description ||
										'No hay descripción disponible para esta fracción.'}
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="tlcs">
							<div
								class="animate-in fade-in-50 min-h-[150px] overflow-hidden rounded-xl border bg-card duration-300"
							>
								<div class="flex items-center justify-between border-b bg-muted/30 p-3">
									<h3
										class="flex items-center gap-2 text-xs font-bold tracking-wider text-muted-foreground uppercase"
									>
										<ShieldCheck class="h-4 w-4" /> Información TLCS
									</h3>
									{#if isLoadingSitar}
										<div
											class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"
										></div>
									{/if}
								</div>
								<div class="overflow-x-auto">
									<table class="w-full text-xs">
										<thead class="border-b bg-muted/10">
											<tr>
												<th class="px-4 py-2 text-left font-bold">País</th>
												<th class="px-4 py-2 text-center font-bold">Tasa</th>
												<th class="px-4 py-2 text-center font-bold">D.O.F</th>
												<th class="px-4 py-2 text-left font-bold">Notas</th>
											</tr>
										</thead>
										<tbody class="divide-y">
											{#each sitarTLCSData as item}
												<tr class="transition-colors hover:bg-muted/5">
													<td class="px-4 py-2 font-bold">{item.PAIS}</td>
													<td class="px-4 py-2 text-center font-mono text-blue-600"
														>{item.TASATXT}</td
													>
													<td class="px-4 py-2 text-center font-mono">{item.DOF || '-'}</td>
													<td
														class="max-w-xs truncate px-4 py-2 text-left text-[10px] text-muted-foreground"
														title={item.NOTAS ?? ''}
													>
														{item.NOTAS || '-'}
													</td>
												</tr>
											{:else}
												<tr>
													<td
														colspan="4"
														class="px-4 py-8 text-center text-muted-foreground italic"
													>
														{#if isLoadingSitar}
															Consultando SITAR...
														{:else}
															No hay información de TLCS disponible para esta fracción.
														{/if}
													</td>
												</tr>
											{/each}
										</tbody>
									</table>
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="prosec">
							<div
								class="animate-in fade-in-50 min-h-[150px] overflow-hidden rounded-xl border bg-card duration-300"
							>
								<div class="flex items-center justify-between border-b bg-muted/30 p-3">
									<h3
										class="flex items-center gap-2 text-xs font-bold tracking-wider text-muted-foreground uppercase"
									>
										<Layers class="h-4 w-4" /> Programa PROSEC
									</h3>
									{#if isLoadingSitar}
										<div
											class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"
										></div>
									{/if}
								</div>
								<div class="overflow-x-auto">
									<table class="w-full text-xs">
										<thead class="border-b bg-muted/10">
											<tr>
												<th class="px-4 py-2 text-left font-bold">Articulo</th>
												<th class="px-4 py-2 text-center font-bold">Sector</th>
												<th class="px-4 py-2 text-center font-bold">Tasa Txt</th>
												<th class="px-4 py-2 text-center font-bold">D.O.F</th>
											</tr>
										</thead>
										<tbody class="divide-y">
											{#each sitarPROSECData as item}
												<tr class="transition-colors hover:bg-muted/5">
													<td
														class="max-w-xs truncate px-4 py-2 text-left font-medium"
														title={item.ARTICULO}>{item.ARTICULO}</td
													>
													<td
														class="bg-blue-50/50 px-4 py-2 text-center font-mono dark:bg-blue-900/10"
														>{item.SECTOR}</td
													>
													<td class="px-4 py-2 text-center font-mono font-bold text-orange-600"
														>{item.TASATXT}</td
													>
													<td class="px-4 py-2 text-center font-mono">{item.DOF || '-'}</td>
												</tr>
											{:else}
												<tr>
													<td
														colspan="4"
														class="px-4 py-8 text-center text-muted-foreground italic"
													>
														{#if isLoadingSitar}
															Consultando SITAR...
														{:else}
															No hay información de PROSEC disponible para esta fracción.
														{/if}
													</td>
												</tr>
											{/each}
										</tbody>
									</table>
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="aladi">
							<div
								class="animate-in fade-in-50 min-h-[150px] overflow-hidden rounded-xl border bg-card duration-300"
							>
								<div class="flex items-center justify-between border-b bg-muted/30 p-3">
									<h3
										class="flex items-center gap-2 text-xs font-bold tracking-wider text-muted-foreground uppercase"
									>
										<Globe class="h-4 w-4" /> Acuerdo ALADI
									</h3>
									{#if isLoadingSitar}
										<div
											class="h-4 w-4 animate-spin rounded-full border-2 border-primary border-t-transparent"
										></div>
									{/if}
								</div>
								<div class="overflow-x-auto">
									<table class="w-full text-xs">
										<thead class="border-b bg-muted/10">
											<tr>
												<th class="px-4 py-2 text-left font-bold">Acuerdo</th>
												<th class="px-4 py-2 text-center font-bold">País</th>
												<th class="px-4 py-2 text-center font-bold">Tasa</th>
												<th class="px-4 py-2 text-center font-bold">D.O.F</th>
											</tr>
										</thead>
										<tbody class="divide-y">
											{#each sitarALADIData as item}
												<tr class="transition-colors hover:bg-muted/5">
													<td class="px-4 py-2 text-left font-medium">{item.ACUERDO}</td>
													<td class="px-4 py-2 text-center font-bold">{item.PAIS}</td>
													<td class="px-4 py-2 text-center font-mono text-green-600"
														>{item.TASATXT}</td
													>
													<td class="px-4 py-2 text-center font-mono">{item.DOF || '-'}</td>
												</tr>
											{:else}
												<tr>
													<td
														colspan="4"
														class="px-4 py-8 text-center text-muted-foreground italic"
													>
														{#if isLoadingSitar}
															Consultando SITAR...
														{:else}
															No hay información de ALADI disponible para esta fracción.
														{/if}
													</td>
												</tr>
											{/each}
										</tbody>
									</table>
								</div>
							</div>
						</Tabs.Content>
					</Tabs.Root>
				</div>
			</div>
		</div>

		<Dialog.Footer class="border-t pt-4">
			<Button variant="outline" onclick={() => (showCountryRelDialog = false)}>Cancelar</Button>
			<Button onclick={saveRelationItem} class="gap-2">
				<Save class="h-4 w-4" /> Guardar Cambios
			</Button>
		</Dialog.Footer>
	</Dialog.Content>
</Dialog.Root>

<style>
	:global(.required::after) {
		content: ' *';
		color: hsl(var(--destructive));
	}
</style>
