<script lang="ts">
	import { userHasDodaCatalogAction } from '$lib/permissions/catalogs/doda-permissions';

	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	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 { Switch } from '$lib/components/ui/switch';
	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 * as RadioGroup from '$lib/components/ui/radio-group';
	import { Separator } from '$lib/components/ui/separator';
	import { companyStore } from '$lib/stores/company.svelte';
	import {
		createDoda,
		updateDoda,
		getDoda,
		type DodaCreate
	} from '$lib/api/dashboard/a76/general_catalogs/doda';
	import {
		ArrowLeft,
		Save,
		RefreshCw,
		FileText,
		LayoutGrid,
		Printer,
		Trash2,
		FolderSearch,
		ShieldCheck,
		LoaderCircle
	} from 'lucide-svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosFormularioDoda } from '$lib/config/shortcuts/dashboard/general_catalogs/doda/edit';
	import ChildDetailTable from '$lib/components/dashboard/general_catalogs/doda/child-detail-table.svelte';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	// 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';

	// 1. Identificación reactiva
	let id = $derived($page.params.id);
	let isEdit = $derived(!!$page.params.id);
	let title = $derived(isEdit ? 'Editar DODA' : 'Nuevo DODA');

	const accessDenied = $derived.by(() => {
		if (!userHasDodaCatalogAction($currentUser, 'view')) {
			return 'Permission denied: cat_doda.view';
		}
		if (!isEdit && !userHasDodaCatalogAction($currentUser, 'create')) {
			return 'Permission denied: cat_doda.create';
		}
		if (isEdit && !userHasDodaCatalogAction($currentUser, 'edit')) {
			return 'Permission denied: cat_doda.edit';
		}
		return null;
	});

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

	// Estados de Modales
	let showBrokerSelector = $state(false);
	let showAduanaSelector = $state(false);
	let showSectionSelector = $state(false);
	let showTransporterSelector = $state(false);

	// Atajos
	useShortcuts(
		'Formulario DODA',
		obtenerAtajosFormularioDoda({
			cambiarPestana: (pestana) => (activeTab = pestana),
			manejarGuardar: () => {
				if (accessDenied) return;
				handleSubmit();
			},
			manejarCerrar: () => goto('/dashboard/general_catalogs/doda')
		})
	);

	function getEmptyForm(): DodaCreate & {
		pedimentos_detail?: any[];
		containers?: any[];
		american_pedimentos?: any[];
		uuid_carta_porte?: string;
	} {
		return {
			integration_number: '',
			doda_date: undefined,
			doda_time: undefined,
			dispatch_customs: '',
			customs_sections: '',
			patent: '',
			pedimentos: '',
			caat: '',
			transport_identification: '',
			fast_id: '',
			operation_type: 'I',
			selected: false,
			user_selected: '',
			last_user: '',
			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, // 2 = DODA, 1 = PITA
			unique_badge_number: '',
			pedimentos_detail: [],
			containers: [],
			american_pedimentos: [],
			uuid_carta_porte: ''
		};
	}

	let formData = $state(getEmptyForm());

	$effect(() => {
		if (accessDenied) return;
		const currentId = $page.params.id;
		const companyId = companyStore.activeCompany?.id;


		if (currentId && companyId) {
			loadDoda(Number(currentId));
		} else if (!currentId) {
			formData = getEmptyForm();
			error = null;
		}
	});

	async function loadDoda(dodaId: number) {
		loading = true;
		try {
			const companyId = companyStore.activeCompany?.id;

			const data = await getDoda(dodaId, companyId);

			if (data) {
				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: '' // Simulated field
				};
			}
		} catch (e) {
			error = 'No se pudo cargar la información del DODA';
		} finally {
			loading = false;
		}
	}

	async function handleSubmit() {
		if (accessDenied) {
			error = accessDenied;
			return;
		}
		error = null;
		loading = true;
		try {
			const companyId = companyStore.activeCompany?.id;
			if (!companyId) throw new Error('Selecciona una compañía');
			if (!formData.patent?.trim()) throw new Error('El Agente Aduanal (Patente) es requerido');

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

			if (isEdit) {
				await updateDoda(Number(id), payload, companyId);
			} else {
				await createDoda(payload, companyId);
			}

			goto('/dashboard/general_catalogs/doda');
		} catch (e: any) {
			error = e.message || 'Error al guardar';
		} finally {
			loading = false;
		}
	}

	const pedimentosColumns = [
		{ header: 'Doda Sysid', key: 'id' },
		{ header: 'Línea Pedimento', key: 'pedimento_line' },
		{ header: 'Patente Autorización', key: 'authorization_patent' },
		{ header: 'Documento', key: 'document' },
		{ header: 'Remesa', key: 'shipment' },
		{ header: 'Cove', key: 'cove' },
		{ header: 'UMC', key: 'umc' },
		{ header: 'Importe Efectivo USD', key: 'effective_amount_usd' },
		{ header: 'Importe Diferencia USD', key: 'difference_amount_usd' },
		{ header: 'DTA NIU', key: 'dta_niu' },
		{ header: 'Articulo 7', key: 'article_7', render: (v: any) => (v ? 'Sí' : 'No') }
	];

	const containersColumns = [
		{ header: 'Contenedor', key: 'container_value' },
		{ header: 'Percinto', key: 'seals' }
	];

	const americanPedimentosColumns = [
		{ header: 'Tipo', key: 'american_pedimento_type' },
		{ header: 'Pedido Americano', key: 'american_pedimento_value' }
	];

	// Handlers de Selección
	function handleBrokerSelect(broker: any) {
		formData.responsible = broker.broker_key || '';
		formData.patent = broker.license || '';
	}

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

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

	function handleTransporterSelect(transporter: any) {
		formData.carrier = transporter.name || '';
	}

	function handleBrokerClear() {
		formData.responsible = '';
		formData.patent = '';
	}
	function handleAduanaClear() {
		formData.dispatch_customs = '';
	}
	function handleSectionClear() {
		formData.customs_sections = '';
	}
	function handleTransporterClear() {
		formData.carrier = '';
	}

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

{#if accessDenied}
	<div class="p-6">
		<ErrorState status={403} error={accessDenied} />
	</div>
{:else}
<div class="space-y-3 p-6 pb-48">
	<!-- Header Estilo Facturas -->
	<div class="flex items-center justify-between">
		<div class="space-y-1">
			<div class="flex items-center gap-3">
				<Button
					variant="ghost"
					size="icon"
					onclick={() => goto('/dashboard/general_catalogs/doda')}
				>
					<ArrowLeft size={20} />
				</Button>
				<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
			</div>
			<p class="text-muted-foreground">Catálogos Generales / Doda</p>
		</div>
	</div>

	<Separator />

	<Tabs.Root bind:value={activeTab} class="w-full">
		<!-- Contenido Principal con Campos Superiores -->
		<div class="space-y-6">
			<!-- Fila Compacta de Datos Principales (Estilo InvoiceTopFields) con líneas blancas entre campos -->
			<div class="grid grid-cols-12 items-end gap-0 pb-3">
				<div class="col-span-3 space-y-1 border-r border-white/20 pr-3">
					<Label
						class="cursor-pointer text-xs leading-none text-muted-foreground transition-colors hover:text-primary"
						onclick={() => (showBrokerSelector = true)}
					>
						Responsable Agentes
					</Label>
					<div class="flex gap-2">
						<Input
							bind:value={formData.responsible}
							class="h-8 flex-1 cursor-pointer bg-background/5 text-sm font-medium transition-colors hover:bg-background/10"
							maxlength={14}
							placeholder="Clave"
							onclick={() => (showBrokerSelector = true)}
							onkeydown={(event) =>
								openOnEnterOrSpace(event, () => (showBrokerSelector = true))}
							tabindex="0"
							readonly
						/>
						<Button
							variant="secondary"
							size="icon"
							type="button"
							onclick={() => (showBrokerSelector = true)}
							class="h-8 w-8 shrink-0 transition-colors hover:bg-background/20"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>
				<div class="col-span-2 space-y-1 border-r border-white/20 px-3">
					<Label
						class="cursor-pointer text-xs leading-none text-muted-foreground transition-colors hover:text-primary"
						onclick={() => (showAduanaSelector = true)}
					>
						Aduana
					</Label>
					<div class="flex gap-2">
						<Input
							bind:value={formData.dispatch_customs}
							class="h-8 flex-1 cursor-pointer bg-background/5 text-sm font-medium transition-colors hover:bg-background/10"
							maxlength={3}
							placeholder="000"
							onclick={() => (showAduanaSelector = true)}
							onkeydown={(event) =>
								openOnEnterOrSpace(event, () => (showAduanaSelector = true))}
							tabindex="0"
							readonly
						/>
						<Button
							variant="outline"
							size="icon"
							type="button"
							onclick={() => (showAduanaSelector = true)}
							class="h-8 w-8 shrink-0 border-white/10 transition-colors hover:bg-background/20"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>
				<div class="col-span-2 space-y-1 border-r border-white/20 px-3">
					<Label
						class="cursor-pointer text-xs leading-none text-muted-foreground transition-colors hover:text-primary"
						onclick={() => (showSectionSelector = true)}
					>
						Sección
					</Label>
					<div class="flex gap-2">
						<Input
							bind:value={formData.customs_sections}
							class="h-8 flex-1 cursor-pointer bg-background/5 text-sm font-medium transition-colors hover:bg-background/10"
							maxlength={3}
							placeholder="000"
							onclick={() => (showSectionSelector = true)}
							onkeydown={(event) =>
								openOnEnterOrSpace(event, () => (showSectionSelector = true))}
							tabindex="0"
							readonly
						/>
						<Button
							variant="outline"
							size="icon"
							type="button"
							onclick={() => (showSectionSelector = true)}
							class="h-8 w-8 shrink-0 border-white/10 transition-colors hover:bg-background/20"
						>
							<FolderSearch class="h-4 w-4" />
						</Button>
					</div>
				</div>
				<div class="col-span-2 space-y-1 pl-3">
					<Label class="text-xs leading-none text-muted-foreground">Operación</Label>
					<Select.Root
						type="single"
						value={formData.operation_type}
						onValueChange={(v) => (formData.operation_type = v)}
					>
						<Select.Trigger class="h-8 border-none bg-background/5 text-sm font-medium shadow-none">
							<span class="truncate"
								>{formData.operation_type === 'E'
									? 'E'
									: formData.operation_type === 'I'
										? 'I'
										: '...'}</span
							>
						</Select.Trigger>
						<Select.Content>
							<Select.Item value="I">I - Importación</Select.Item>
							<Select.Item value="E">E - Exportación</Select.Item>
						</Select.Content>
					</Select.Root>
				</div>
			</div>

			{#if error}
				<div
					class="animate-in fade-in slide-in-from-top-2 mb-6 flex items-center gap-2 rounded-lg border border-destructive/20 bg-destructive/5 p-4 text-sm font-semibold text-destructive"
				>
					<span class="text-lg">⚠️</span>
					{error}
				</div>
			{/if}

			<Tabs.Content value="general" class="animate-in fade-in space-y-6 duration-300 outline-none">
				<!-- Grid de Campos Generales Reorganizado -->
				<div class="grid grid-cols-12 items-start gap-8">
					<!-- Columna 1 (Izquierda): Stack Vertical Principal -->
					<div class="col-span-3 space-y-4">
						<div class="space-y-1.5">
							<Label
								class="cursor-pointer text-xs font-semibold text-muted-foreground uppercase transition-colors hover:text-primary"
								onclick={() => (showTransporterSelector = true)}
							>
								Transportista
							</Label>
							<div class="flex gap-2">
								<Input
									bind:value={formData.carrier}
									placeholder="Transportista"
									class="h-9 flex-1 cursor-pointer text-sm font-medium shadow-sm transition-colors hover:bg-background/5"
									onclick={() => (showTransporterSelector = true)}
									onkeydown={(event) =>
										openOnEnterOrSpace(event, () => (showTransporterSelector = true))}
									tabindex="0"
									readonly
								/>
								<Button
									variant="secondary"
									size="icon"
									type="button"
									onclick={() => (showTransporterSelector = true)}
									class="h-9 w-9 shrink-0 shadow-sm transition-all hover:translate-y-[-1px]"
								>
									<FolderSearch class="h-4 w-4" />
								</Button>
							</div>
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs font-semibold text-muted-foreground uppercase"
								>Identificación</Label
							>
							<Input
								bind:value={formData.transport_identification}
								placeholder="Identificación"
								class="h-9 text-sm font-medium shadow-sm"
							/>
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs font-semibold text-muted-foreground uppercase"
								>No. de Integración</Label
							>
							<Input
								bind:value={formData.integration_number}
								placeholder="Integración"
								class="h-9 bg-muted/20 text-sm font-medium shadow-sm"
							/>
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs font-semibold text-muted-foreground uppercase"
								>Transacción</Label
							>
							<Input
								bind:value={formData.transaction_number}
								placeholder="Transacción"
								class="h-9 text-sm font-medium shadow-sm"
							/>
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs font-semibold text-muted-foreground uppercase">Fast ID</Label>
							<Input
								bind:value={formData.fast_id}
								placeholder="Fast ID"
								class="h-9 text-sm font-medium shadow-sm"
							/>
						</div>
					</div>

					<!-- Columna 4 (Alineada con Operación): Stack de Estatus/Patente -->
					<div class="col-span-3 col-start-8 space-y-4">
						<div class="space-y-1.5">
							<Label class="text-xs font-semibold text-muted-foreground uppercase">CAAT</Label>
							<Input
								bind:value={formData.caat}
								placeholder="CAAT"
								class="h-9 text-sm font-medium shadow-sm"
							/>
						</div>
						<div class="space-y-1.5">
							<Label
								class="cursor-pointer text-xs font-semibold text-muted-foreground uppercase transition-colors hover:text-primary"
								onclick={() => (showBrokerSelector = true)}
							>
								Patente <span class="text-destructive">*</span>
							</Label>
							<div class="flex gap-2">
								<Input
									bind:value={formData.patent}
									maxlength={4}
									placeholder="Patente"
									class="h-9 flex-1 cursor-pointer text-sm font-medium shadow-sm transition-colors hover:bg-background/5"
									onclick={() => (showBrokerSelector = true)}
									onkeydown={(event) =>
										openOnEnterOrSpace(event, () => (showBrokerSelector = true))}
									tabindex="0"
									readonly
								/>
								<Button
									variant="outline"
									size="icon"
									type="button"
									onclick={() => (showBrokerSelector = true)}
									class="h-9 w-9 shrink-0 shadow-sm transition-all hover:translate-y-[-1px]"
								>
									<FolderSearch class="h-4 w-4" />
								</Button>
							</div>
						</div>
						<div class="space-y-1.5">
							<Label class="text-xs font-semibold text-muted-foreground uppercase">Estatus</Label>
							<Select.Root
								type="single"
								value={formData.status}
								onValueChange={(v) => (formData.status = v)}
							>
								<Select.Trigger class="h-9 w-full text-sm font-medium shadow-sm">
									{formData.status || 'Seleccionar...'}
								</Select.Trigger>
								<Select.Content>
									<Select.Item value="PENDIENTE">PENDIENTE</Select.Item>
									<Select.Item value="GENERADO">GENERADO</Select.Item>
									<Select.Item value="ELIMINADO">ELIMINADO</Select.Item>
								</Select.Content>
							</Select.Root>
						</div>
					</div>

					<!-- Fila Horizontal: Despacho y Gafete (A la derecha de Fast ID) -->
					<div class="col-span-12 grid grid-cols-12 items-end gap-8">
						<div class="col-span-3">
							<!-- Espacio vacío para alinear con la primera columna si es necesario -->
						</div>

						<!-- Despacho Aduanero (A la derecha de Fast ID en términos lógicos) -->
						<div class="col-span-4">
							<div
								class="flex items-center justify-between rounded-xl border bg-muted/30 p-4 shadow-inner"
							>
								<Label class="text-xs font-semibold tracking-widest text-muted-foreground uppercase"
									>Despacho Aduanero</Label
								>
								<RadioGroup.Root
									value={formData.customs_clearance?.toString()}
									onValueChange={(v) => (formData.customs_clearance = parseInt(v))}
									class="flex gap-6"
								>
									<div class="flex cursor-pointer items-center space-x-2">
										<RadioGroup.Item value="1" id="pita" class="h-4 w-4 border-primary" />
										<Label for="pita" class="cursor-pointer text-xs font-medium uppercase"
											>PITA</Label
										>
									</div>
									<div class="flex cursor-pointer items-center space-x-2">
										<RadioGroup.Item value="2" id="doda" class="h-4 w-4 border-primary" />
										<Label for="doda" class="cursor-pointer text-xs font-medium uppercase"
											>DODA</Label
										>
									</div>
								</RadioGroup.Root>
							</div>
						</div>

						<!-- Gafete Único (A la derecha de Despacho) -->
						<div class="col-span-4">
							<div class="space-y-1.5">
								<Label class="text-xs font-semibold text-muted-foreground uppercase"
									>Número de gafete único</Label
								>
								<Input
									bind:value={formData.unique_badge_number}
									placeholder="Gafete único"
									class="h-9 text-sm font-medium shadow-sm"
								/>
							</div>
						</div>
					</div>
				</div>

				<!-- Tabla Principal -->
				<div class="pt-4">
					<ChildDetailTable
						title="Detalle de Pedimentos"
						columns={pedimentosColumns}
						data={formData.pedimentos_detail || []}
						class="border-border bg-card shadow-sm"
					/>
				</div>

				<!-- Tablas Inferiores -->
				<div class="grid grid-cols-1 gap-6 pt-4 lg:grid-cols-2">
					<ChildDetailTable
						title="Contenedores"
						columns={containersColumns}
						data={formData.containers || []}
					/>
					<ChildDetailTable
						title="Pedimento Americano"
						columns={americanPedimentosColumns}
						data={formData.american_pedimentos || []}
					/>
				</div>
			</Tabs.Content>

			<Tabs.Content value="sellos" class="animate-in fade-in duration-300 outline-none">
				<div class="max-w-4xl space-y-8 py-4">
					<div class="space-y-1">
						<h2 class="text-xl font-bold tracking-tight">Sellos y Firmas</h2>
						<p class="text-xs font-semibold text-muted-foreground uppercase">
							Validación electrónica ante el SAT
						</p>
					</div>

					<div class="grid grid-cols-1 gap-8">
						<div class="space-y-2">
							<Label class="text-xs font-semibold tracking-wide text-muted-foreground uppercase"
								>Cadena original</Label
							>
							<Textarea
								bind:value={formData.original_chain}
								placeholder="Cadena Original..."
								class="min-h-[120px] w-full border-muted/60 font-mono text-xs font-medium shadow-none"
							/>
						</div>

						<div class="space-y-2">
							<Label class="text-xs font-semibold tracking-wide text-muted-foreground uppercase"
								>Número de certificado</Label
							>
							<Input
								bind:value={formData.serial_number}
								placeholder="Certificado"
								class="w-full border-muted/60 text-sm font-medium shadow-none"
							/>
						</div>

						<div class="space-y-2">
							<Label class="text-xs font-semibold tracking-wide text-muted-foreground uppercase"
								>Firma electrónica</Label
							>
							<Textarea
								bind:value={formData.electronic_signature}
								placeholder="Firma..."
								class="min-h-[100px] w-full border-muted/60 font-mono text-xs font-medium shadow-none"
							/>
						</div>

						<div class="space-y-2">
							<Label class="text-xs font-semibold tracking-wide text-primary uppercase"
								>UUID Carta Porte</Label
							>
							<Input
								bind:value={formData.uuid_carta_porte}
								placeholder="00000000-0000-0000-0000-000000000000"
								class="w-full border-muted/60 font-mono text-sm font-medium shadow-none"
							/>
						</div>

						<div class="space-y-2">
							<Label class="text-xs font-semibold tracking-wide text-muted-foreground uppercase"
								>Número certificado SAT</Label
							>
							<Input
								bind:value={formData.sat_certificate}
								placeholder="Certificado SAT"
								class="w-full border-muted/60 text-sm font-medium shadow-none"
							/>
						</div>

						<div class="space-y-2">
							<Label class="text-xs font-semibold tracking-wide text-muted-foreground uppercase"
								>Firma electrónica SAT (Cadena Original SAT)</Label
							>
							<Textarea
								bind:value={formData.sat_original_chain}
								placeholder="Firma SAT..."
								class="min-h-[120px] w-full border-muted/60 font-mono text-xs font-medium shadow-none"
							/>
						</div>
					</div>
				</div>
			</Tabs.Content>
		</div>

		<!-- Footer fijo con Tabs.List y Botones de Acción -->
		<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">
				<div class="w-full overflow-x-auto pb-2">
					<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-2">
						<Tabs.Trigger value="general" class="whitespace-nowrap">
							<LayoutGrid size={16} class="mr-2" />
							General
						</Tabs.Trigger>
						<Tabs.Trigger value="sellos" class="whitespace-nowrap">
							<ShieldCheck size={16} class="mr-2" />
							Sellos
						</Tabs.Trigger>
					</Tabs.List>
				</div>

				<div class="flex justify-end gap-3">
					<Button
						type="button"
						variant="outline"
						onclick={() => goto('/dashboard/general_catalogs/doda')}
						disabled={loading}
						class="rounded px-8 font-medium"
					>
						Cancelar
					</Button>
					<Button
						onclick={handleSubmit}
						disabled={loading}
						class="min-w-[200px] rounded font-bold uppercase shadow-sm"
					>
						{#if loading}
							<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
							Guardando...
						{:else}
							<Save class="mr-2 h-4 w-4" />
							{isEdit ? 'Guardar Cambios' : 'Crear DODA'}
						{/if}
					</Button>
				</div>
			</div>
		</div>
	</Tabs.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}
	/>
</div>
{/if}
