<script lang="ts">
	import { userHasCompanyCatalogAction } from '$lib/permissions/catalogs/company-catalog-permissions';

	import { page } from '$app/stores';
	import { goto } from '$app/navigation';
	import { Button } from '$lib/components/ui/button';
	import { Input, FilePickerInput } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Tabs from '$lib/components/ui/tabs';
	import { Switch } from '$lib/components/ui/switch';
	import * as Card from '$lib/components/ui/card';
	import CountrySelectorDialog from '$lib/components/dashboard/goods/modales/country-selector-dialog.svelte';
	import StateSelectorDialog from '$lib/components/dashboard/shared/modals/state-selector-dialog.svelte';
	import {
		createCompany,
		updateCompany,
		getCompany,
		uploadCompanyLogo,
		uploadCompanyCertificate,
		type Company
	} from '$lib/api/dashboard/a76/general_catalogs/company';
	import { companyStore } from '$lib/stores/company.svelte';
	import { getBackendAssetUrl, getFileDisplayName } from '$lib/utils';
	import { toDbDate, toInputDate } from '$lib/utils/date';
	import {
		ArrowLeft,
		LoaderCircle,
		Save,
		Upload,
		X,
		Globe,
		Building2,
		FileText,
		User,
		Settings,
		MapPin,
		Key,
		ShieldCheck,
		FileSignature,
		Ban
	} from 'lucide-svelte';

	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosFormularioEmpresa } from '$lib/config/shortcuts/dashboard/general_catalogs/company_information/edit';
	import { currentUser } from '$lib/auth';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';

	// 1. Lógica de Navegación y Modo
	const id = $derived($page.params.id);
	const isEdit = $derived(!!id);
	const title = $derived(isEdit ? 'Editar Empresa' : 'Nueva Empresa');
	const canCreate = $derived(userHasCompanyCatalogAction($currentUser, 'create'));
	const canEdit = $derived(userHasCompanyCatalogAction($currentUser, 'edit'));
	const canAccessEditor = $derived((isEdit && canEdit) || (!isEdit && canCreate));
	const canMutate = $derived(isEdit ? canEdit : canCreate);

	let loading = $state(false);
	let uploading = $state(false);
	let error = $state<string | null>(null);
	let successMessage = $state<string | null>(null);
	let activeTab = $state('general');
	let countryModalOpen = $state(false);
	let activeCountryField = $state<'main_country' | 'ind1_country' | 'ind2_country'>('main_country');
	let stateModalOpen = $state(false);
	let activeStateField = $state<'main_state' | 'ind1_state' | 'ind2_state'>('main_state');

	let logoFile = $state<File | null>(null);
	let logoPreview = $state<string | null>(null);
	let currentLogo = $state<string | null>(null);
	let uploadingLogo = $state(false);

	// URL completa del logo derivada
	let currentLogoUrl = $derived(
		logoPreview
			? logoPreview
			: currentLogo
				? getBackendAssetUrl(`v1/a76/company/${id}/logo/image?t=${new Date().getTime()}`)
				: ''
	);

	// 2. Estado Inicial (Reset)
	const initialData = {
		name: '',
		rfc: '',
		curp: '',
		main_activity: '',
		program: '',
		program_number: '',
		prosec: 0,
		prosec_authorization: '',
		responsible_name: '',
		responsible_last_name: '',
		responsible_mother_last_name: '',
		responsible_rfc: '',
		position: '',
		manufacturer_id: '',
		fiscal_deposit: false,
		generate_barcodes_with_fiel: false,
		is_service_company: false,
		order_format_type: '',
		ctpat_svi: '',
		trusted_exporter_number: '',
		logo: '',
		previous_code: 0,
		client_name: '',
		subassembly_mode: '',
		broker_company: '',
		inter_db_name: '',
		prevalidator_key: '',
		seventh_amendment: false,
		// Sectores
		sector1: '',
		sector2: '',
		sector3: '',
		// Certificaciones (CompanyCertification)
		is_certified_company: false,
		certified_company_registration: '',
		certified_company_start_date: '',
		certified_company_end_date: '',
		annex30_certification_date: '',
		annex30_certification_number: '',
		annex30_modality: '',
		annex30_company_type: '',
		annex30_renewal_date: '',
		annex30_final_certification_date: '',
		is_seciit_company: false,
		is_oea_company: false,
		neec_company: false,
		// Dirección Principal
		main_street: '',
		main_exterior_number: '',
		main_interior_number: '',
		main_postal_code: '',
		main_neighborhood: '',
		main_city: '',
		main_municipality: '',
		main_state: '',
		main_country: '',
		main_phone: '',
		main_fax: '',
		main_email: '',
		// Dirección Industrial 1
		ind1_street: '',
		ind1_exterior_number: '',
		ind1_interior_number: '',
		ind1_postal_code: '',
		ind1_neighborhood: '',
		ind1_city: '',
		ind1_municipality: '',
		ind1_state: '',
		ind1_country: '',
		ind1_phone: '',
		ind1_fax: '',
		ind1_email: '',
		// Dirección Industrial 2
		ind2_street: '',
		ind2_exterior_number: '',
		ind2_interior_number: '',
		ind2_postal_code: '',
		ind2_neighborhood: '',
		ind2_city: '',
		ind2_municipality: '',
		ind2_state: '',
		ind2_country: '',
		ind2_phone: '',
		ind2_fax: '',
		ind2_email: '',
		// Configuraciones técnicas (flags)
		active_labels: 0,
		active_fractions: 0,
		activate_caat: 0,
		trans_interface: 0,
		american_costs: 0,
		scaf_readonly: 0,
		parts_replacement: 0,
		activate_facmexame: 0,
		part_reference: 0,
		international_firm: 0,
		// Configuraciones avanzadas
		ftp_key: '',
		sifra_path: '',
		version_type: '',
		sql_language: '',
		balance_operation_mode: '',
		// Prevalidador (CompanyPrevalidator)
		prev_customs: '',
		prev_key: '',
		prev_patent: '',
		prev_description: '',
		// Ventanilla Única (CompanyVU)
		vu_webservice_user: '',
		vu_webservice_password: '',
		vu_email: '',
		vu_figure_type: '',
		vu_central_path: '',
		vu_xml_files_path: '',
		vu_query_rfc: '',
		vu_validation_rfc: '',
		vu_configuration_source: '',
		vu_measurement_units: '',
		// Agente Aduanal Electrónico (CompanyElectronicAgent)
		ea_input_folder: '',
		ea_output_folder: '',
		ea_send_mask: '',
		ea_response_mask: '',
		ea_response_extension: '',
		ea_counter_start: 0,
		ea_counter_end: 0,
		ea_counter_next: 0,
		// CFDI (CompanyCFDI)
		cfdi_xml_save_path: '',
		cfdi_app_path: '',
		cfdi_pac_app_path: '',
		// Certificados Digitales
		fiel_cer: '',
		fiel_key: '',
		fiel_pass: '',
		fiel_access: '',
		fiel_cer_exp: 0,
		fiel_key_exp: 0,
		cfdi_cert_cer: '',
		cfdi_cert_key: '',
		cfdi_cert_pass: '',
		cfdi_cert_access: '',
		cfdi_cert_cer_exp: 0,
		cfdi_cert_key_exp: 0,
		cancel_cer: '',
		cancel_key: '',
		cancel_pass: '',
		cancel_access: '',
		cancel_cer_exp: 0,
		cancel_key_exp: 0
	};

	let formData = $state({ ...initialData });

	// ... (Fetch Data) ...
	$effect(() => {
		if (isEdit) {
			fetchData(String(id));
		} else {
			formData = { ...initialData };
			error = null;
		}
	});

	async function fetchData(companyId: string) {
		if (!canEdit) {
			error = 'Permission denied: cat_company.edit';
			return;
		}
		loading = true;
		try {
			const response = await getCompany(Number(companyId));
			if (response.data) {
				const item = response.data;
				formData = {
					name: item.name || '',
					rfc: item.rfc || '',
					curp: item.curp || '',
					main_activity: item.main_activity || '',
					program: item.program || '',
					program_number: item.program_number || '',
					prosec: item.prosec || 0,
					prosec_authorization: item.prosec_authorization || '',
					responsible_name: item.responsible_name || '',
					responsible_last_name: item.responsible_last_name || '',
					responsible_mother_last_name: item.responsible_mother_last_name || '',
					responsible_rfc: item.responsible_rfc || '',
					position: item.position || '',
					manufacturer_id: item.manufacturer_id || '',
					fiscal_deposit: item.fiscal_deposit || false,
					generate_barcodes_with_fiel: item.generate_barcodes_with_fiel || false,
					is_service_company: item.is_service_company || false,
					order_format_type: item.order_format_type || '',
					ctpat_svi: item.ctpat_svi || '',
					trusted_exporter_number: item.trusted_exporter_number || '',
					logo: item.logo || '',
					previous_code: item.previous_code || 0,
					client_name: item.client_name || '',
					subassembly_mode: item.subassembly_mode || '',
					broker_company: item.broker_company || '',
					inter_db_name: item.inter_db_name || '',
					prevalidator_key: item.prevalidator_key || '',
					seventh_amendment: item.seventh_amendment || false,
					// Sectores
					sector1: item.sector1 || '',
					sector2: item.sector2 || '',
					sector3: item.sector3 || '',
					// Configuraciones técnicas (flags)
					active_labels: item.active_labels || 0,
					active_fractions: item.active_fractions || 0,
					activate_caat: item.activate_caat || 0,
					trans_interface: item.trans_interface || 0,
					american_costs: item.american_costs || 0,
					scaf_readonly: item.scaf_readonly || 0,
					parts_replacement: item.parts_replacement || 0,
					activate_facmexame: item.activate_facmexame || 0,
					part_reference: item.part_reference || 0,
					international_firm: item.international_firm || 0,
					// Configuraciones avanzadas
					ftp_key: item.ftp_key || '',
					sifra_path: item.sifra_path || '',
					version_type: item.version_type || '',
					sql_language: item.sql_language || '',
					balance_operation_mode: item.balance_operation_mode || '',
					// Certificaciones
					is_certified_company: item.is_certified_company || false,
					certified_company_registration: item.certified_company_registration || '',
					certified_company_start_date: toInputDate(item.certified_company_start_date),
					certified_company_end_date: toInputDate(item.certified_company_end_date),
					annex30_certification_date: toInputDate(item.annex30_certification_date),
					annex30_certification_number: item.annex30_certification_number || '',
					annex30_modality: item.annex30_modality || '',
					annex30_company_type: item.annex30_company_type || '',
					annex30_renewal_date: toInputDate(item.annex30_renewal_date),
					annex30_final_certification_date: toInputDate(item.annex30_final_certification_date),
					is_seciit_company: item.is_seciit_company || false,
					is_oea_company: item.is_oea_company || false,
					neec_company: item.neec_company || false,
					// Direcciones - Principal
					main_street: item.main_street || '',
					main_exterior_number: item.main_exterior_number || '',
					main_interior_number: item.main_interior_number || '',
					main_postal_code: item.main_postal_code || '',
					main_neighborhood: item.main_neighborhood || '',
					main_city: item.main_city || '',
					main_municipality: item.main_municipality || '',
					main_state: item.main_state || '',
					main_country: item.main_country || '',
					main_phone: item.main_phone || '',
					main_fax: item.main_fax || '',
					main_email: item.main_email || '',
					// Direcciones - Industrial 1
					ind1_street: item.ind1_street || '',
					ind1_exterior_number: item.ind1_exterior_number || '',
					ind1_interior_number: item.ind1_interior_number || '',
					ind1_postal_code: item.ind1_postal_code || '',
					ind1_neighborhood: item.ind1_neighborhood || '',
					ind1_city: item.ind1_city || '',
					ind1_municipality: item.ind1_municipality || '',
					ind1_state: item.ind1_state || '',
					ind1_country: item.ind1_country || '',
					ind1_phone: item.ind1_phone || '',
					ind1_fax: item.ind1_fax || '',
					ind1_email: item.ind1_email || '',
					// Direcciones - Industrial 2
					ind2_street: item.ind2_street || '',
					ind2_exterior_number: item.ind2_exterior_number || '',
					ind2_interior_number: item.ind2_interior_number || '',
					ind2_postal_code: item.ind2_postal_code || '',
					ind2_neighborhood: item.ind2_neighborhood || '',
					ind2_city: item.ind2_city || '',
					ind2_municipality: item.ind2_municipality || '',
					ind2_state: item.ind2_state || '',
					ind2_country: item.ind2_country || '',
					ind2_phone: item.ind2_phone || '',
					ind2_fax: item.ind2_fax || '',
					ind2_email: item.ind2_email || '',
					// Prevalidador
					prev_customs: item.prev_customs || '',
					prev_key: item.prev_key || '',
					prev_patent: item.prev_patent || '',
					prev_description: item.prev_description || '',
					// Ventanilla Única
					vu_webservice_user: item.vu_webservice_user || '',
					vu_webservice_password: item.vu_webservice_password || '',
					vu_email: item.vu_email || '',
					vu_figure_type: item.vu_figure_type || '',
					vu_central_path: item.vu_central_path || '',
					vu_xml_files_path: item.vu_xml_files_path || '',
					vu_query_rfc: item.vu_query_rfc || '',
					vu_validation_rfc: item.vu_validation_rfc || '',
					vu_configuration_source: item.vu_configuration_source || '',
					vu_measurement_units: item.vu_measurement_units || '',
					// Agente Aduanal Electrónico
					ea_input_folder: item.ea_input_folder || '',
					ea_output_folder: item.ea_output_folder || '',
					ea_send_mask: item.ea_send_mask || '',
					ea_response_mask: item.ea_response_mask || '',
					ea_response_extension: item.ea_response_extension || '',
					ea_counter_start: item.ea_counter_start || 0,
					ea_counter_end: item.ea_counter_end || 0,
					ea_counter_next: item.ea_counter_next || 0,
					// CFDI
					cfdi_xml_save_path: item.cfdi_xml_save_path || '',
					cfdi_app_path: item.cfdi_app_path || '',
					cfdi_pac_app_path: item.cfdi_pac_app_path || '',
					// Certificados Digitales
					fiel_cer: item.fiel_cer || '',
					fiel_key: item.fiel_key || '',
					fiel_pass: item.fiel_pass || '',
					fiel_access: item.fiel_access || '',
					fiel_cer_exp: item.fiel_cer_exp || 0,
					fiel_key_exp: item.fiel_key_exp || 0,
					cfdi_cert_cer: item.cfdi_cert_cer || '',
					cfdi_cert_key: item.cfdi_cert_key || '',
					cfdi_cert_pass: item.cfdi_cert_pass || '',
					cfdi_cert_access: item.cfdi_cert_access || '',
					cfdi_cert_cer_exp: item.cfdi_cert_cer_exp || 0,
					cfdi_cert_key_exp: item.cfdi_cert_key_exp || 0,
					cancel_cer: item.cancel_cer || '',
					cancel_key: item.cancel_key || '',
					cancel_pass: item.cancel_pass || '',
					cancel_access: item.cancel_access || '',
					cancel_cer_exp: item.cancel_cer_exp || 0,
					cancel_key_exp: item.cancel_key_exp || 0
				};

				// Guardar la URL del logo actual si existe
				if (item.logo) {
					currentLogo = item.logo;
				}
			}
		} catch (e) {
			error = 'Error al cargar los datos de la empresa';
		} finally {
			loading = false;
		}
	}

	const clean = (value: any) => (typeof value === 'string' ? value.trim() || null : value);

	function openCountrySelector(field: 'main_country' | 'ind1_country' | 'ind2_country') {
		activeCountryField = field;
		countryModalOpen = true;
	}

	function handleCountrySelect(country: { m3_key: string }) {
		formData[activeCountryField] = country.m3_key;
	}

	function openStateSelector(field: 'main_state' | 'ind1_state' | 'ind2_state') {
		activeStateField = field;
		stateModalOpen = true;
	}

	function handleStateSelect(state: { description: string; m3_key: string }) {
		formData[activeStateField] = state.description;

		const relatedCountryField = activeStateField.replace('_state', '_country') as
			| 'main_country'
			| 'ind1_country'
			| 'ind2_country';

		formData[relatedCountryField] = state.m3_key;
	}

	function handleLogoChange(event: Event) {
		const target = event.target as HTMLInputElement;
		const file = target.files?.[0];

		if (file) {
			// Validar tipo
			const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
			if (!allowedTypes.includes(file.type)) {
				error = 'Tipo de archivo no permitido. Solo JPG, PNG, GIF o WEBP';
				return;
			}

			// Validar tamaño (5MB)
			if (file.size > 5 * 1024 * 1024) {
				error = 'El archivo es demasiado grande. Máximo 5MB';
				return;
			}

			logoFile = file;

			// Crear preview
			const reader = new FileReader();
			reader.onload = (e) => {
				logoPreview = e.target?.result as string;
			};
			reader.readAsDataURL(file);
			error = null;
		}
	}

	function removeLogo() {
		logoFile = null;
		logoPreview = null;
		// Resetear el input
		const input = document.getElementById('logo-input') as HTMLInputElement;
		if (input) input.value = '';
	}

	async function uploadLogo(companyId: number) {
		if (!canMutate) return;
		if (!logoFile) return;

		uploadingLogo = true;
		try {
			const response = await uploadCompanyLogo(companyId, logoFile);
			if (response.error) {
				throw new Error(response.error);
			}
			// Actualizar la ruta del logo actual
			if (response.data?.logo_path) {
				currentLogo = response.data.logo_path;
				logoFile = null;
				logoPreview = null;

				// Actualizar el store reactivamente
				companyStore.updateCompany(companyId, { logo: response.data.logo_path });
			}
		} catch (e: any) {
			error = `Error al subir el logo: ${e.message}`;
		} finally {
			uploadingLogo = false;
		}
	}

	async function handleCertificateFile(file: File, type: string) {
		if (!canMutate) {
			error = 'Permission denied';
			return;
		}
		const ext = file.name.split('.').pop()?.toLowerCase();
		if (type.toLowerCase().endsWith('_cer') && ext !== 'cer') {
			error = 'El archivo debe ser .cer';
			return;
		}
		if (type.toLowerCase().endsWith('_key') && ext !== 'key') {
			error = 'El archivo debe ser .key';
			return;
		}
		if (file.size > 5 * 1024 * 1024) {
			error = 'El archivo es demasiado grande. Máximo 5MB';
			return;
		}
		if (!isEdit) {
			error = 'Debes guardar la empresa primero antes de subir certificados.';
			return;
		}
		loading = true;
		error = null;
		successMessage = null;
		try {
			const response = await uploadCompanyCertificate(Number(id), type, file);
			if (response.error) throw new Error(response.error);
			if (response.data) {
				(formData as any)[type] = response.data.file_path;
				successMessage = `Certificado ${type} subido correctamente`;
			}
		} catch (e: any) {
			error = `Error al subir certificado: ${e.message}`;
		} finally {
			loading = false;
		}
	}
	
	const annex30DurationDays = $derived.by(() => {
		const modalityDaysMap: Record<string, number> = {
			A: 365,
			AA: 730,
			AAA: 1095
		};
		return modalityDaysMap[formData.annex30_modality] ?? 0;
	});

	// Auto-cálculo de fecha de renovación del Anexo 30
	$effect(() => {
		const certDateStr = formData.annex30_certification_date;
		if (certDateStr && annex30DurationDays > 0) {
			// Usamos el formato ISO para evitar problemas de zona horaria al crear el objeto Date
			const certDate = new Date(certDateStr + 'T00:00:00');
			if (!isNaN(certDate.getTime())) {
				const renewalDate = new Date(certDate);
				renewalDate.setDate(certDate.getDate() + annex30DurationDays);
				formData.annex30_renewal_date = renewalDate.toISOString().split('T')[0];
			}
		}
	});

	async function handleSubmit() {
		if (!canMutate) {
			error = isEdit
				? 'Permission denied: cat_company.edit'
				: 'Permission denied: cat_company.create';
			return;
		}
		error = null;
		loading = true;

		try {
			if (!formData.name.trim()) throw new Error('El nombre es requerido');
			if (!formData.rfc.trim()) throw new Error('El RFC es requerido');

			const payload = {
				...formData,
				name: formData.name.trim(),
				rfc: formData.rfc.trim(),
				responsible:
					`${formData.responsible_name} ${formData.responsible_last_name}`.trim() || null,
				curp: clean(formData.curp),
				main_activity: clean(formData.main_activity),
				program: clean(formData.program),
				program_number: clean(formData.program_number),
				prosec: Number(formData.prosec) || 0,
				prosec_authorization: clean(formData.prosec_authorization),
				responsible_name: clean(formData.responsible_name),
				responsible_last_name: clean(formData.responsible_last_name),
				responsible_mother_last_name: clean(formData.responsible_mother_last_name),
				responsible_rfc: clean(formData.responsible_rfc),
				position: clean(formData.position),
				manufacturer_id: clean(formData.manufacturer_id),
				order_format_type: clean(formData.order_format_type),
				ctpat_svi: clean(formData.ctpat_svi),
				trusted_exporter_number: clean(formData.trusted_exporter_number),
				logo: clean(formData.logo),
				previous_code: Number(formData.previous_code) || 0,
				client_name: clean(formData.client_name),
				subassembly_mode: clean(formData.subassembly_mode),
				broker_company: clean(formData.broker_company),
				inter_db_name: clean(formData.inter_db_name),
				prevalidator_key: clean(formData.prevalidator_key),
				seventh_amendment: formData.seventh_amendment,
				// Sectores
				sector1: clean(formData.sector1),
				sector2: clean(formData.sector2),
				sector3: clean(formData.sector3),
				// Configuraciones técnicas (flags)
				active_labels: Number(formData.active_labels) || 0,
				active_fractions: Number(formData.active_fractions) || 0,
				activate_caat: Number(formData.activate_caat) || 0,
				trans_interface: Number(formData.trans_interface) || 0,
				american_costs: Number(formData.american_costs) || 0,
				scaf_readonly: Number(formData.scaf_readonly) || 0,
				parts_replacement: Number(formData.parts_replacement) || 0,
				activate_facmexame: Number(formData.activate_facmexame) || 0,
				part_reference: Number(formData.part_reference) || 0,
				international_firm: Number(formData.international_firm) || 0,
				// Configuraciones avanzadas
				ftp_key: clean(formData.ftp_key),
				sifra_path: clean(formData.sifra_path),
				version_type: clean(formData.version_type),
				sql_language: clean(formData.sql_language),
				balance_operation_mode: clean(formData.balance_operation_mode),
				// Certificaciones
				is_certified_company: formData.is_certified_company,
				certified_company_registration: clean(formData.certified_company_registration),
				certified_company_start_date: toDbDate(formData.certified_company_start_date),
				certified_company_end_date: toDbDate(formData.certified_company_end_date),
				annex30_certification_date: toDbDate(formData.annex30_certification_date),
				annex30_certification_number: clean(formData.annex30_certification_number),
				annex30_modality: clean(formData.annex30_modality),
				annex30_company_type: clean(formData.annex30_company_type),
				annex30_renewal_date: toDbDate(formData.annex30_renewal_date),
				annex30_final_certification_date: toDbDate(formData.annex30_final_certification_date),
				is_seciit_company: formData.is_seciit_company,
				is_oea_company: formData.is_oea_company,
				neec_company: formData.neec_company,
				// Direcciones - Principal
				main_street: clean(formData.main_street),
				main_exterior_number: clean(formData.main_exterior_number),
				main_interior_number: clean(formData.main_interior_number),
				main_postal_code: clean(formData.main_postal_code),
				main_neighborhood: clean(formData.main_neighborhood),
				main_city: clean(formData.main_city),
				main_municipality: clean(formData.main_municipality),
				main_state: clean(formData.main_state),
				main_country: clean(formData.main_country),
				main_phone: clean(formData.main_phone),
				main_fax: clean(formData.main_fax),
				main_email: clean(formData.main_email),
				// Direcciones - Industrial 1
				ind1_street: clean(formData.ind1_street),
				ind1_exterior_number: clean(formData.ind1_exterior_number),
				ind1_interior_number: clean(formData.ind1_interior_number),
				ind1_postal_code: clean(formData.ind1_postal_code),
				ind1_neighborhood: clean(formData.ind1_neighborhood),
				ind1_city: clean(formData.ind1_city),
				ind1_municipality: clean(formData.ind1_municipality),
				ind1_state: clean(formData.ind1_state),
				ind1_country: clean(formData.ind1_country),
				ind1_phone: clean(formData.ind1_phone),
				ind1_fax: clean(formData.ind1_fax),
				ind1_email: clean(formData.ind1_email),
				// Direcciones - Industrial 2
				ind2_street: clean(formData.ind2_street),
				ind2_exterior_number: clean(formData.ind2_exterior_number),
				ind2_interior_number: clean(formData.ind2_interior_number),
				ind2_postal_code: clean(formData.ind2_postal_code),
				ind2_neighborhood: clean(formData.ind2_neighborhood),
				ind2_city: clean(formData.ind2_city),
				ind2_municipality: clean(formData.ind2_municipality),
				ind2_state: clean(formData.ind2_state),
				ind2_country: clean(formData.ind2_country),
				ind2_phone: clean(formData.ind2_phone),
				ind2_fax: clean(formData.ind2_fax),
				ind2_email: clean(formData.ind2_email),
				// Prevalidador
				prev_customs: clean(formData.prev_customs),
				prev_key: clean(formData.prev_key),
				prev_patent: clean(formData.prev_patent),
				prev_description: clean(formData.prev_description),
				// Ventanilla Única
				vu_webservice_user: clean(formData.vu_webservice_user),
				vu_webservice_password: clean(formData.vu_webservice_password),
				vu_email: clean(formData.vu_email),
				vu_figure_type: clean(formData.vu_figure_type),
				vu_central_path: clean(formData.vu_central_path),
				vu_xml_files_path: clean(formData.vu_xml_files_path),
				vu_query_rfc: clean(formData.vu_query_rfc),
				vu_validation_rfc: clean(formData.vu_validation_rfc),
				vu_configuration_source: clean(formData.vu_configuration_source),
				vu_measurement_units: clean(formData.vu_measurement_units),
				// Agente Aduanal Electrónico
				ea_input_folder: clean(formData.ea_input_folder),
				ea_output_folder: clean(formData.ea_output_folder),
				ea_send_mask: clean(formData.ea_send_mask),
				ea_response_mask: clean(formData.ea_response_mask),
				ea_response_extension: clean(formData.ea_response_extension),
				ea_counter_start: Number(formData.ea_counter_start) || 0,
				ea_counter_end: Number(formData.ea_counter_end) || 0,
				ea_counter_next: Number(formData.ea_counter_next) || 0,
				// CFDI
				cfdi_xml_save_path: clean(formData.cfdi_xml_save_path),
				cfdi_app_path: clean(formData.cfdi_app_path),
				cfdi_pac_app_path: clean(formData.cfdi_pac_app_path),
				// Certificados Digitales
				fiel_cer: clean(formData.fiel_cer),
				fiel_key: clean(formData.fiel_key),
				fiel_pass: clean(formData.fiel_pass),
				fiel_access: clean(formData.fiel_access),
				fiel_cer_exp: Number(formData.fiel_cer_exp) || 0,
				fiel_key_exp: Number(formData.fiel_key_exp) || 0,
				cfdi_cert_cer: clean(formData.cfdi_cert_cer),
				cfdi_cert_key: clean(formData.cfdi_cert_key),
				cfdi_cert_pass: clean(formData.cfdi_cert_pass),
				cfdi_cert_access: clean(formData.cfdi_cert_access),
				cfdi_cert_cer_exp: Number(formData.cfdi_cert_cer_exp) || 0,
				cfdi_cert_key_exp: Number(formData.cfdi_cert_key_exp) || 0,
				cancel_cer: clean(formData.cancel_cer),
				cancel_key: clean(formData.cancel_key),
				cancel_pass: clean(formData.cancel_pass),
				cancel_access: clean(formData.cancel_access),
				cancel_cer_exp: Number(formData.cancel_cer_exp) || 0,
				cancel_key_exp: Number(formData.cancel_key_exp) || 0,
				// Ensure optional booleans are passed correctly or default to false/null if needed
				fiscal_deposit: formData.fiscal_deposit,
				generate_barcodes_with_fiel: formData.generate_barcodes_with_fiel,
				is_service_company: formData.is_service_company
			};

			const response = isEdit
				? await updateCompany(Number(id), payload)
				: await createCompany(payload);

			if (response.error) throw new Error(response.error);

			// Si hay un logo para subir y ya tenemos la empresa creada/actualizada
			if (logoFile && response.data?.id) {
				await uploadLogo(response.data.id);
			}

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

	// Atajos
	useShortcuts(
		'Formulario Empresa',
		obtenerAtajosFormularioEmpresa({
			cambiarPestana: (pestana) => (activeTab = pestana),
			manejarGuardar: () => {
				if (!canMutate) return;
				handleSubmit();
			},
			manejarCerrar: () => goto('/dashboard/general_catalogs/company_information')
		})
	);
</script>

{#if !canAccessEditor}
	<div class="p-6">
		<ErrorState status={403} error={isEdit ? 'Permission denied: cat_company.edit' : 'Permission denied: cat_company.create'} />
	</div>
{:else}
<div class="mx-auto w-full max-w-6xl space-y-6 px-4 py-6 pb-48">
	<div class="flex items-center gap-4">
		<Button variant="outline" size="icon" href="/dashboard/general_catalogs/company_information">
			<ArrowLeft class="h-4 w-4" />
		</Button>
		<div>
			<h1 class="text-2xl font-bold tracking-tight">{title}</h1>
			<p class="text-muted-foreground">Configuración legal y operativa de la entidad.</p>
		</div>
	</div>

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

	<form
		onsubmit={(e) => {
			e.preventDefault();
			handleSubmit();
		}}
		class="space-y-6 pb-48"
	>
		<Card.Root>
			<Card.Content class="p-6">
				<Tabs.Root bind:value={activeTab} class="w-full">
					<div class="min-h-[400px]">
						<Tabs.Content value="general" class="space-y-4 pt-4">
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<Label>Logo de la Empresa</Label>
								<div class="flex flex-col gap-4 sm:flex-row sm:items-start">
									{#if logoPreview || currentLogoUrl}
										<div
											class="relative h-32 w-32 overflow-hidden rounded-lg border-2 border-dashed"
										>
											<img
												src={logoPreview || currentLogoUrl}
												alt="Logo preview"
												class="h-full w-full object-contain"
											/>
											{#if logoPreview}
												<button
													type="button"
													onclick={removeLogo}
													class="text-destructive-foreground absolute top-1 right-1 rounded-full bg-destructive p-1 hover:bg-destructive/90"
												>
													<X class="h-3 w-3" />
												</button>
											{/if}
										</div>
									{:else}
										<div
											class="flex h-32 w-32 items-center justify-center rounded-lg border-2 border-dashed bg-muted"
										>
											<Upload class="h-8 w-8 text-muted-foreground" />
										</div>
									{/if}
									<div class="flex-1 space-y-2">
										<Input
											id="logo-input"
											type="file"
											accept="image/jpeg,image/jpg,image/png,image/gif,image/webp"
											onchange={handleLogoChange}
											class="cursor-pointer"
										/>
										<p class="text-xs text-muted-foreground">
											Formatos permitidos: JPG, PNG, GIF, WEBP. Tamaño máximo: 5MB
										</p>
									</div>
								</div>
							</div>

							<div class="grid gap-2">
								<Label for="name">Razón Social <span class="text-destructive">*</span></Label>
								<Input id="name" bind:value={formData.name} placeholder="Nombre oficial" />
							</div>
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="rfc">RFC <span class="text-destructive">*</span></Label>
									<Input id="rfc" bind:value={formData.rfc} maxlength={13} />
								</div>
								<div class="grid gap-2">
									<Label for="curp">CURP</Label>
									<Input id="curp" bind:value={formData.curp} maxlength={18} />
								</div>
							</div>
							<div class="grid gap-2">
								<Label for="main_activity">Actividad Principal</Label>
								<Input id="main_activity" bind:value={formData.main_activity} />
							</div>
							<div class="grid gap-2">
								<Label for="client_name">Nombre Cliente (Maquila)</Label>
								<Input
									id="client_name"
									bind:value={formData.client_name}
									disabled={!formData.is_service_company}
									placeholder={formData.is_service_company ? 'Para Shelters' : 'Disponible para Empresa de Servicios'}
								/>
							</div>
						</Tabs.Content>

						<Tabs.Content value="programa" class="space-y-4 pt-4">
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="program">Programa (IMMEX)</Label>
									<Input id="program" bind:value={formData.program} />
								</div>
								<div class="grid gap-2">
									<Label for="program_number">No. Programa</Label>
									<Input id="program_number" bind:value={formData.program_number} />
								</div>
							</div>
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="prosec">Sector PROSEC (ID)</Label>
									<Input id="prosec" type="number" bind:value={formData.prosec} />
								</div>
								<div class="grid gap-2">
									<Label for="prosec_auth">Autorización PROSEC</Label>
									<Input id="prosec_auth" bind:value={formData.prosec_authorization} />
								</div>
							</div>
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="broker_company">Empresa Broker</Label>
									<Input id="broker_company" bind:value={formData.broker_company} />
								</div>
								<div class="grid gap-2">
									<Label for="subassembly">Selector Para Submaquilar</Label>
									<select
										id="subassembly"
										bind:value={formData.subassembly_mode}
										class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
									>
										<option value="">Seleccionar</option>
										<option value="SI">Si</option>
										<option value="NO">No</option>
									</select>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Sectores</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
									<div class="grid gap-2">
										<Label for="sector1">Sector 1</Label>
										<Input id="sector1" bind:value={formData.sector1} maxlength={150} />
									</div>
									<div class="grid gap-2">
										<Label for="sector2">Sector 2</Label>
										<Input id="sector2" bind:value={formData.sector2} maxlength={150} />
									</div>
									<div class="grid gap-2">
										<Label for="sector3">Sector 3</Label>
										<Input id="sector3" bind:value={formData.sector3} maxlength={5} />
									</div>
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="responsable" class="space-y-4 pt-4">
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="resp_name">Nombre</Label>
									<Input id="resp_name" bind:value={formData.responsible_name} />
								</div>
								<div class="grid gap-2">
									<Label for="resp_last">Apellido Paterno</Label>
									<Input id="resp_last" bind:value={formData.responsible_last_name} />
								</div>
							</div>
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="resp_mother">Apellido Materno</Label>
									<Input id="resp_mother" bind:value={formData.responsible_mother_last_name} />
								</div>
								<div class="grid gap-2">
									<Label for="resp_rfc">RFC Responsable</Label>
									<Input id="resp_rfc" bind:value={formData.responsible_rfc} maxlength={13} />
								</div>
							</div>
							<div class="grid gap-2">
								<Label for="position">Puesto / Cargo</Label>
								<Input id="position" bind:value={formData.position} />
							</div>
						</Tabs.Content>

						<Tabs.Content value="certificaciones" class="space-y-4 pt-4">
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Certificaciones OEA/NEEC</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="ctpat">C-TPAT / SVI</Label>
										<Input id="ctpat" bind:value={formData.ctpat_svi} maxlength={100} />
									</div>
									<div class="grid gap-2">
										<Label for="exporter">No. Exportador Confiable</Label>
										<Input
											id="exporter"
											bind:value={formData.trusted_exporter_number}
											maxlength={50}
										/>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Certificación General</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-3 rounded-lg border p-4 md:col-span-2">
										<label for="is_certified_company" class="flex items-center justify-between gap-3 rounded-md border border-border/60 bg-background/40 px-3 py-2">
											<span class="text-sm font-medium">¿Es Empresa Certificada?</span>
											<Switch
												id="is_certified_company"
												bind:checked={formData.is_certified_company}
											/>
										</label>
										<Label>Tipos de Certificacion</Label>
										<div class="grid grid-cols-1 gap-3 md:grid-cols-3">
											<label class="flex items-center justify-between gap-3 rounded-md border border-border/60 bg-background/40 px-3 py-2 text-sm">
												<span>SECIIT</span>
												<Switch
													id="seciit"
													bind:checked={formData.is_seciit_company}
												/>
											</label>
											<label class="flex items-center justify-between gap-3 rounded-md border border-border/60 bg-background/40 px-3 py-2 text-sm">
												<span>OEA</span>
												<Switch
													id="oea"
													bind:checked={formData.is_oea_company}
												/>
											</label>
											<label class="flex items-center justify-between gap-3 rounded-md border border-border/60 bg-background/40 px-3 py-2 text-sm">
												<span>RFE / NEEC</span>
												<Switch
													id="neec"
													bind:checked={formData.neec_company}
												/>
											</label>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="cert_reg">Registro de Empresa Certificada</Label>
										<Input
											id="cert_reg"
											bind:value={formData.certified_company_registration}
											maxlength={40}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cert_start">Fecha Inicio Certificación</Label>
										<Input
											id="cert_start"
											type="date"
											bind:value={formData.certified_company_start_date}
											placeholder="DD/MM/YYYY"
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cert_end">Fecha Fin Certificación</Label>
										<Input
											id="cert_end"
											type="date"
											bind:value={formData.certified_company_end_date}
											placeholder="DD/MM/YYYY"
										/>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Anexo 30</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="a30_cert_date">Fecha Certificación Anexo 30</Label>
										<Input
											id="a30_cert_date"
											type="date"
											bind:value={formData.annex30_certification_date}
											placeholder="DD/MM/YYYY"
										/>
									</div>
									<div class="grid gap-2">
										<Label for="a30_cert_num">Número Certificación Anexo 30</Label>
										<Input
											id="a30_cert_num"
											bind:value={formData.annex30_certification_number}
											maxlength={50}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="a30_modality">Modalidad Anexo 30</Label>
										<select
											id="a30_modality"
											bind:value={formData.annex30_modality}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value="">Seleccionar</option>
											<option value="A">A</option>
											<option value="AA">AA</option>
											<option value="AAA">AAA</option>
										</select>
									</div>
									<div class="grid gap-2">
										<Label for="a30_type">Tipo de Empresa Anexo 30</Label>
										<select
											id="a30_type"
											bind:value={formData.annex30_company_type}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value="">Seleccionar</option>
											<option value="NO_CERTIFICADA">No Certificada</option>
											<option value="CERTIFICADA">Certificada</option>
											<option value="BAJO_FIANZA">Bajo Fianza</option>
										</select>
									</div>
									<div class="grid gap-2">
										<Label for="a30_renewal">Fecha de Renovación Anexo 30</Label>
										<Input
											id="a30_renewal"
											type="date"
											bind:value={formData.annex30_renewal_date}
											placeholder="DD/MM/YYYY"
										/>
									</div>
									<div class="grid gap-2">
										<Label for="a30_final">Fecha de Cancelación Anexo 30</Label>
										<Input
											id="a30_final"
											type="date"
											bind:value={formData.annex30_final_certification_date}
											placeholder="DD/MM/YYYY"
										/>
									</div>
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="direcciones" class="space-y-4 pt-4">
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Dirección Principal</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="main_street">Calle</Label>
										<Input id="main_street" bind:value={formData.main_street} maxlength={255} />
									</div>
									<div class="grid gap-2">
										<Label for="main_ext_num">Número Exterior</Label>
										<Input
											id="main_ext_num"
											bind:value={formData.main_exterior_number}
											maxlength={10}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="main_int_num">Número Interior</Label>
										<Input
											id="main_int_num"
											bind:value={formData.main_interior_number}
											maxlength={10}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="main_postal">Código Postal</Label>
										<Input id="main_postal" bind:value={formData.main_postal_code} maxlength={5} />
									</div>
									<div class="grid gap-2">
										<Label for="main_neighborhood">Colonia</Label>
										<Input
											id="main_neighborhood"
											bind:value={formData.main_neighborhood}
											maxlength={40}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="main_city">Ciudad</Label>
										<Input id="main_city" bind:value={formData.main_city} maxlength={40} />
									</div>
									<div class="grid gap-2">
										<Label for="main_municipality">Municipio</Label>
										<Input
											id="main_municipality"
											bind:value={formData.main_municipality}
											maxlength={50}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="main_state">Estado</Label>
										<div class="flex gap-2">
											<Input
												id="main_state"
												bind:value={formData.main_state}
												maxlength={30}
												readonly
											/>
											<Button
												type="button"
												variant="outline"
												size="icon"
												onclick={() => openStateSelector('main_state')}
												disabled={loading}
												title="Buscar Estado"
											>
												<MapPin class="h-4 w-4" />
											</Button>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="main_country">País</Label>
										<div class="flex gap-2">
											<Input
												id="main_country"
												bind:value={formData.main_country}
												maxlength={4}
												placeholder="MEX"
												readonly
											/>
											<Button
												type="button"
												variant="outline"
												size="icon"
												onclick={() => openCountrySelector('main_country')}
												disabled={loading}
												title="Buscar País"
											>
												<Globe class="h-4 w-4" />
											</Button>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="main_phone">Teléfono</Label>
										<Input id="main_phone" bind:value={formData.main_phone} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="main_fax">Fax</Label>
										<Input id="main_fax" bind:value={formData.main_fax} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="main_email">Email</Label>
										<Input
											id="main_email"
											type="email"
											bind:value={formData.main_email}
											maxlength={255}
										/>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Dirección Industrial 1</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="ind1_street">Calle</Label>
										<Input id="ind1_street" bind:value={formData.ind1_street} maxlength={255} />
									</div>
									<div class="grid gap-2">
										<Label for="ind1_ext_num">Número Exterior</Label>
										<Input
											id="ind1_ext_num"
											bind:value={formData.ind1_exterior_number}
											maxlength={10}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind1_int_num">Número Interior</Label>
										<Input
											id="ind1_int_num"
											bind:value={formData.ind1_interior_number}
											maxlength={10}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind1_postal">Código Postal</Label>
										<Input id="ind1_postal" bind:value={formData.ind1_postal_code} maxlength={5} />
									</div>
									<div class="grid gap-2">
										<Label for="ind1_neighborhood">Colonia</Label>
										<Input
											id="ind1_neighborhood"
											bind:value={formData.ind1_neighborhood}
											maxlength={40}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind1_city">Ciudad</Label>
										<Input id="ind1_city" bind:value={formData.ind1_city} maxlength={40} />
									</div>
									<div class="grid gap-2">
										<Label for="ind1_municipality">Municipio</Label>
										<Input
											id="ind1_municipality"
											bind:value={formData.ind1_municipality}
											maxlength={50}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind1_state">Estado</Label>
										<div class="flex gap-2">
											<Input
												id="ind1_state"
												bind:value={formData.ind1_state}
												maxlength={30}
												readonly
											/>
											<Button
												type="button"
												variant="outline"
												size="icon"
												onclick={() => openStateSelector('ind1_state')}
												disabled={loading}
												title="Buscar Estado"
											>
												<MapPin class="h-4 w-4" />
											</Button>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="ind1_country">País</Label>
										<div class="flex gap-2">
											<Input
												id="ind1_country"
												bind:value={formData.ind1_country}
												maxlength={4}
												placeholder="MEX"
												readonly
											/>
											<Button
												type="button"
												variant="outline"
												size="icon"
												onclick={() => openCountrySelector('ind1_country')}
												disabled={loading}
												title="Buscar País"
											>
												<Globe class="h-4 w-4" />
											</Button>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="ind1_phone">Teléfono</Label>
										<Input id="ind1_phone" bind:value={formData.ind1_phone} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="ind1_fax">Fax</Label>
										<Input id="ind1_fax" bind:value={formData.ind1_fax} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="ind1_email">Email</Label>
										<Input
											id="ind1_email"
											type="email"
											bind:value={formData.ind1_email}
											maxlength={255}
										/>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Dirección Industrial 2</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="ind2_street">Calle</Label>
										<Input id="ind2_street" bind:value={formData.ind2_street} maxlength={255} />
									</div>
									<div class="grid gap-2">
										<Label for="ind2_ext_num">Número Exterior</Label>
										<Input
											id="ind2_ext_num"
											bind:value={formData.ind2_exterior_number}
											maxlength={10}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind2_int_num">Número Interior</Label>
										<Input
											id="ind2_int_num"
											bind:value={formData.ind2_interior_number}
											maxlength={10}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind2_postal">Código Postal</Label>
										<Input id="ind2_postal" bind:value={formData.ind2_postal_code} maxlength={5} />
									</div>
									<div class="grid gap-2">
										<Label for="ind2_neighborhood">Colonia</Label>
										<Input
											id="ind2_neighborhood"
											bind:value={formData.ind2_neighborhood}
											maxlength={40}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind2_city">Ciudad</Label>
										<Input id="ind2_city" bind:value={formData.ind2_city} maxlength={40} />
									</div>
									<div class="grid gap-2">
										<Label for="ind2_municipality">Municipio</Label>
										<Input
											id="ind2_municipality"
											bind:value={formData.ind2_municipality}
											maxlength={50}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ind2_state">Estado</Label>
										<div class="flex gap-2">
											<Input
												id="ind2_state"
												bind:value={formData.ind2_state}
												maxlength={30}
												readonly
											/>
											<Button
												type="button"
												variant="outline"
												size="icon"
												onclick={() => openStateSelector('ind2_state')}
												disabled={loading}
												title="Buscar Estado"
											>
												<MapPin class="h-4 w-4" />
											</Button>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="ind2_country">País</Label>
										<div class="flex gap-2">
											<Input
												id="ind2_country"
												bind:value={formData.ind2_country}
												maxlength={4}
												placeholder="MEX"
												readonly
											/>
											<Button
												type="button"
												variant="outline"
												size="icon"
												onclick={() => openCountrySelector('ind2_country')}
												disabled={loading}
												title="Buscar País"
											>
												<Globe class="h-4 w-4" />
											</Button>
										</div>
									</div>
									<div class="grid gap-2">
										<Label for="ind2_phone">Teléfono</Label>
										<Input id="ind2_phone" bind:value={formData.ind2_phone} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="ind2_fax">Fax</Label>
										<Input id="ind2_fax" bind:value={formData.ind2_fax} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="ind2_email">Email</Label>
										<Input
											id="ind2_email"
											type="email"
											bind:value={formData.ind2_email}
											maxlength={255}
										/>
									</div>
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="config" class="space-y-4 pt-4">
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Configuración General</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
									<div class="grid gap-2">
										<Label for="is_service_company">Empresa de Servicios?</Label>
										<select
											id="is_service_company"
											bind:value={formData.is_service_company}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value={true}>Sí</option>
											<option value={false}>No</option>
										</select>
									</div>
									<div class="grid gap-2">
										<Label for="fiscal_deposit">Deposito Fiscal</Label>
										<select
											id="fiscal_deposit"
											bind:value={formData.fiscal_deposit}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value={true}>Sí</option>
											<option value={false}>No</option>
										</select>
									</div>
										<label class="flex items-center gap-3 rounded-lg border p-4">
											<Switch id="generate_fiel_barcodes" bind:checked={formData.generate_barcodes_with_fiel} />
											<Label for="generate_fiel_barcodes">Generar Codigos de barras con FIEL</Label>
										</label>
									<div class="flex items-center gap-3 rounded-lg border p-4">
										<Switch id="seventh" bind:checked={formData.seventh_amendment} />
										<Label for="seventh">Séptima Enmienda</Label>
									</div>
									<div class="grid gap-2">
										<Label for="previous_code">Código Anterior</Label>
										<Input id="previous_code" type="number" bind:value={formData.previous_code} />
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Configuraciones Técnicas</h3>
								<div class="grid grid-cols-2 gap-4 md:grid-cols-5">
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="active_labels"
											checked={formData.active_labels === 1}
											onCheckedChange={(checked) => (formData.active_labels = checked ? 1 : 0)}
										/>
										<Label for="active_labels" class="text-xs">Etiquetas Activas</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="active_fractions"
											checked={formData.active_fractions === 1}
											onCheckedChange={(checked) => (formData.active_fractions = checked ? 1 : 0)}
										/>
										<Label for="active_fractions" class="text-xs">Fracciones Activas</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="activate_caat"
											checked={formData.activate_caat === 1}
											onCheckedChange={(checked) => (formData.activate_caat = checked ? 1 : 0)}
										/>
										<Label for="activate_caat" class="text-xs">Activar CAAT</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="trans_interface"
											checked={formData.trans_interface === 1}
											onCheckedChange={(checked) => (formData.trans_interface = checked ? 1 : 0)}
										/>
										<Label for="trans_interface" class="text-xs">Interfaz Trans</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="american_costs"
											checked={formData.american_costs === 1}
											onCheckedChange={(checked) => (formData.american_costs = checked ? 1 : 0)}
										/>
										<Label for="american_costs" class="text-xs">Costos Americanos</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="scaf_readonly"
											checked={formData.scaf_readonly === 1}
											onCheckedChange={(checked) => (formData.scaf_readonly = checked ? 1 : 0)}
										/>
										<Label for="scaf_readonly" class="text-xs">SCAF Solo Lectura</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="parts_replacement"
											checked={formData.parts_replacement === 1}
											onCheckedChange={(checked) => (formData.parts_replacement = checked ? 1 : 0)}
										/>
										<Label for="parts_replacement" class="text-xs">Reemplazo Partes</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="activate_facmexame"
											checked={formData.activate_facmexame === 1}
											onCheckedChange={(checked) => (formData.activate_facmexame = checked ? 1 : 0)}
										/>
										<Label for="activate_facmexame" class="text-xs">Activar FACMEXAME</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="part_reference"
											checked={formData.part_reference === 1}
											onCheckedChange={(checked) => (formData.part_reference = checked ? 1 : 0)}
										/>
										<Label for="part_reference" class="text-xs">Referencia Partes</Label>
									</div>
									<div class="flex items-center gap-3 rounded border p-3">
										<Switch
											id="international_firm"
											checked={formData.international_firm === 1}
											onCheckedChange={(checked) => (formData.international_firm = checked ? 1 : 0)}
										/>
										<Label for="international_firm" class="text-xs">Firma Internacional</Label>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Identificadores y Operación</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="man_id">Manufacturer ID (MID)</Label>
										<Input id="man_id" bind:value={formData.manufacturer_id} />
									</div>
									<div class="grid gap-2">
										<Label for="order_format">Formato Interfase Pedimento</Label>
										<select
											id="order_format"
											bind:value={formData.order_format_type}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value="">Seleccionar formato</option>
											<option value="INTERFASE_PEDIMENTO">Interfase Pedimento</option>
											<option value="ESTANDAR">Estandar</option>
										</select>
									</div>
									<div class="grid gap-2">
										<Label for="inter_db">Base de Datos Intermedia</Label>
										<Input id="inter_db" bind:value={formData.inter_db_name} />
									</div>
									<div class="grid gap-2">
										<Label for="prevalidator">Clave Prevalidador</Label>
										<Input id="prevalidator" bind:value={formData.prevalidator_key} />
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Configuraciones Avanzadas</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="ftp_key">Clave FTP</Label>
										<Input id="ftp_key" bind:value={formData.ftp_key} maxlength={10} />
									</div>
									<div class="grid gap-2">
										<Label for="sifra_path">Ruta SIFRA</Label>
										<Input id="sifra_path" bind:value={formData.sifra_path} maxlength={255} />
									</div>
									<div class="grid gap-2">
										<Label for="version_type">Tipo de Versión</Label>
										<Input id="version_type" bind:value={formData.version_type} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="sql_language">Lenguaje SQL</Label>
										<select
											id="sql_language"
											bind:value={formData.sql_language}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value="">Seleccionar lenguaje</option>
											<option value="SQLSERVER">SQL Server</option>
											<option value="POSTGRESQL">PostgreSQL</option>
											<option value="MYSQL">MySQL</option>
										</select>
									</div>
									<div class="grid gap-2">
										<Label for="balance_mode">Modo de Operación de Balance</Label>
										<select
											id="balance_mode"
											bind:value={formData.balance_operation_mode}
											class="flex h-9 w-full rounded-md border border-input bg-card px-3 py-1 text-sm shadow-sm ring-offset-background focus-visible:ring-2 focus-visible:ring-ring focus-visible:outline-none"
										>
											<option value="">Seleccionar modo</option>
											<option value="PEDIMENTO">Por Pedimento</option>
											<option value="FACTURA">Por Factura</option>
											<option value="PARTIDA">Por Partida</option>
										</select>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Prevalidador Aduanal</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="prev_customs">Aduana</Label>
										<Input id="prev_customs" bind:value={formData.prev_customs} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="prev_key">Clave</Label>
										<Input id="prev_key" bind:value={formData.prev_key} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="prev_patent">Patente</Label>
										<Input id="prev_patent" bind:value={formData.prev_patent} maxlength={4} />
									</div>
									<div class="grid gap-2">
										<Label for="prev_desc">Descripción</Label>
										<Input id="prev_desc" bind:value={formData.prev_description} maxlength={100} />
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Ventanilla Única</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="vu_user">Usuario Webservice</Label>
										<Input id="vu_user" bind:value={formData.vu_webservice_user} maxlength={100} />
									</div>
									<div class="grid gap-2">
										<Label for="vu_pass">Contraseña Webservice</Label>
										<Input
											id="vu_pass"
											type="password"
											bind:value={formData.vu_webservice_password}
											maxlength={100}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="vu_email">Email</Label>
										<Input
											id="vu_email"
											type="email"
											bind:value={formData.vu_email}
											maxlength={800}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="vu_figure">Tipo de Figura</Label>
										<Input id="vu_figure" bind:value={formData.vu_figure_type} maxlength={29} />
									</div>
									<div class="grid gap-2">
										<Label for="vu_central">Ruta Central</Label>
										<Input id="vu_central" bind:value={formData.vu_central_path} maxlength={1499} />
									</div>
									<div class="grid gap-2">
										<Label for="vu_xml">Ruta Archivos XML</Label>
										<Input id="vu_xml" bind:value={formData.vu_xml_files_path} maxlength={1499} />
									</div>
									<div class="grid gap-2">
										<Label for="vu_query_rfc">RFC Consulta</Label>
										<Input id="vu_query_rfc" bind:value={formData.vu_query_rfc} maxlength={30} />
									</div>
									<div class="grid gap-2">
										<Label for="vu_validation_rfc">RFC Validación</Label>
										<Input
											id="vu_validation_rfc"
											bind:value={formData.vu_validation_rfc}
											maxlength={30}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="vu_config_source">Fuente de Configuración</Label>
										<Input
											id="vu_config_source"
											bind:value={formData.vu_configuration_source}
											maxlength={30}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="vu_units">Unidades de Medida</Label>
										<Input id="vu_units" bind:value={formData.vu_measurement_units} maxlength={3} />
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">Agente Aduanal Electrónico</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="ea_input">Carpeta de Entrada</Label>
										<Input id="ea_input" bind:value={formData.ea_input_folder} maxlength={1000} />
									</div>
									<div class="grid gap-2">
										<Label for="ea_output">Carpeta de Salida</Label>
										<Input id="ea_output" bind:value={formData.ea_output_folder} maxlength={1000} />
									</div>
									<div class="grid gap-2">
										<Label for="ea_send_mask">Máscara de Envío</Label>
										<Input id="ea_send_mask" bind:value={formData.ea_send_mask} maxlength={20} />
									</div>
									<div class="grid gap-2">
										<Label for="ea_resp_mask">Máscara de Respuesta</Label>
										<Input
											id="ea_resp_mask"
											bind:value={formData.ea_response_mask}
											maxlength={20}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ea_resp_ext">Extensión de Respuesta</Label>
										<Input
											id="ea_resp_ext"
											bind:value={formData.ea_response_extension}
											maxlength={20}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ea_counter_start">Contador Inicio</Label>
										<Input
											id="ea_counter_start"
											type="number"
											bind:value={formData.ea_counter_start}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="ea_counter_end">Contador Fin</Label>
										<Input id="ea_counter_end" type="number" bind:value={formData.ea_counter_end} />
									</div>
									<div class="grid gap-2">
										<Label for="ea_counter_next">Contador Siguiente</Label>
										<Input
											id="ea_counter_next"
											type="number"
											bind:value={formData.ea_counter_next}
										/>
									</div>
								</div>
							</div>

							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<h3 class="font-semibold">CFDI - Facturación Electrónica</h3>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="cfdi_xml_path">Ruta de Guardado XML</Label>
										<Input
											id="cfdi_xml_path"
											bind:value={formData.cfdi_xml_save_path}
											maxlength={5000}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_app_path">Ruta Aplicación CFDI</Label>
										<Input
											id="cfdi_app_path"
											bind:value={formData.cfdi_app_path}
											maxlength={5000}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_pac_path">Ruta Aplicación PAC</Label>
										<Input
											id="cfdi_pac_path"
											bind:value={formData.cfdi_pac_app_path}
											maxlength={5000}
										/>
									</div>
								</div>
							</div>
						</Tabs.Content>

						<Tabs.Content value="certificados" class="space-y-4 pt-4">
							<!-- FIEL Section -->
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<div class="flex items-center gap-2">
									<ShieldCheck class="h-5 w-5 text-muted-foreground" />
									<h3 class="font-semibold">Firma Electrónica Avanzada (FIEL)</h3>
								</div>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="fiel_cer">Archivo .CER</Label>
										<FilePickerInput
											value={getFileDisplayName(formData.fiel_cer, 'CER', 'Seleccionar archivo .cer')}
											placeholder="Seleccionar archivo .cer"
											accept=".cer"
											disabled={loading}
											onchange={(file) => handleCertificateFile(file, 'fiel_cer')}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="fiel_key">Archivo .KEY</Label>
										<FilePickerInput
											value={getFileDisplayName(formData.fiel_key, 'KEY', 'Seleccionar archivo .key')}
											placeholder="Seleccionar archivo .key"
											accept=".key"
											disabled={loading}
											onchange={(file) => handleCertificateFile(file, 'fiel_key')}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="fiel_pass">Contraseña</Label>
										<Input id="fiel_pass" type="password" bind:value={formData.fiel_pass} />
									</div>
									<div class="grid gap-2">
										<Label for="fiel_access">Clave de Acceso</Label>
										<Input id="fiel_access" bind:value={formData.fiel_access} />
									</div>
									<div class="grid gap-2">
										<Label for="fiel_cer_exp">Vencimiento CER</Label>
										<Input id="fiel_cer_exp" type="number" bind:value={formData.fiel_cer_exp} />
									</div>
									<div class="grid gap-2">
										<Label for="fiel_key_exp">Vencimiento KEY</Label>
										<Input id="fiel_key_exp" type="number" bind:value={formData.fiel_key_exp} />
									</div>
								</div>
							</div>

							<!-- CSD Section -->
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<div class="flex items-center gap-2">
									<FileSignature class="h-5 w-5 text-muted-foreground" />
									<h3 class="font-semibold">Certificado de Sellos Digitales (CSD)</h3>
								</div>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="cfdi_cert_cer">Archivo .CER</Label>
										<FilePickerInput
											value={getFileDisplayName(formData.cfdi_cert_cer, 'CER', 'Seleccionar archivo .cer')}
											placeholder="Seleccionar archivo .cer"
											accept=".cer"
											disabled={loading}
											onchange={(file) => handleCertificateFile(file, 'cfdi_cert_cer')}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_cert_key">Archivo .KEY</Label>
										<FilePickerInput
											value={getFileDisplayName(formData.cfdi_cert_key, 'KEY', 'Seleccionar archivo .key')}
											placeholder="Seleccionar archivo .key"
											accept=".key"
											disabled={loading}
											onchange={(file) => handleCertificateFile(file, 'cfdi_cert_key')}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_cert_pass">Contraseña</Label>
										<Input
											id="cfdi_cert_pass"
											type="password"
											bind:value={formData.cfdi_cert_pass}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_cert_access">Clave de Acceso</Label>
										<Input id="cfdi_cert_access" bind:value={formData.cfdi_cert_access} />
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_cert_cer_exp">Vencimiento CER</Label>
										<Input
											id="cfdi_cert_cer_exp"
											type="number"
											bind:value={formData.cfdi_cert_cer_exp}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cfdi_cert_key_exp">Vencimiento KEY</Label>
										<Input
											id="cfdi_cert_key_exp"
											type="number"
											bind:value={formData.cfdi_cert_key_exp}
										/>
									</div>
								</div>
							</div>

							<!-- Cancelación Section -->
							<div class="grid gap-4 rounded-lg border bg-muted/30 p-4">
								<div class="flex items-center gap-2">
									<Ban class="h-5 w-5 text-muted-foreground" />
									<h3 class="font-semibold">Certificado de Cancelación (Opcional)</h3>
								</div>
								<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="cancel_cer">Archivo .CER</Label>
										<FilePickerInput
											value={getFileDisplayName(formData.cancel_cer, 'CER', 'Seleccionar archivo .cer')}
											placeholder="Seleccionar archivo .cer"
											accept=".cer"
											disabled={loading}
											onchange={(file) => handleCertificateFile(file, 'cancel_cer')}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cancel_key">Archivo .KEY</Label>
										<FilePickerInput
											value={getFileDisplayName(formData.cancel_key, 'KEY', 'Seleccionar archivo .key')}
											placeholder="Seleccionar archivo .key"
											accept=".key"
											disabled={loading}
											onchange={(file) => handleCertificateFile(file, 'cancel_key')}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="cancel_pass">Contraseña</Label>
										<Input id="cancel_pass" type="password" bind:value={formData.cancel_pass} />
									</div>
									<div class="grid gap-2">
										<Label for="cancel_access">Clave de Acceso</Label>
										<Input id="cancel_access" bind:value={formData.cancel_access} />
									</div>
								</div>
							</div>
						</Tabs.Content>
					</div>
				</Tabs.Root>
			</Card.Content>
		</Card.Root>
	</form>

	<div
		class="fixed right-0 bottom-0 left-0 z-50 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-6xl space-y-4 px-4 py-4">
			<Tabs.Root bind:value={activeTab} class="w-full">
				<div class="w-full overflow-x-auto pb-2">
					<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-7">
						<Tabs.Trigger value="general" class="whitespace-nowrap">
							<Building2 class="mr-2 h-4 w-4" />
							General
						</Tabs.Trigger>
						<Tabs.Trigger value="programa" class="whitespace-nowrap">
							<FileText class="mr-2 h-4 w-4" />
							Programa
						</Tabs.Trigger>
						<Tabs.Trigger value="responsable" class="whitespace-nowrap">
							<User class="mr-2 h-4 w-4" />
							Responsable
						</Tabs.Trigger>
						<Tabs.Trigger value="certificaciones" class="whitespace-nowrap">
							<FileText class="mr-2 h-4 w-4" />
							Certif.
						</Tabs.Trigger>
						<Tabs.Trigger value="direcciones" class="whitespace-nowrap">
							<MapPin class="mr-2 h-4 w-4" />
							Direcc.
						</Tabs.Trigger>
						<Tabs.Trigger value="config" class="whitespace-nowrap">
							<Settings class="mr-2 h-4 w-4" />
							Config
						</Tabs.Trigger>
						<Tabs.Trigger value="certificados" class="whitespace-nowrap">
							<Key class="mr-2 h-4 w-4" />
							Certif. Digitales
						</Tabs.Trigger>
					</Tabs.List>
				</div>
			</Tabs.Root>

			<div class="flex justify-end gap-3">
				<Button
					type="button"
					variant="outline"
					onclick={() => goto('/dashboard/general_catalogs/company_information')}
					disabled={loading}
				>
					Cancelar
				</Button>
				<Button type="submit" disabled={loading} onclick={handleSubmit}>
					{#if loading}
						<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
						{isEdit ? 'Actualizando...' : 'Guardando...'}
					{:else}
						<Save class="mr-2 h-4 w-4" />
						{isEdit ? 'Actualizar' : 'Guardar'}
					{/if}
				</Button>
			</div>
		</div>
	</div>
</div>

<CountrySelectorDialog bind:open={countryModalOpen} onSelect={handleCountrySelect} />
<StateSelectorDialog bind:open={stateModalOpen} onSelect={handleStateSelect} />
{/if}
