<script lang="ts">
	import { browser } from '$app/environment';
	import { page } from '$app/state';
	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 Dialog from '$lib/components/ui/dialog';
	import * as Select from '$lib/components/ui/select';
	import * as RadioGroup from '$lib/components/ui/radio-group';
	import { Separator } from '$lib/components/ui/separator';
	import { toast } from 'svelte-sonner';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		addDodaAmericanPedimento,
		addDodaPedimento,
		addDodaContainer,
		updateDodaContainer,
		addDodaSeal,
		createDoda,
		deleteDodaAmericanPedimento,
		deleteDodaContainer,
		deleteDodaSeal,
		updateDoda,
		getDoda,
		type DodaAmericanPedimentoCreate,
		type DodaCreate,
		type DodaContainerCreate,
		type DodaPedimentoCreate
	} from '$lib/api/dashboard/a76/general_catalogs/doda';
	import { customsBrokersApi } from '$lib/api/dashboard/a76/customs-brokers';
	import type { CustomsBroker } from '$lib/api/dashboard/a76/customs-brokers';
	import type { Pedimento } from '$lib/api/dashboard/a76/pedimentos';
	import type { Vehicle } from '$lib/api/dashboard/a76/vehicles';
	import {
		appendPedimentosString,
		isPitaCustomsClearance,
		pedimentoRowFromCatalog,
		syncShipmentsFromPedimentos,
		validateAmericanPedimentoTipo,
		yyyymmddTodayInt
	} from '$lib/components/dashboard/general_catalogs/doda/doda-form-helpers';
	import {
		Save,
		LayoutGrid,
		FolderSearch,
		ShieldCheck,
		LoaderCircle,
		AlertCircle
	} from 'lucide-svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosFormularioDodaPagina } from '$lib/config/shortcuts/dashboard/general_catalogs/doda/edit';
	import ChildDetailTable from '$lib/components/dashboard/general_catalogs/doda/child-detail-table.svelte';
	import {
		dodaFormAmericanTipoMessage,
		dodaFormLocaleFromRuntime,
		dodaFormT,
		type DodaFormKey
	} from '$lib/i18n/doda-form-strings';

	// Modales de Selección
	import BrokerSelectorDialog from '$lib/components/dashboard/export/manifest/modals/broker-selector-dialog.svelte';
	import CustomsSectionSelectorDialog from '$lib/components/dashboard/shared/modals/customs-section-selector-dialog.svelte';
	import TransporterSelectorDialog from '$lib/components/dashboard/export/manifest/modals/transporter-selector-dialog.svelte';
	import VehicleSelectorDialog from '$lib/components/dashboard/export/manifest/modals/vehicle-selector-dialog.svelte';
	import PedimentoSelectorDialog from '$lib/components/dashboard/pedimentos/edit/pedimento-selector-dialog.svelte';

	let {
		dodaIdParam,
		defaultLastUser: defaultLastUserProp = '',
		canMutate = true,
		onClose,
		onCreatedNavigateTo
	}: {
		/** 'new' o id numérico en string; desde ?doda_id= de la URL */
		dodaIdParam: string;
		defaultLastUser?: string;
		canMutate?: boolean;
		onClose: () => void;
		/** Tras crear DODA, actualiza ?doda_id= al id creado (sin desmontar la lista) */
		onCreatedNavigateTo: (dodaId: number) => void;
	} = $props();

	const dodaLoc = $derived.by(() => {
		void page.url.pathname;
		return dodaFormLocaleFromRuntime();
	});

	function t(key: DodaFormKey, params?: Record<string, string | number>) {
		return dodaFormT(dodaFormLocaleFromRuntime(), key, params);
	}

	const id = $derived.by((): number | undefined => {
		if (dodaIdParam === 'new' || dodaIdParam == null) return undefined;
		const n = Number(dodaIdParam);
		if (!Number.isFinite(n) || n < 1) return undefined;
		return n;
	});
	const isEdit = $derived(id != null);
	const title = $derived(dodaFormT(dodaLoc, isEdit ? 'title_edit' : 'title_new'));

	/** Modal principal: cerrar con X / overlay / Escape → volver a la lista anterior */
	let dialogOpen = $state(true);

	function handleFormDialogOpenChange(open: boolean) {
		if (!open && browser) onClose();
	}

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

	/** Validación diferida: no mostrar errores hasta que el usuario interactúe o intente guardar */
	let submitAttempted = $state(false);
	let brokerTouched = $state(false);
	let transportTouched = $state(false);
	let badgeTouched = $state(false);

	/** Índice en `formData.containers` para panel de precintos */
	let selectedContainerIndex = $state<number | null>(null);
	let newSealValue = $state('');
	let sealOpsBusy = $state(false);
	let americanPedBusy = $state(false);

	// Estados de Modales
	let showBrokerSelector = $state(false);
	let showAduanaSelector = $state(false);
	let showSectionSelector = $state(false);
	let showTransporterSelector = $state(false);
	let showVehicleSelector = $state(false);
	let showPedimentoSelector = $state(false);
	let selectedBrokerVuReady = $state(false);
	/** Mientras se consulta el API del agente, no forzar "VU incompleto" (evita parpadeo al guardar/recargar). */
	let vuBrokerCheckPending = $state(false);
	let showSealModal = $state(false);
	let showContainerModal = $state(false);
	let showAmericanPedimentoModal = $state(false);
	let sealModalContext = $state<'selected-panel' | 'container-modal'>('selected-panel');
	let containerModalMode = $state<'create' | 'edit'>('create');
	let containerModalValue = $state('');
	let containerModalTarget = $state<{
		index: number;
		id?: number;
		container_line?: number;
	} | null>(null);
	let containerModalSeals = $state<{ id?: number; seal_line: number; seal_value?: string }[]>([]);
	let containerModalOriginalSealLines = $state<number[]>([]);
	let americanModalType = $state('');
	let americanModalValue = $state('');
	let americanModalTargetIndex = $state<number | null>(null);
	let americanModalTargetIsPersisted = $state(false);
	const americanTypeOptions = $derived([
		{ code: '6', description: dodaFormT(dodaLoc, 'american_cat_6') },
		{ code: '7', description: dodaFormT(dodaLoc, 'american_cat_7') },
		{ code: '8', description: dodaFormT(dodaLoc, 'american_cat_8') }
	]);

	function hasDodaVuConfig(broker?: CustomsBroker | null): boolean {
		const vu = broker?.vu;
		return !!(
			vu &&
			(vu.doda_certificate_path || '').trim() &&
			(vu.doda_key_path || '').trim() &&
			(vu.doda_fiel_access_key || '').trim()
		);
	}

	useShortcuts(
		dodaFormT(dodaLoc, 'shortcuts_scope'),
		obtenerAtajosFormularioDodaPagina({
			cambiarPestana: (pestana) => (activeTab = pestana),
			manejarGuardar: () => {
				if (!canMutate) return;
				handleSubmit();
			},
			manejarCerrar: () => {
				if (browser) onClose();
			}
		})
	);

	function ensureCanMutate(): boolean {
		if (canMutate) return true;
		error = 'Permission denied: cat_doda.create/edit';
		return false;
	}

	function getEmptyForm(): DodaCreate & {
		pedimentos_detail?: any[];
		containers?: any[];
		american_pedimentos?: any[];
		uuid_carta_porte?: string;
	} {
		return {
			integration_number: '',
			doda_date: yyyymmddTodayInt(),
			doda_time: undefined,
			dispatch_customs: '',
			customs_sections: '',
			patent: '',
			pedimentos: '',
			caat: '',
			transport_identification: '',
			fast_id: '',
			operation_type: 'I',
			selected: false,
			user_selected: '',
			last_user: defaultLastUserProp || '',
			responsible: '',
			carrier: '',
			shipments: '',
			pedimento_type: '',
			original_chain: '',
			serial_number: '',
			electronic_signature: '',
			transaction_number: '',
			status: 'PENDIENTE',
			linq_sat_qr: '',
			sat_certificate: '',
			sat_digital_seal: '',
			xml_doda_sent_path: '',
			xml_doda_response_path: '',
			sat_original_chain: '',
			customs_clearance: 2,
			unique_badge_number: '',
			pedimentos_detail: [],
			containers: [],
			american_pedimentos: [],
			uuid_carta_porte: ''
		};
	}

	let formData = $state(getEmptyForm());

	const totalSealCount = $derived(
		(formData.containers || []).reduce((n, c) => n + (c.seals_detail?.length ?? 0), 0)
	);
	const requiresUniqueBadge = $derived(formData.customs_clearance !== 1);
	const missingTransportId = $derived(!(formData.transport_identification || '').trim());
	const missingUniqueBadge = $derived(
		requiresUniqueBadge && !(formData.unique_badge_number || '').trim()
	);
	const missingBrokerVu = $derived(!(formData.responsible || '').trim() || !selectedBrokerVuReady);

	$effect(() => {
		const param = dodaIdParam;
		const companyId = companyStore.activeCompany?.id;
		if (!param || !companyId) return;
		if (param === 'new') {
			formData = getEmptyForm();
			error = null;
			warning = null;
			selectedBrokerVuReady = false;
			vuBrokerCheckPending = false;
			submitAttempted = false;
			brokerTouched = false;
			transportTouched = false;
			badgeTouched = false;
			return;
		}
		const n = Number(param);
		if (Number.isFinite(n) && n > 0) {
			loadDoda(n);
		}
	});

	async function loadDoda(dodaId: number) {
		loading = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			const data = await getDoda(dodaId, companyId);
			if (data) {
				selectedContainerIndex = null;
				newSealValue = '';
				formData = {
					integration_number: data.integration_number || '',
					doda_date: data.doda_date,
					doda_time: data.doda_time,
					dispatch_customs: data.dispatch_customs || '',
					customs_sections: data.customs_sections || '',
					patent: data.patent || '',
					pedimentos: data.pedimentos || '',
					caat: data.caat || '',
					transport_identification: data.transport_identification || '',
					fast_id: data.fast_id || '',
					operation_type: data.operation_type || 'I',
					selected: data.selected || false,
					user_selected: data.user_selected || '',
					last_user: data.last_user || '',
					responsible: data.responsible || '',
					carrier: data.carrier || '',
					shipments: data.shipments || '',
					pedimento_type: data.pedimento_type || '',
					original_chain: data.original_chain || '',
					serial_number: data.serial_number || '',
					electronic_signature: data.electronic_signature || '',
					transaction_number: data.transaction_number || '',
					status: data.status || 'PENDIENTE',
					linq_sat_qr: data.linq_sat_qr || '',
					sat_certificate: data.sat_certificate || '',
					sat_digital_seal: data.sat_digital_seal || '',
					xml_doda_sent_path: data.xml_doda_sent_path || '',
					xml_doda_response_path: data.xml_doda_response_path || '',
					sat_original_chain: data.sat_original_chain || '',
					customs_clearance: data.customs_clearance || 2,
					unique_badge_number: data.unique_badge_number || '',
					pedimentos_detail: data.pedimentos_detail || [],
					containers: data.containers || [],
					american_pedimentos: data.american_pedimentos || [],
					uuid_carta_porte: ''
				};
				warning = null;
				submitAttempted = false;
				brokerTouched = !!(data.responsible || '').trim();
				transportTouched = !!(data.transport_identification || '').trim();
				badgeTouched = !!(data.unique_badge_number || '').trim();
				if ((data.responsible || '').trim()) {
					vuBrokerCheckPending = true;
					try {
						const brokerRes = await customsBrokersApi.get(
							String(data.responsible).trim(),
							String(companyId)
						);
						const broker = (brokerRes as { data?: CustomsBroker }).data ?? (brokerRes as CustomsBroker);
						selectedBrokerVuReady = hasDodaVuConfig(broker);
						if (!selectedBrokerVuReady) {
							warning = t('warn_vu_incomplete');
						} else {
							warning = null;
						}
					} catch {
						selectedBrokerVuReady = false;
						warning = t('warn_vu_fetch');
					} finally {
						vuBrokerCheckPending = false;
					}
				} else {
					selectedBrokerVuReady = false;
					vuBrokerCheckPending = false;
				}
			}
		} catch {
			error = t('load_error');
		} finally {
			loading = false;
		}
	}

	async function persistNewPedimentos(
		dodaId: number,
		rows: { id?: number; authorization_patent?: string; document?: string; shipment?: string; cove?: string; umc?: string }[]
	) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		for (const p of rows) {
			if (p.id) continue;
			const body: DodaPedimentoCreate = {
				authorization_patent: p.authorization_patent,
				document: p.document,
				shipment: p.shipment,
				cove: p.cove,
				umc: p.umc
			};
			await addDodaPedimento(dodaId, body, companyId);
		}
	}

	async function persistNewContainers(
		dodaId: number,
		rows: { id?: number; container_value?: string }[]
	) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		for (const c of rows) {
			if (c.id) continue;
			const v = (c.container_value || '').trim();
			if (!v) continue;
			const body: DodaContainerCreate = { container_value: v };
			await addDodaContainer(dodaId, body, companyId);
		}
	}

	async function persistNewAmericanPedimentos(
		dodaId: number,
		rows: {
			id?: number;
			american_pedimento_type?: string;
			american_pedimento_value?: string;
		}[]
	) {
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) return;
		for (const p of rows) {
			if (p.id) continue;
			const tipo = (p.american_pedimento_type || '').trim();
			const valor = (p.american_pedimento_value || '').trim();
			if (!tipo && !valor) continue;
			const body: DodaAmericanPedimentoCreate = {};
			if (isPitaCustomsClearance(formData.customs_clearance)) {
				body.american_pedimento_type = tipo || undefined;
				body.american_pedimento_value = valor || undefined;
			} else {
				body.american_pedimento_type = tipo;
				body.american_pedimento_value = valor || undefined;
			}
			await addDodaAmericanPedimento(dodaId, body, companyId);
		}
	}

	async function handleAddSeal() {
		if (!ensureCanMutate()) return;
		error = null;
		if (!isEdit || !id) {
			error = t('seal_save_first');
			return;
		}
		if (selectedContainerIndex == null) {
			error = t('seal_pick_container');
			return;
		}
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			error = t('err_company');
			return;
		}
		const row = formData.containers?.[selectedContainerIndex] as
			| { id?: number; container_line?: number }
			| undefined;
		if (!row?.id || row.container_line == null) {
			error = t('seal_not_persisted');
			return;
		}
		const trimmed = newSealValue.trim();
		if (!trimmed) {
			error = t('seal_empty');
			return;
		}
		if (totalSealCount >= 8) {
			error = t('seal_max');
			return;
		}
		sealOpsBusy = true;
		try {
			await addDodaSeal(Number(id), row.container_line, trimmed, companyId);
			newSealValue = '';
			await loadDoda(Number(id));
		} catch (e: unknown) {
			error = e instanceof Error ? e.message : t('seal_add_err');
		} finally {
			sealOpsBusy = false;
		}
	}

	function openSealModal() {
		error = null;
		newSealValue = '';
		sealModalContext = 'selected-panel';
		showSealModal = true;
	}

	function openSealModalForContainerModal() {
		error = null;
		newSealValue = '';
		sealModalContext = 'container-modal';
		showSealModal = true;
	}

	async function handleAddSealFromContainerModal() {
		if (!ensureCanMutate()) return;
		const trimmed = newSealValue.trim();
		if (!trimmed) {
			error = t('seal_empty');
			return;
		}
		const line = (containerModalSeals[containerModalSeals.length - 1]?.seal_line || 0) + 1;
		containerModalSeals = [...containerModalSeals, { seal_line: line, seal_value: trimmed }];
		newSealValue = '';
		showSealModal = false;
	}

	function removeSealFromContainerModal(_: any, idx: number) {
		containerModalSeals = containerModalSeals
			.filter((__, i) => i !== idx)
			.map((s, i) => ({ ...s, seal_line: i + 1 }));
	}

	function openCreateAmericanPedimentoModal() {
		error = null;
		americanModalType = '';
		americanModalValue = '';
		americanModalTargetIndex = null;
		americanModalTargetIsPersisted = false;
		showAmericanPedimentoModal = true;
	}

	function openEditAmericanPedimentoModal(row: any, idx: number) {
		error = null;
		americanModalType = (row?.american_pedimento_type || '').toString();
		americanModalValue = (row?.american_pedimento_value || '').toString();
		americanModalTargetIndex = idx;
		americanModalTargetIsPersisted = !!row?.id;
		showAmericanPedimentoModal = true;
	}

	function handleAmericanPedimentoModalConfirm() {
		if (!ensureCanMutate()) return;
		error = null;
		const tipo = americanModalType.trim();
		const valor = americanModalValue.trim();
		const isPita = isPitaCustomsClearance(formData.customs_clearance);

		if (americanModalTargetIsPersisted) {
			error = t('american_cannot_edit_persisted');
			return;
		}
		if (!isPita) {
			const tipoErr = validateAmericanPedimentoTipo(formData.operation_type, tipo);
			if (tipoErr) {
				error = dodaFormAmericanTipoMessage(dodaFormLocaleFromRuntime(), tipoErr);
				return;
			}
			if (!valor) {
				error = t('err_american_value');
				return;
			}
		} else if (!tipo && !valor) {
			error = t('err_american_type_or_value');
			return;
		}

		const current = [...(formData.american_pedimentos || [])];
		if (americanModalTargetIndex == null) {
			current.push({
				american_pedimento_type: tipo,
				american_pedimento_value: valor,
				american_pedimento_line: current.length + 1
			});
		} else {
			current[americanModalTargetIndex] = {
				...current[americanModalTargetIndex],
				american_pedimento_type: tipo,
				american_pedimento_value: valor
			};
		}
		formData.american_pedimentos = current.map((row, i) => ({
			...row,
			american_pedimento_line: row.american_pedimento_line || i + 1
		}));
		showAmericanPedimentoModal = false;
	}

	async function handleDeleteSeal(sealLine: number) {
		if (!ensureCanMutate()) return;
		error = null;
		if (!isEdit || !id) return;
		if (selectedContainerIndex == null) return;
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			error = t('err_company');
			return;
		}
		const row = formData.containers?.[selectedContainerIndex] as
			| { container_line?: number }
			| undefined;
		if (row?.container_line == null) return;
		sealOpsBusy = true;
		try {
			await deleteDodaSeal(Number(id), row.container_line, sealLine, companyId);
			await loadDoda(Number(id));
		} catch (e: unknown) {
			error = e instanceof Error ? e.message : t('seal_delete_err');
		} finally {
			sealOpsBusy = false;
		}
	}

	async function handleSubmit() {
		if (!ensureCanMutate()) return;
		submitAttempted = true;
		error = null;
		warning = null;
		loading = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) throw new Error(t('err_company'));
			if (!formData.responsible?.trim()) throw new Error(t('err_responsible'));
			if (!formData.patent?.trim()) throw new Error(t('err_patent'));
			if (!formData.transport_identification?.trim()) {
				throw new Error(t('err_transport'));
			}
			if (!formData.unique_badge_number?.trim()) {
				throw new Error(t('err_badge'));
			}
			if (vuBrokerCheckPending) {
				throw new Error(t('err_vu_wait'));
			}
			if (!selectedBrokerVuReady) {
				throw new Error(t('err_vu_config'));
			}
			const filledContainers = (formData.containers || []).filter((c) =>
				(c.container_value || '').trim()
			);
			if (filledContainers.length === 0) {
				throw new Error(t('err_min_containers'));
			}

			const {
				pedimentos_detail: pedRows,
				containers: contRows,
				american_pedimentos: amerRows,
				uuid_carta_porte: _u,
				...formRest
			} = formData;

			for (const row of amerRows || []) {
				const r = row as {
					id?: number;
					american_pedimento_type?: string;
					american_pedimento_value?: string;
				};
				if (r.id) continue;
				const tipo = (r.american_pedimento_type || '').trim();
				const valor = (r.american_pedimento_value || '').trim();
				if (!tipo && !valor) continue;
				if (!isPitaCustomsClearance(formData.customs_clearance)) {
					const tipoErr = validateAmericanPedimentoTipo(formData.operation_type, tipo);
					if (tipoErr) {
						throw new Error(dodaFormAmericanTipoMessage(dodaFormLocaleFromRuntime(), tipoErr));
					}
					if (!valor) {
						throw new Error(t('err_american_new_lines'));
					}
				}
			}

			const payload: DodaCreate = {
				...formRest,
				integration_number: formData.integration_number?.trim() || '',
				doda_date: formData.doda_date || undefined,
				doda_time: formData.doda_time || undefined,
				customs_clearance: formData.customs_clearance || undefined
			};

			let dodaId: number;
			if (isEdit) {
				dodaId = Number(id);
				await updateDoda(dodaId, payload, companyId);
			} else {
				const created = await createDoda(payload, companyId);
				dodaId = created.id;
			}
			if (Array.isArray(pedRows) && pedRows.length > 0) {
				await persistNewPedimentos(
					dodaId,
					pedRows as { id?: number; authorization_patent?: string; document?: string; shipment?: string; cove?: string; umc?: string }[]
				);
			}
			if (Array.isArray(contRows) && contRows.length > 0) {
				await persistNewContainers(
					dodaId,
					contRows as { id?: number; container_value?: string }[]
				);
			}
			if (Array.isArray(amerRows) && amerRows.length > 0) {
				await persistNewAmericanPedimentos(
					dodaId,
					amerRows as {
						id?: number;
						american_pedimento_type?: string;
						american_pedimento_value?: string;
					}[]
				);
			}
			/* Recargar contenedores/ped. americanos con id de servidor. En edición nos quedamos
			   aquí (no al listado) para poder gestionar precintos sin reabrir. DODA nuevo: ir a
			   la URL de edición para que getDoda traiga contenedores persistidos. */
			if (isEdit) {
				await loadDoda(dodaId);
			} else {
				onCreatedNavigateTo(dodaId);
				await loadDoda(dodaId);
			}
			toast.success(isEdit ? t('toast_saved') : t('toast_created'), { duration: 4000 });
		} catch (e: any) {
			const msg = e instanceof Error ? e.message : String(e);
			error = msg || t('err_save');
			toast.error(error, { duration: 6000 });
		} finally {
			loading = false;
		}
	}

	const pedimentosColumns = $derived([
		{ header: dodaFormT(dodaLoc, 'col_line'), key: 'pedimento_line' },
		{ header: dodaFormT(dodaLoc, 'col_auth_patent'), key: 'authorization_patent' },
		{ header: dodaFormT(dodaLoc, 'col_document'), key: 'document' },
		{ header: dodaFormT(dodaLoc, 'col_remesa'), key: 'shipment' },
		{ header: dodaFormT(dodaLoc, 'col_cove'), key: 'cove' },
		{ header: dodaFormT(dodaLoc, 'col_umc'), key: 'umc' },
		{ header: dodaFormT(dodaLoc, 'col_cash_usd'), key: 'effective_amount_usd' },
		{ header: dodaFormT(dodaLoc, 'col_diff_usd'), key: 'difference_amount_usd' },
		{ header: dodaFormT(dodaLoc, 'col_dta_niu'), key: 'dta_niu' },
		{
			header: dodaFormT(dodaLoc, 'col_art7'),
			key: 'article_7',
			render: (v: any) => (v ? dodaFormT(dodaLoc, 'yes') : dodaFormT(dodaLoc, 'no'))
		}
	]);

	const containersColumns = $derived([
		{ header: dodaFormT(dodaLoc, 'col_line'), key: 'container_line' },
		{ header: dodaFormT(dodaLoc, 'col_container'), key: 'container_value' },
		{ header: dodaFormT(dodaLoc, 'col_seals'), key: 'seals' }
	]);

	const containerSealsColumns = $derived([
		{ header: dodaFormT(dodaLoc, 'col_line'), key: 'seal_line' },
		{ header: dodaFormT(dodaLoc, 'col_seal_value'), key: 'seal_value' }
	]);

	const americanPedimentosColumns = $derived(
		isPitaCustomsClearance(formData.customs_clearance)
			? [
					{ header: dodaFormT(dodaLoc, 'col_line'), key: 'american_pedimento_line' },
					{ header: dodaFormT(dodaLoc, 'col_pedimento_only'), key: 'american_pedimento_value' }
				]
			: [
					{ header: dodaFormT(dodaLoc, 'col_line'), key: 'american_pedimento_line' },
					{ header: dodaFormT(dodaLoc, 'col_american_type'), key: 'american_pedimento_type' },
					{ header: dodaFormT(dodaLoc, 'col_american_ped'), key: 'american_pedimento_value' }
				]
	);

	const pedimentosTableTitle = $derived(
		`${dodaFormT(dodaLoc, 'pedimentos')} (${formData.pedimentos_detail?.length ?? 0} ${dodaFormT(dodaLoc, 'lines')})`
	);
	const containersTableTitle = $derived(
		`${dodaFormT(dodaLoc, 'containers')} (${formData.containers?.length ?? 0} / 4)`
	);
	const americanTableTitle = $derived(
		`${dodaFormT(dodaLoc, 'american_pedimentos')} (${formData.american_pedimentos?.length ?? 0})`
	);
	const containerModalSealsTableTitle = $derived(
		`${dodaFormT(dodaLoc, 'modal_seals_in_container')} (${containerModalSeals.length})`
	);

	async function handleBrokerSelect(broker: any) {
		formData.responsible = broker.broker_key || '';
		formData.patent = broker.license || '';
		brokerTouched = true;
		warning = null;
		const companyId = companyStore.activeCompany?.id;
		if (!companyId) {
			vuBrokerCheckPending = false;
			return;
		}
		const key = (broker.broker_key as string) || (broker.license as string);
		if (!key) {
			vuBrokerCheckPending = false;
			return;
		}
		vuBrokerCheckPending = true;
		try {
			const res = await customsBrokersApi.get(key, companyId.toString());
			const b = (res as { data?: any }).data ?? (res as any);
			if (b?.license) formData.patent = String(b.license);
			if (b?.broker_key) formData.responsible = String(b.broker_key);
			const vuOk = hasDodaVuConfig(b as CustomsBroker);
			selectedBrokerVuReady = vuOk;
			if (!vuOk) {
				warning = t('warn_broker_select');
			}
		} catch {
			/* mantiene la selección del diálogo; VU desconocida */
			selectedBrokerVuReady = false;
		} finally {
			vuBrokerCheckPending = false;
		}
	}

	function handleAduanaSelect(section: any) { formData.dispatch_customs = section.customs_code || ''; }
	function handleSectionSelect(section: any) { formData.customs_sections = section.customs_code || ''; }

	function handleBrokerClear() {
		formData.responsible = '';
		formData.patent = '';
		brokerTouched = false;
		warning = null;
		vuBrokerCheckPending = false;
		selectedBrokerVuReady = false;
	}
	function handleAduanaClear() {
		formData.dispatch_customs = '';
	}
	function handleSectionClear() {
		formData.customs_sections = '';
	}
	function handleTransporterClear() {
		formData.carrier = '';
		formData.caat = '';
	}
	function handleVehicleClear() {
		formData.transport_identification = '';
		transportTouched = false;
	}

	function handleTransporterSelect(transporter: any) {
		formData.carrier = transporter.name || '';
		const caat = (transporter.caat_code as string | undefined)?.trim();
		if (caat) formData.caat = caat;
	}

	function handleVehicleSelect(vehicle: Vehicle) {
		const vid =
			(vehicle.transport_identifier && String(vehicle.transport_identifier).trim()) ||
			(vehicle.vehicle_key && String(vehicle.vehicle_key).trim()) || '';
		if (vid) {
			formData.transport_identification = vid;
			transportTouched = true;
		}
	}

	function handlePedimentoSelect(ped: Pedimento) {
		const { row, label } = pedimentoRowFromCatalog(ped, formData.patent);
		const next = [...(formData.pedimentos_detail || []), { ...row }];
		formData.pedimentos_detail = next;
		formData.pedimentos = appendPedimentosString(formData.pedimentos, label);
		formData.shipments = syncShipmentsFromPedimentos(next);
	}

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

	function openCreateContainerModal() {
		const d = formData.containers || [];
		if (d.length >= 4) {
			error = t('err_containers_max');
			return;
		}
		error = null;
		containerModalMode = 'create';
		containerModalValue = '';
		containerModalTarget = null;
		containerModalSeals = [];
		containerModalOriginalSealLines = [];
		showContainerModal = true;
	}

	function openEditContainerModal(row: any, idx: number) {
		error = null;
		containerModalMode = 'edit';
		containerModalValue = (row?.container_value || '').toString();
		containerModalTarget = {
			index: idx,
			id: row?.id,
			container_line: row?.container_line
		};
		const sealsDetail = (row?.seals_detail || []) as Array<{ id?: number; seal_line?: number; seal_value?: string }>;
		if (sealsDetail.length > 0) {
			containerModalSeals = sealsDetail.map((s, i) => ({
				id: s.id,
				seal_line: s.seal_line ?? i + 1,
				seal_value: s.seal_value || ''
			}));
		} else {
			const legacySeals = (row?.seals || '')
				.toString()
				.split(',')
				.map((s: string) => s.trim())
				.filter(Boolean);
			containerModalSeals = legacySeals.map((s: string, i: number) => ({
				seal_line: i + 1,
				seal_value: s
			}));
		}
		containerModalOriginalSealLines = containerModalSeals
			.filter((s) => s.id && s.seal_line != null)
			.map((s) => s.seal_line);
		showContainerModal = true;
	}

	async function handleContainerModalConfirm() {
		error = null;
		const newValue = containerModalValue.trim();
		if (!newValue) {
			error = t('err_container_empty');
			return;
		}

		if (containerModalMode === 'create') {
			const d = formData.containers || [];
			if (d.length >= 4) {
				error = t('err_containers_max');
				return;
			}
			const joinedSeals = containerModalSeals
				.map((s) => (s.seal_value || '').trim())
				.filter(Boolean)
				.join(', ');
			formData.containers = [
				...d,
				{
					container_value: newValue,
					seals: joinedSeals,
					seals_detail: containerModalSeals,
					container_line: d.length + 1
				} as (typeof d)[0]
			];
			showContainerModal = false;
			return;
		}

		if (!containerModalTarget) {
			error = t('err_container_not_found');
			return;
		}

		const companyId = companyStore.activeCompany?.id;
		if (
			containerModalTarget.id &&
			isEdit &&
			id &&
			companyId &&
			containerModalTarget.container_line != null
		) {
			sealOpsBusy = true;
			try {
				await updateDodaContainer(
					Number(id),
					containerModalTarget.container_line,
					{ container_value: newValue },
					companyId
				);
				const deletedSealLines = containerModalOriginalSealLines.filter(
					(line) =>
						!containerModalSeals.some((s) => s.id && s.seal_line === line)
				);
				for (const line of deletedSealLines) {
					await deleteDodaSeal(Number(id), containerModalTarget.container_line, line, companyId);
				}
				const newSeals = containerModalSeals
					.filter((s) => !s.id)
					.map((s) => (s.seal_value || '').trim())
					.filter(Boolean);
				for (const seal of newSeals) {
					await addDodaSeal(Number(id), containerModalTarget.container_line, seal, companyId);
				}
				await loadDoda(Number(id));
				showContainerModal = false;
			} catch (e: unknown) {
				error = e instanceof Error ? e.message : t('container_update_err');
			} finally {
				sealOpsBusy = false;
			}
			return;
		}

		const updated = [...(formData.containers || [])];
		updated[containerModalTarget.index] = {
			...updated[containerModalTarget.index],
			container_value: newValue,
			seals: containerModalSeals
				.map((s) => (s.seal_value || '').trim())
				.filter(Boolean)
				.join(', '),
			seals_detail: containerModalSeals
		};
		formData.containers = updated;
		showContainerModal = false;
	}
</script>

<Dialog.Root bind:open={dialogOpen} onOpenChange={handleFormDialogOpenChange}>
	<Dialog.Content
		class="flex h-[90dvh] max-h-[90dvh] w-[calc(100vw-2rem)] max-w-5xl flex-col gap-0 overflow-hidden border bg-background p-0 shadow-lg sm:max-w-5xl"
		showCloseButton={true}
	>
		<Tabs.Root bind:value={activeTab} class="flex min-h-0 w-full flex-1 flex-col gap-0">
			<Dialog.Header class="shrink-0 space-y-2 border-b px-4 pb-3 pt-3 pr-12 text-left sm:text-left">
				<div class="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between">
					<div class="min-w-0">
						<Dialog.Title class="text-lg font-bold leading-tight">{title}</Dialog.Title>
						<Dialog.Description class="text-xs text-muted-foreground"
							>{dodaFormT(dodaLoc, 'description_catalog')}</Dialog.Description
						>
					</div>
					<div class="flex shrink-0 flex-col items-stretch gap-1.5 sm:items-end">
						<Tabs.List class="inline-flex h-8 shrink-0 items-center gap-0.5 self-end rounded-md bg-muted/50 p-0.5">
							<Tabs.Trigger
								value="general"
								class="h-7 gap-1.5 px-3 text-xs data-[state=active]:bg-background data-[state=active]:shadow-sm"
							>
								<LayoutGrid class="h-3.5 w-3.5 opacity-70" />
								{dodaFormT(dodaLoc, 'tab_general')}
							</Tabs.Trigger>
							<Tabs.Trigger
								value="sellos"
								class="h-7 gap-1.5 px-3 text-xs data-[state=active]:bg-background data-[state=active]:shadow-sm"
							>
								<ShieldCheck class="h-3.5 w-3.5 opacity-70" />
								{dodaFormT(dodaLoc, 'tab_seals_sat')}
							</Tabs.Trigger>
						</Tabs.List>
						<p class="text-end text-[0.65rem] text-muted-foreground">
							{dodaFormT(dodaLoc, 'shortcuts_hint')}
						</p>
					</div>
				</div>
			</Dialog.Header>

			<div class="min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-3">
			<!-- ── Error ──────────────────────────────────────────────────── -->
			{#if error}
				<div
					role="alert"
					class="flex gap-2 rounded-md border border-destructive/25 bg-destructive/5 p-2.5 text-sm text-destructive"
				>
					<AlertCircle class="mt-0.5 h-4 w-4 shrink-0" />
					<p class="font-medium leading-snug">{error}</p>
				</div>
			{/if}
			{#if warning}
				<div
					role="status"
					class="flex gap-2 rounded-md border border-amber-400/35 bg-amber-500/10 p-2.5 text-sm text-amber-700 dark:text-amber-200"
				>
					<AlertCircle class="mt-0.5 h-4 w-4 shrink-0" />
					<p class="font-medium leading-snug">{warning}</p>
				</div>
			{/if}

			<!-- ── 1. Agente aduanal y aduana (siempre visible) ───────────── -->
			<Card.Root class="border-border/50 shadow-sm">
				<Card.Header class="border-b border-border/50 bg-muted/20 px-3 py-2">
					<Card.Title class="text-[0.65rem] font-semibold uppercase tracking-wider text-muted-foreground">
						{dodaFormT(dodaLoc, 'card_broker_customs')}
					</Card.Title>
				</Card.Header>
				<Card.Content class="p-3">
					<!-- 5 columnas: Responsable · Patente · Aduana despacho · Aduana E/S · Operación -->
					<div class="grid grid-cols-1 gap-2.5 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-5">

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground">
								{dodaFormT(dodaLoc, 'label_responsible')} <span class="text-destructive">*</span>
							</Label>
							<div class="flex gap-1.5">
								<Input
									bind:value={formData.responsible}
									class="h-8 min-w-0 flex-1 cursor-pointer text-sm"
									maxlength={14}
									placeholder={dodaFormT(dodaLoc, 'ph_aga')}
									onclick={() => (showBrokerSelector = true)}
									onkeydown={(e) => openOnEnterOrSpace(e, () => (showBrokerSelector = true))}
									readonly
									tabindex="0"
								/>
								<Button variant="secondary" size="icon" type="button" class="h-8 w-8 shrink-0"
									onclick={() => (showBrokerSelector = true)}>
									<FolderSearch class="h-3.5 w-3.5" />
								</Button>
							</div>
							{#if brokerTouched || submitAttempted}
							{#if vuBrokerCheckPending}
								<p class="text-[11px] leading-tight text-muted-foreground">
									{dodaFormT(dodaLoc, 'vu_checking')}
								</p>
							{:else}
								<p class="text-[11px] leading-tight {missingBrokerVu ? 'text-destructive' : 'text-emerald-600'}">
									{#if missingBrokerVu}
										{dodaFormT(dodaLoc, 'vu_incomplete')}
									{:else}
										{dodaFormT(dodaLoc, 'vu_complete')}
									{/if}
								</p>
							{/if}
						{/if}
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground">
								{dodaFormT(dodaLoc, 'label_patent')} <span class="text-destructive">*</span>
							</Label>
							<div class="flex gap-1.5">
								<Input
									bind:value={formData.patent}
									maxlength={4}
									placeholder={dodaFormT(dodaLoc, 'ph_0000')}
									class="h-8 min-w-0 flex-1 cursor-pointer text-sm"
									onclick={() => (showBrokerSelector = true)}
									onkeydown={(e) => openOnEnterOrSpace(e, () => (showBrokerSelector = true))}
									readonly
								/>
								<Button variant="outline" size="icon" type="button" class="h-8 w-8 shrink-0"
									onclick={() => (showBrokerSelector = true)}>
									<FolderSearch class="h-3.5 w-3.5" />
								</Button>
							</div>
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground">
								{dodaFormT(dodaLoc, 'label_dispatch')} <span class="text-destructive">*</span>
							</Label>
							<div class="flex gap-1.5">
								<Input
									bind:value={formData.dispatch_customs}
									class="h-8 min-w-0 flex-1 cursor-pointer text-sm"
									maxlength={3}
									placeholder={dodaFormT(dodaLoc, 'ph_000')}
									onclick={() => (showAduanaSelector = true)}
									onkeydown={(e) => openOnEnterOrSpace(e, () => (showAduanaSelector = true))}
									readonly
									tabindex="0"
								/>
								<Button variant="outline" size="icon" type="button" class="h-8 w-8 shrink-0"
									onclick={() => (showAduanaSelector = true)}>
									<FolderSearch class="h-3.5 w-3.5" />
								</Button>
							</div>
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground"
								>{dodaFormT(dodaLoc, 'label_section_es')}</Label
							>
							<div class="flex gap-1.5">
								<Input
									bind:value={formData.customs_sections}
									class="h-8 min-w-0 flex-1 cursor-pointer text-sm"
									maxlength={3}
									placeholder={dodaFormT(dodaLoc, 'ph_000')}
									onclick={() => (showSectionSelector = true)}
									onkeydown={(e) => openOnEnterOrSpace(e, () => (showSectionSelector = true))}
									readonly
									tabindex="0"
								/>
								<Button variant="outline" size="icon" type="button" class="h-8 w-8 shrink-0"
									onclick={() => (showSectionSelector = true)}>
									<FolderSearch class="h-3.5 w-3.5" />
								</Button>
							</div>
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground"
								>{dodaFormT(dodaLoc, 'label_operation_type')}</Label
							>
							<Select.Root
								type="single"
								value={formData.operation_type}
								onValueChange={(v) => (formData.operation_type = v)}
							>
								<Select.Trigger class="h-8 w-full text-sm">
									{formData.operation_type === 'E'
										? dodaFormT(dodaLoc, 'op_export')
										: dodaFormT(dodaLoc, 'op_import')}
								</Select.Trigger>
								<Select.Content>
									<Select.Item value="I">{dodaFormT(dodaLoc, 'op_import')}</Select.Item>
									<Select.Item value="E">{dodaFormT(dodaLoc, 'op_export')}</Select.Item>
								</Select.Content>
							</Select.Root>
						</div>
					</div>
				</Card.Content>
			</Card.Root>

			<!-- ══ Pestaña General ═══════════════════════════════════════════ -->
			<Tabs.Content value="general" class="animate-in fade-in space-y-3 duration-150 outline-none">

				<!-- ── 2. Transporte ──────────────────────────────────────── -->
				<Card.Root class="border-border/50 shadow-sm">
					<Card.Header class="border-b border-border/50 bg-muted/20 px-3 py-2">
						<Card.Title class="text-[0.65rem] font-semibold uppercase tracking-wider text-muted-foreground">
							{dodaFormT(dodaLoc, 'card_transport')}
						</Card.Title>
					</Card.Header>
					<Card.Content class="p-3">
						<!-- 3 columnas: Transportista · ID transporte · CAAT -->
						<div class="grid grid-cols-1 gap-2.5 sm:grid-cols-3">
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_transporter')}</Label
								>
								<div class="flex gap-1.5">
									<Input
										bind:value={formData.carrier}
										placeholder={dodaFormT(dodaLoc, 'ph_select')}
										class="h-8 min-w-0 flex-1 cursor-pointer text-sm"
										onclick={() => (showTransporterSelector = true)}
										onkeydown={(e) => openOnEnterOrSpace(e, () => (showTransporterSelector = true))}
										readonly
									/>
									<Button variant="secondary" size="icon" type="button" class="h-8 w-8 shrink-0"
										onclick={() => (showTransporterSelector = true)}>
										<FolderSearch class="h-3.5 w-3.5" />
									</Button>
								</div>
							</div>
							<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground">
								{dodaFormT(dodaLoc, 'label_transport_id')} <span class="text-destructive">*</span>
							</Label>
								<div class="flex gap-1.5">
									<Input
										bind:value={formData.transport_identification}
										placeholder={dodaFormT(dodaLoc, 'ph_plate')}
									class="h-8 min-w-0 flex-1 cursor-pointer text-sm {(transportTouched || submitAttempted) && missingTransportId ? 'border-destructive focus-visible:ring-destructive/40' : ''}"
										onclick={() => (showVehicleSelector = true)}
										onkeydown={(e) => openOnEnterOrSpace(e, () => (showVehicleSelector = true))}
										readonly
									/>
									<Button variant="secondary" size="icon" type="button" class="h-8 w-8 shrink-0"
										onclick={() => (showVehicleSelector = true)}>
										<FolderSearch class="h-3.5 w-3.5" />
									</Button>
								</div>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_caat')}</Label
								>
								<Input
									bind:value={formData.caat}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 w-full text-sm"
								/>
							</div>
						</div>
					</Card.Content>
				</Card.Root>

				<!-- ── 3. Control ────────────────────────────────────────── -->
				<Card.Root class="border-border/50 shadow-sm">
					<Card.Header class="border-b border-border/50 bg-muted/20 px-3 py-2">
						<Card.Title class="text-[0.65rem] font-semibold uppercase tracking-wider text-muted-foreground">
							{dodaFormT(dodaLoc, 'card_control')}
						</Card.Title>
					</Card.Header>
					<Card.Content class="space-y-2.5 p-3">

						<!-- Fila A: Fecha · Estatus · Tipo despacho · Gafete único (4 cols) -->
						<div class="grid grid-cols-2 gap-2.5 sm:grid-cols-4">
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_doda_date')}</Label
								>
								<Input
									type="number"
									bind:value={formData.doda_date}
									placeholder={dodaFormT(dodaLoc, 'ph_yyyymmdd')}
									class="h-8 text-sm"
								/>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_status')}</Label
								>
								<Select.Root
									type="single"
									value={formData.status}
									onValueChange={(v) => (formData.status = v)}
								>
									<Select.Trigger class="h-8 w-full text-sm">
										{formData.status || dodaFormT(dodaLoc, 'ph_dash')}
									</Select.Trigger>
									<Select.Content>
										<Select.Item value="PENDIENTE">PENDIENTE</Select.Item>
										<Select.Item value="GENERADO">GENERADO</Select.Item>
										<Select.Item value="EN PROCESO">EN PROCESO</Select.Item>
										<Select.Item value="VALIDADO">VALIDADO</Select.Item>
										<Select.Item value="ERROR">ERROR</Select.Item>
										<Select.Item value="ELIMINADO">ELIMINADO</Select.Item>
									</Select.Content>
								</Select.Root>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_dispatch_type')}</Label
								>
								<div class="flex h-8 items-center gap-4 rounded-md border border-input bg-background px-3">
									<RadioGroup.Root
										value={formData.customs_clearance?.toString()}
										onValueChange={(v) => {
											formData.customs_clearance = parseInt(v, 10);
											if (formData.customs_clearance === 1) formData.unique_badge_number = '';
										}}
										class="flex items-center gap-4"
									>
										<div class="flex items-center gap-1.5">
											<RadioGroup.Item value="1" id="pita" class="h-3.5 w-3.5" />
											<Label for="pita" class="cursor-pointer text-xs font-medium"
												>{dodaFormT(dodaLoc, 'type_pita')}</Label
											>
										</div>
										<div class="flex items-center gap-1.5">
											<RadioGroup.Item value="2" id="doda-type" class="h-3.5 w-3.5" />
											<Label for="doda-type" class="cursor-pointer text-xs font-medium"
												>{dodaFormT(dodaLoc, 'type_doda')}</Label
											>
										</div>
									</RadioGroup.Root>
								</div>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground">
									{dodaFormT(dodaLoc, 'label_unique_badge')}
									{#if requiresUniqueBadge}
										<span class="text-destructive">*</span>
									{/if}
								</Label>
								<Input
									bind:value={formData.unique_badge_number}
									placeholder={formData.customs_clearance === 1
										? dodaFormT(dodaLoc, 'ph_badge_pita')
										: dodaFormT(dodaLoc, 'ph_badge_num')}
								class="h-8 w-full text-sm {(badgeTouched || submitAttempted) && missingUniqueBadge ? 'border-destructive focus-visible:ring-destructive/40' : ''}"
								disabled={formData.customs_clearance === 1}
								onblur={() => { badgeTouched = true; }}
							/>
							{#if requiresUniqueBadge}
								<p class="text-[11px] leading-tight {(badgeTouched || submitAttempted) && missingUniqueBadge ? 'text-destructive' : 'text-muted-foreground'}">
									{dodaFormT(dodaLoc, 'badge_required_hint')}
								</p>
							{/if}
							</div>
						</div>

						<Separator />

						<!-- Fila B: Núm. integración · Núm. transacción · Fast ID · Último usuario (4 cols) -->
						<div class="grid grid-cols-2 gap-2.5 sm:grid-cols-4">
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_integration_num')}</Label
								>
								<Input
									bind:value={formData.integration_number}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 text-sm"
								/>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_transaction_num')}</Label
								>
								<Input
									bind:value={formData.transaction_number}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 text-sm"
								/>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_fast_id')}</Label
								>
								<Input
									bind:value={formData.fast_id}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 text-sm"
								/>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_last_user')}</Label
								>
								<Input
									bind:value={formData.last_user}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 bg-muted/30 text-sm"
									maxlength={30}
									readonly
								/>
							</div>
						</div>
					</Card.Content>
				</Card.Root>

				<!-- ── 4. Pedimentos detalle ──────────────────────────────── -->
				<ChildDetailTable
					locale={dodaLoc}
					title={pedimentosTableTitle}
					bodyMaxClass="max-h-52 overflow-y-auto sm:max-h-56"
					columns={pedimentosColumns}
					data={formData.pedimentos_detail || []}
					onAdd={() => (showPedimentoSelector = true)}
					onEdit={() => (showPedimentoSelector = true)}
					onDelete={(_row, idx) => {
						const d = formData.pedimentos_detail || [];
						if (d[idx]?.id) {
							error = t('pedimento_remove_blocked');
							return;
						}
						formData.pedimentos_detail = d.filter((_, i) => i !== idx);
					}}
					class="border-border bg-card shadow-sm"
				/>

				<!-- ── 5. Contenedores + Pedimentos americanos ────────────── -->
				<div class="grid grid-cols-1 gap-3 lg:grid-cols-2">
					<ChildDetailTable
						locale={dodaLoc}
						title={containersTableTitle}
						bodyMaxClass="max-h-40 overflow-y-auto"
						columns={containersColumns}
						data={formData.containers || []}
						onRowSelect={(_, i) => (selectedContainerIndex = i)}
						onAdd={openCreateContainerModal}
						onEdit={openEditContainerModal}
						onDelete={async (row, idx) => {
							const r = row as { id?: number; container_line?: number };
							const companyId = companyStore.activeCompany?.id;
							if (r.id && isEdit && id && companyId) {
								sealOpsBusy = true;
								error = null;
								try {
									await deleteDodaContainer(Number(id), r.container_line!, companyId);
									selectedContainerIndex = null;
									await loadDoda(Number(id));
								} catch (e: unknown) {
									error = e instanceof Error ? e.message : t('container_delete_err');
								} finally {
									sealOpsBusy = false;
								}
								return;
							}
							formData.containers = (formData.containers || []).filter((_, i) => i !== idx);
							if (selectedContainerIndex === idx) selectedContainerIndex = null;
						}}
					/>
					<ChildDetailTable
						locale={dodaLoc}
						title={americanTableTitle}
						bodyMaxClass="max-h-40 overflow-y-auto"
						columns={americanPedimentosColumns}
						data={formData.american_pedimentos || []}
						onAdd={openCreateAmericanPedimentoModal}
						onEdit={openEditAmericanPedimentoModal}
						onDelete={async (row, idx) => {
							const r = row as { id?: number; american_pedimento_line?: number };
							const companyId = companyStore.activeCompany?.id;
							if (r.id && isEdit && id && companyId) {
								americanPedBusy = true;
								error = null;
								try {
									await deleteDodaAmericanPedimento(Number(id), r.american_pedimento_line!, companyId);
									await loadDoda(Number(id));
								} catch (e: unknown) {
									error = e instanceof Error ? e.message : t('american_delete_err');
								} finally {
									americanPedBusy = false;
								}
								return;
							}
							formData.american_pedimentos = (formData.american_pedimentos || []).filter((_, i) => i !== idx);
						}}
					/>
				</div>

				<!-- Precintos (candados) del contenedor seleccionado -->
				<div class="rounded-lg border border-border/60 bg-card/80 p-3 shadow-sm">
					<h3 class="text-xs font-medium text-muted-foreground">
						{dodaFormT(dodaLoc, 'seals_block_title', { n: totalSealCount })}
					</h3>
					<p class="mt-1 text-xs text-muted-foreground">
						{dodaFormT(dodaLoc, 'seals_help')}
					</p>
					{#if selectedContainerIndex == null}
						<p class="mt-2 text-xs text-muted-foreground">
							{dodaFormT(dodaLoc, 'seals_select_container')}
						</p>
					{:else}
						{@const sel = formData.containers?.[selectedContainerIndex]}
						{#if !sel?.id}
							<p class="mt-2 text-xs text-amber-800 dark:text-amber-200">
								{dodaFormT(dodaLoc, 'container_no_id_warning')}
							</p>
						{:else}
							<p class="mt-2 text-xs">
								{dodaFormT(dodaLoc, 'container_line_info')}
								<span class="font-medium">{sel.container_value || dodaFormT(dodaLoc, 'ph_dash')}</span
								>
								<span class="text-muted-foreground">
									({dodaFormT(dodaLoc, 'line_word').toLowerCase()} {sel.container_line})</span
								>
								— {sel.seals_detail?.length ?? 0}
								{dodaFormT(dodaLoc, 'seal_on_line')}
							</p>
							<ul class="mt-2 max-h-40 space-y-1 overflow-y-auto">
								{#each sel.seals_detail || [] as seal}
									<li
										class="flex items-center justify-between gap-2 rounded border border-border/50 bg-background/50 px-2 py-1.5 text-xs"
									>
										<span
											><span class="text-muted-foreground"
												>{dodaFormT(dodaLoc, 'line_word').toLowerCase()} {seal.seal_line}:</span
											>
											{seal.seal_value ?? dodaFormT(dodaLoc, 'ph_dash')}</span
										>
										<Button
											variant="ghost"
											size="sm"
											class="h-7 shrink-0 px-2 text-xs"
											disabled={sealOpsBusy}
											onclick={() => handleDeleteSeal(seal.seal_line)}
										>
											{dodaFormT(dodaLoc, 'btn_seal_delete')}
										</Button>
									</li>
								{:else}
									<li class="text-xs text-muted-foreground">
										{dodaFormT(dodaLoc, 'seals_empty_line')}
									</li>
								{/each}
							</ul>
							<div class="mt-3 flex flex-wrap items-end gap-2">
								<Button
									size="sm"
									class="h-8"
									disabled={sealOpsBusy || totalSealCount >= 8}
									onclick={openSealModal}
								>
									{dodaFormT(dodaLoc, 'btn_add_seal')}
								</Button>
							</div>
						{/if}
					{/if}
				</div>

			</Tabs.Content>

			<!-- ══ Pestaña Sellos y SAT ══════════════════════════════════════ -->
			<Tabs.Content value="sellos" class="animate-in fade-in space-y-3 duration-150 outline-none">
				<Card.Root class="border-border/50 shadow-sm">
					<Card.Header class="border-b border-border/50 bg-muted/20 px-3 py-2">
						<Card.Title class="text-[0.65rem] font-semibold uppercase tracking-wider text-muted-foreground">
							{dodaFormT(dodaLoc, 'card_sat_chain')}
						</Card.Title>
					</Card.Header>
					<Card.Content class="space-y-3 p-3">

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground"
								>{dodaFormT(dodaLoc, 'label_original_chain')}</Label
							>
							<Textarea
								bind:value={formData.original_chain}
								placeholder={dodaFormT(dodaLoc, 'ph_dash')}
								class="min-h-[4.5rem] w-full resize-y font-mono text-xs leading-relaxed"
							/>
						</div>

						<!-- Núm. serie + UUID carta porte (2 cols) -->
						<div class="grid grid-cols-1 gap-2.5 sm:grid-cols-2">
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_serial_cert')}</Label
								>
								<Input
									bind:value={formData.serial_number}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 w-full text-sm"
								/>
							</div>
							<div class="space-y-1.5">
								<Label class="text-xs font-medium text-muted-foreground"
									>{dodaFormT(dodaLoc, 'label_uuid_cp')}</Label
								>
								<Input
									bind:value={formData.uuid_carta_porte}
									placeholder={dodaFormT(dodaLoc, 'ph_dash')}
									class="h-8 w-full font-mono text-sm"
								/>
							</div>
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground"
								>{dodaFormT(dodaLoc, 'label_electronic_sig')}</Label
							>
							<Textarea
								bind:value={formData.electronic_signature}
								placeholder={dodaFormT(dodaLoc, 'ph_dash')}
								class="min-h-[4rem] w-full resize-y font-mono text-xs leading-relaxed"
							/>
						</div>

						<Separator />

						<!-- Cert. SAT -->
						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground"
								>{dodaFormT(dodaLoc, 'label_sat_cert')}</Label
							>
							<Input
								bind:value={formData.sat_certificate}
								placeholder={dodaFormT(dodaLoc, 'ph_dash')}
								class="h-8 w-full text-sm"
							/>
						</div>

						<div class="space-y-1.5">
							<Label class="text-xs font-medium text-muted-foreground"
								>{dodaFormT(dodaLoc, 'label_sat_chain')}</Label
							>
							<Textarea
								bind:value={formData.sat_original_chain}
								placeholder={dodaFormT(dodaLoc, 'ph_dash')}
								class="min-h-[4rem] w-full resize-y font-mono text-xs leading-relaxed"
							/>
						</div>

					</Card.Content>
				</Card.Root>
			</Tabs.Content>

			</div>

			<Dialog.Footer class="shrink-0 gap-2 border-t px-4 py-3 sm:flex sm:flex-row sm:justify-end">
				<Button
					type="button"
					variant="ghost"
					size="sm"
					class="h-8 px-3 text-xs"
					onclick={() => {
						if (browser) onClose();
					}}
					disabled={loading}
				>
					{dodaFormT(dodaLoc, 'btn_cancel')}
				</Button>
				<Button
					size="sm"
					onclick={handleSubmit}
					disabled={loading || !canMutate}
					class="h-8 min-w-[7rem] px-4 text-sm font-semibold"
				>
					{#if loading}
						<LoaderCircle class="mr-2 h-3.5 w-3.5 shrink-0 animate-spin" />
						{dodaFormT(dodaLoc, 'btn_saving')}
					{:else}
						<Save class="mr-1.5 h-3.5 w-3.5 shrink-0" />
						{isEdit
							? dodaFormT(dodaLoc, 'btn_save_changes')
							: dodaFormT(dodaLoc, 'btn_create_doda')}
					{/if}
				</Button>
			</Dialog.Footer>
		</Tabs.Root>
	</Dialog.Content>
</Dialog.Root>

	<!-- Diálogos de Selección de Catálogos -->
	<BrokerSelectorDialog bind:open={showBrokerSelector} onSelect={handleBrokerSelect} onClear={handleBrokerClear} />
	<CustomsSectionSelectorDialog bind:open={showAduanaSelector} onSelect={handleAduanaSelect} onClear={handleAduanaClear} />
	<CustomsSectionSelectorDialog bind:open={showSectionSelector} onSelect={handleSectionSelect} onClear={handleSectionClear} />
	<TransporterSelectorDialog
		bind:open={showTransporterSelector}
		onSelect={handleTransporterSelect}
		onClear={handleTransporterClear}
	/>
	<VehicleSelectorDialog bind:open={showVehicleSelector} onSelect={handleVehicleSelect} onClear={handleVehicleClear} />
	<PedimentoSelectorDialog bind:open={showPedimentoSelector} onSelect={handlePedimentoSelect} />

	<Dialog.Root bind:open={showContainerModal}>
		<Dialog.Content class="max-w-2xl">
			<Dialog.Header>
				<Dialog.Title>
					{containerModalMode === 'create'
						? dodaFormT(dodaLoc, 'modal_container_new')
						: dodaFormT(dodaLoc, 'modal_container_edit')}
				</Dialog.Title>
				<Dialog.Description>
					{dodaFormT(dodaLoc, 'modal_container_desc')}
				</Dialog.Description>
			</Dialog.Header>
			<div class="space-y-2 py-2">
				<Label for="container-value">{dodaFormT(dodaLoc, 'label_container_value')}</Label>
				<Input
					id="container-value"
					bind:value={containerModalValue}
					maxlength={20}
					placeholder={dodaFormT(dodaLoc, 'ph_example_container')}
				/>
			</div>
			<div class="space-y-2 py-1">
				<ChildDetailTable
					locale={dodaLoc}
					title={containerModalSealsTableTitle}
					bodyMaxClass="max-h-44 overflow-y-auto"
					columns={containerSealsColumns}
					data={containerModalSeals}
					onAdd={openSealModalForContainerModal}
					onEdit={() => {}}
					onDelete={removeSealFromContainerModal}
				/>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showContainerModal = false)}>
					{dodaFormT(dodaLoc, 'btn_cancel')}
				</Button>
				<Button onclick={handleContainerModalConfirm}
					>{dodaFormT(dodaLoc, 'btn_accept')}</Button
				>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<Dialog.Root bind:open={showSealModal}>
		<Dialog.Content class="max-w-md">
			<Dialog.Header>
				<Dialog.Title>{dodaFormT(dodaLoc, 'seal_modal_title')}</Dialog.Title>
				<Dialog.Description>
					{dodaFormT(dodaLoc, 'seal_modal_desc')}
				</Dialog.Description>
			</Dialog.Header>
			<div class="space-y-2 py-2">
				<Label for="seal-value">{dodaFormT(dodaLoc, 'label_seal')}</Label>
				<Input
					id="seal-value"
					bind:value={newSealValue}
					placeholder={dodaFormT(dodaLoc, 'ph_seal')}
					maxlength={21}
					disabled={sealOpsBusy}
				/>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showSealModal = false)} disabled={sealOpsBusy}>
					{dodaFormT(dodaLoc, 'btn_cancel')}
				</Button>
				<Button
					disabled={sealOpsBusy}
					onclick={async () => {
						if (sealModalContext === 'container-modal') {
							await handleAddSealFromContainerModal();
						} else {
							await handleAddSeal();
						}
						if (!error) showSealModal = false;
					}}
				>
					{dodaFormT(dodaLoc, 'btn_accept')}
				</Button>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>

	<Dialog.Root bind:open={showAmericanPedimentoModal}>
		<Dialog.Content class="max-w-lg">
			<Dialog.Header>
				<Dialog.Title>{dodaFormT(dodaLoc, 'american_modal_title')}</Dialog.Title>
				<Dialog.Description>
					{dodaFormT(dodaLoc, 'american_modal_desc')}
				</Dialog.Description>
			</Dialog.Header>
			<div class="space-y-3 py-2">
				<div class="space-y-1.5">
					<Label for="american-type">{dodaFormT(dodaLoc, 'label_american_type_short')}</Label>
					<Select.Root
						type="single"
						value={americanModalType}
						onValueChange={(v) => (americanModalType = v)}
					>
						<Select.Trigger id="american-type" class="h-8 w-full">
							{#if americanModalType}
								{@const selectedType = americanTypeOptions.find((o) => o.code === americanModalType)}
								{selectedType ? `${selectedType.code} - ${selectedType.description}` : americanModalType}
							{:else}
								{dodaFormT(dodaLoc, 'select_type')}
							{/if}
						</Select.Trigger>
						<Select.Content>
							{#each americanTypeOptions as option}
								<Select.Item value={option.code}>
									{option.code} - {option.description}
								</Select.Item>
							{/each}
						</Select.Content>
					</Select.Root>
				</div>
				<div class="space-y-1.5">
					<Label for="american-value">{dodaFormT(dodaLoc, 'label_american_value')}</Label>
					<Input
						id="american-value"
						bind:value={americanModalValue}
						placeholder={dodaFormT(dodaLoc, 'ph_american_value')}
						class="h-8"
					/>
				</div>
				<div class="text-xs text-muted-foreground">
					{dodaFormT(dodaLoc, 'line_label')}
					{(americanModalTargetIndex ?? (formData.american_pedimentos?.length || 0)) + 1}
				</div>
			</div>
			<Dialog.Footer>
				<Button variant="outline" onclick={() => (showAmericanPedimentoModal = false)}>
					{dodaFormT(dodaLoc, 'btn_cancel')}
				</Button>
				<Button onclick={handleAmericanPedimentoModalConfirm}
					>{dodaFormT(dodaLoc, 'btn_accept')}</Button
				>
			</Dialog.Footer>
		</Dialog.Content>
	</Dialog.Root>
