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

	// Componentes UI
	import { Button } from '$lib/components/ui/button';
	import { Input } from '$lib/components/ui/input';
	import { Label } from '$lib/components/ui/label';
	import * as Card from '$lib/components/ui/card';
	import * as Select from '$lib/components/ui/select';
	import * as Tabs from '$lib/components/ui/tabs';
	import { Switch } from '$lib/components/ui/switch';
	import { Badge } from '$lib/components/ui/badge';
	import { Separator } from '$lib/components/ui/separator';
	import {
		LoaderCircle,
		ArrowLeft,
		Save,
		Building2,
		MapPin,
		FileText,
		Settings,
		User,
		Trash2,
		Search,
		Globe,
		MapPin as MapPinIcon,
		Factory,
		Calendar,
		Hash,
		ShieldCheck,
		Award,
		Fingerprint,
		Briefcase
	} from 'lucide-svelte';
	import { toast } from 'svelte-sonner';

	// Componentes Compartidos (Modales)
	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 SectorSelectorDialog from '$lib/components/dashboard/shared/modals/sector-selector-dialog.svelte';

	import { type Country } from '$lib/api/dashboard/reference_data/countries';
	import { type State } from '$lib/api/dashboard/reference_data/states';
	import { type Sector } from '$lib/api/dashboard/reference_data/sectors';

	// API & Stores
	import { clientsProvidersApi } from '$lib/api/dashboard/a76/clients-providers';
	import { companyStore } from '$lib/stores/company.svelte';
	import { currentUser } from '$lib/auth';
	import {
		canCreateClientsAndProviders,
		canEditClientsAndProviders
	} from '$lib/permissions/clients-providers-permissions';
	import ErrorState from '$lib/components/dashboard/common/error-state.svelte';
	import { useShortcuts } from '$lib/hooks/use-shortcuts';
	import { obtenerAtajosEdicionSocio } from '$lib/config/shortcuts/dashboard/clients_and_providers/edit';

	// --- CONFIGURACIÓN ---
	let id = $derived($page.params.id);
	/** Alta: sin id o ruta legacy `/edit/new` (misma intención que el botón "Nuevo"). */
	let isEditing = $derived(!!id && id !== 'new');

	const canAccessPartnerEditor = $derived(
		isEditing ? canEditClientsAndProviders($currentUser) : canCreateClientsAndProviders($currentUser)
	);

	// State for Tabs
	let activeTab = $state('general');

	const typeLabels: Record<string, string> = {
		client: 'Cliente',
		provider: 'Proveedor',
		both: 'Ambos'
	};

	// --- ESTADO INICIAL (PLANO) ---
	const getEmptyForm = () => ({
		rfc: '',
		name: '',
		short_name: '',
		curp: '',
		client_or_provider: 'both',
		type_nat_foreign: 'N',
		responsible: '',
		position: '',
		is_active: true,

		streets: '',
		exterior_number: '',
		interior_number: '',
		neighborhood: '',
		municipality: '',
		city: '',
		state: '',
		country: '',
		postal_code: '',
		email: '',
		phone: '',
		contact: '',

		// Tabla Programas (Programs)
		program: '',
		program_number: '',
		authorization_date_str: '', // String para input date
		prosec: '',
		manufacturer_id: '',
		ctpat_svi: '',
		is_certified_company: false
	});

	let formData = $state(getEmptyForm());
	let loading = $state(false);
	let error = $state<string | null>(null);

	// --- ESTADO PARA MODALES ---
	let countryModalOpen = $state(false);
	let stateModalOpen = $state(false);
	let sectorModalOpen = $state(false);

	const scaiiPrograms = [
		{ value: 'IMMEX', label: 'IMMEX' },
		{ value: 'PROSEC', label: 'PROSEC' },
		{ value: 'ALTEX', label: 'ALTEX' },
		{ value: 'ECEX', label: 'ECEX' },
		{ value: 'DRAWBACK', label: 'DRAWBACK' }
	];

	// --- UTILIDADES ---
	const intDateToString = (d?: number | null) =>
		d
			? `${d.toString().substring(0, 4)}-${d.toString().substring(4, 6)}-${d.toString().substring(6, 8)}`
			: '';
	const stringDateToInt = (d?: string) => (d ? parseInt(d.replace(/-/g, '')) : null);
	const clean = (v: any) => (typeof v === 'string' && !v.trim() ? null : v);

	// --- CARGA DE DATOS ---
	$effect(() => {
		if (!canAccessPartnerEditor) return;
		if (id && id !== 'new' && companyStore.activeCompany?.id) loadData(Number(id));
		else if (!id || id === 'new') formData = getEmptyForm();
	});

	async function loadData(clientId: number) {
		if (!companyStore.activeCompany?.id) return;
		loading = true;
		try {
			const res = await clientsProvidersApi.get(clientId, companyStore.activeCompany.id);
			const item = (res as any).data || res;

			if (item) {
				const addr = item.address || {};
				const prog = item.programs || {};

				// Mapear respuesta anidada -> formulario plano
				formData = {
					rfc: item.rfc || '',
					name: item.name || '',
					short_name: item.short_name || '',
					curp: item.curp || '',
					client_or_provider: item.client_or_provider || 'client',
					type_nat_foreign: item.type_nat_foreign || 'N',
					responsible: item.responsible || '',
					position: item.position || '',
					is_active: !!item.is_active,

					streets: addr.streets || '',
					exterior_number: addr.exterior_number || '',
					interior_number: addr.interior_number || '',
					neighborhood: addr.neighborhood || '',
					municipality: addr.municipality || '',
					city: addr.city || '',
					state: addr.state || '',
					country: addr.country || '',
					postal_code: addr.postal_code || '',
					email: addr.email || '',
					phone: addr.phone || '',
					contact: addr.contact || '',

					program: prog.program || '',
					program_number: prog.program_number || '',
					authorization_date_str: intDateToString(prog.secon_auth_date),
					prosec: prog.prosec ? String(prog.prosec) : '',
					manufacturer_id: prog.manufacturer_id || '',
					ctpat_svi: prog.ctpat_svi || '',
					is_certified_company: prog.is_certified_company === '1'
				};
			}
		} catch (e: any) {
			error = 'Error al cargar: ' + e.message;
			toast.error(error);
		} finally {
			loading = false;
		}
	}

	// Validación de formato: RFC (Nacional) o TAX-ID (Extranjero)
	const RFC_REGEX = /^[A-Z&Ñ]{3,4}\d{6}[A-Z0-9]{3}$/i;
	// TAX-ID: 2 dígitos, guión, resto alfanumérico. Ej: 12-3456789. Máx 30 caracteres.
	const TAX_ID_REGEX = /^\d{2}-[A-Z0-9]{1,27}$/i;

	// --- ENVÍO DE DATOS ---
	async function handleSubmit() {
		if (!canAccessPartnerEditor) {
			toast.error('No tienes permiso para guardar este registro');
			return;
		}
		if (!companyStore.activeCompany) {
			error = 'Selecciona una compañía';
			toast.error(error);
			return;
		}
		if (!formData.rfc.trim() || !formData.name.trim()) {
			error = 'Identificador fiscal (RFC/TAX-ID) y Nombre son obligatorios';
			toast.error(error);
			return;
		}

		const rfcVal = formData.rfc.trim();
		const isForeign = (formData.type_nat_foreign || 'N').toUpperCase() === 'E';
		if (isForeign) {
			if (!TAX_ID_REGEX.test(rfcVal)) {
				error = 'El TAX-ID debe tener formato: 2 dígitos, guión y resto (ej. 12-3456789). Máx 30 caracteres.';
				toast.error(error);
				return;
			}
		} else {
			if (!RFC_REGEX.test(rfcVal)) {
				error = 'El RFC no tiene el formato correcto. Ejemplo: XAXX010101000.';
				toast.error(error);
				return;
			}
		}

		loading = true;
		error = null;

		try {
			// Reconstruir objeto anidado para el backend
			const payload = {
				rfc: clean(formData.rfc),
				name: clean(formData.name),
				short_name: clean(formData.short_name),
				curp: clean(formData.curp),
				client_or_provider: formData.client_or_provider,
				type_nat_foreign: clean(formData.type_nat_foreign),
				responsible: clean(formData.responsible),
				position: clean(formData.position),
				is_active: formData.is_active,

				address: {
					streets: clean(formData.streets),
					exterior_number: clean(formData.exterior_number),
					interior_number: clean(formData.interior_number),
					neighborhood: clean(formData.neighborhood),
					municipality: clean(formData.municipality),
					city: clean(formData.city),
					state: clean(formData.state),
					country: clean(formData.country),
					postal_code: clean(formData.postal_code),
					email: clean(formData.email),
					phone: clean(formData.phone),
					contact: clean(formData.contact)
				},

				programs: {
					program: clean(formData.program),
					program_number: clean(formData.program_number),
					secon_auth_date: stringDateToInt(formData.authorization_date_str),
					prosec: clean(formData.prosec),
					manufacturer_id: clean(formData.manufacturer_id),
					ctpat_svi: clean(formData.ctpat_svi),
					is_certified_company: formData.is_certified_company ? '1' : '0'
				}
			};

			const companyId = companyStore.activeCompany.id;
			const response = isEditing
				? await clientsProvidersApi.update(Number(id), companyId, payload as any)
				: await clientsProvidersApi.create(companyId, payload as any);

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

			toast.success(
				isEditing ? 'Registro actualizado correctamente' : 'Registro creado correctamente'
			);
			goto('/dashboard/clients_and_providers');
		} catch (e: any) {
			console.error(e);
			error = e.message || 'Error al guardar';
			toast.error(error || 'Error al guardar');
		} finally {
			loading = false;
		}
	}

	function handleCancel() {
		goto('/dashboard/clients_and_providers');
	}

	useShortcuts(
		'Edit Client Provider',
		obtenerAtajosEdicionSocio({
			irGeneral: () => (activeTab = 'general'),
			irDireccion: () => (activeTab = 'address'),
			irProgramas: () => (activeTab = 'programs'),
			irConfig: () => (activeTab = 'config'),
			guardar: handleSubmit,
			cancelar: handleCancel
		})
	);
</script>

{#if !canAccessPartnerEditor}
	<div
		class="flex h-[calc(100svh-4rem)] flex-col p-6 group-has-data-[collapsible=icon]/sidebar-wrapper:h-[calc(100svh-3rem)]"
	>
		<ErrorState status={403} />
	</div>
{:else}
<div class="space-y-3">
	<!-- Header -->
	<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={handleCancel}>
					<ArrowLeft size={20} />
				</Button>
				<h1 class="text-3xl font-bold tracking-tight">
					{isEditing ? `Socio Comercial #${id}` : 'Nuevo Socio Comercial'}
				</h1>
				{#if isEditing}
					<Badge variant={formData.is_active ? 'default' : 'secondary'}>
						{formData.is_active ? 'Activo' : 'Inactivo'}
					</Badge>
				{:else}
					<Badge variant="default">Nuevo</Badge>
				{/if}
			</div>
			<p class="ml-12 text-muted-foreground">
				{isEditing
					? 'Edita la información del cliente o proveedor'
					: 'Registra un nuevo cliente o proveedor en el sistema'}
			</p>
		</div>
	</div>

	<Separator />

	<!-- Main Content with Tabs -->
	<div class="pb-48">
		<!-- Padding bottom for sticky footer -->
		<form
			onsubmit={(e) => {
				e.preventDefault();
				handleSubmit();
			}}
		>
			<Tabs.Root bind:value={activeTab}>
				<!-- Tab Panel: General -->
				<Tabs.Content value="general">
					<Card.Root>
						<Card.Header>
							<Card.Title>Información General</Card.Title>
							<Card.Description
								>Datos principales de identificación y clasificación.</Card.Description
							>
						</Card.Header>
						<Card.Content class="space-y-4">
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="rfc">{formData.type_nat_foreign?.toUpperCase() === 'E' ? 'TAX-ID' : 'RFC'} <span class="text-destructive">*</span></Label>
									<Input
										id="rfc"
										bind:value={formData.rfc}
										placeholder={formData.type_nat_foreign?.toUpperCase() === 'E' ? 'Ej: 12-3456789 (según país)' : 'XAXX010101000'}
										maxlength={30}
										disabled={loading}
									/>
								</div>
								<div class="grid gap-2">
									<Label for="type">Tipo de Relación <span class="text-destructive">*</span></Label>
									<Select.Root
										type="single"
										value={formData.client_or_provider}
										onValueChange={(v) => (formData.client_or_provider = v)}
									>
										<Select.Trigger id="type">
											{typeLabels[formData.client_or_provider] || 'Selecciona un tipo'}
										</Select.Trigger>
										<Select.Content>
											<Select.Item value="client" label="Cliente">Cliente</Select.Item>
											<Select.Item value="provider" label="Proveedor">Proveedor</Select.Item>
											<Select.Item value="both" label="Ambos">Ambos</Select.Item>
										</Select.Content>
									</Select.Root>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-4 md:grid-cols-4">
								<div class="grid gap-2 md:col-span-3">
									<Label for="name">Razón Social <span class="text-destructive">*</span></Label>
									<Input
										id="name"
										bind:value={formData.name}
										placeholder="Nombre completo"
										maxlength={256}
										disabled={loading}
									/>
								</div>
								<div class="grid gap-2">
									<Label for="short_name">Nombre Corto</Label>
									<Input
										id="short_name"
										bind:value={formData.short_name}
										placeholder="Alias"
										maxlength={10}
										disabled={loading}
									/>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="curp">CURP (Opcional)</Label>
									<Input id="curp" bind:value={formData.curp} maxlength={18} disabled={loading} />
								</div>
								<div class="grid gap-2">
									<Label for="type_nat">Tipo Origen</Label>
									<Select.Root
										type="single"
										value={formData.type_nat_foreign}
										onValueChange={(v) => (formData.type_nat_foreign = v)}
									>
										<Select.Trigger id="type_nat">
											{formData.type_nat_foreign === 'N'
												? 'Nacional'
												: formData.type_nat_foreign === 'E'
													? 'Extranjero'
													: 'Seleccione'}
										</Select.Trigger>
										<Select.Content>
											<Select.Item value="N" label="Nacional">Nacional</Select.Item>
											<Select.Item value="E" label="Extranjero">Extranjero</Select.Item>
										</Select.Content>
									</Select.Root>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="responsible">Responsable</Label>
									<Input id="responsible" bind:value={formData.responsible} disabled={loading} />
								</div>
								<div class="grid gap-2">
									<Label for="position">Puesto</Label>
									<Input id="position" bind:value={formData.position} disabled={loading} />
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>

				<!-- Tab Panel: Address -->
				<Tabs.Content value="address">
					<Card.Root>
						<Card.Header>
							<Card.Title>Dirección y Contacto</Card.Title>
							<Card.Description>Ubicación fiscal y datos de contacto.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-4">
							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="street">Calle</Label>
									<Input
										id="street"
										bind:value={formData.streets}
										maxlength={100}
										disabled={loading}
									/>
								</div>
								<div class="grid grid-cols-2 gap-4">
									<div class="grid gap-2">
										<Label for="ext">No. Exterior</Label>
										<Input
											id="ext"
											bind:value={formData.exterior_number}
											maxlength={20}
											disabled={loading}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="int">No. Interior</Label>
										<Input
											id="int"
											bind:value={formData.interior_number}
											maxlength={20}
											disabled={loading}
										/>
									</div>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
								<div class="grid gap-2">
									<Label for="col">Colonia</Label>
									<Input
										id="col"
										bind:value={formData.neighborhood}
										maxlength={40}
										disabled={loading}
									/>
								</div>
								<div class="grid gap-2">
									<Label for="cp">C.P.</Label>
									<Input
										id="cp"
										bind:value={formData.postal_code}
										maxlength={15}
										disabled={loading}
									/>
								</div>
								<div class="grid gap-2">
									<Label for="mun">Municipio</Label>
									<Input
										id="mun"
										bind:value={formData.municipality}
										maxlength={150}
										disabled={loading}
									/>
								</div>
							</div>

							<div class="grid grid-cols-1 gap-4 md:grid-cols-3">
								<div class="grid gap-2">
									<Label for="city">Ciudad</Label>
									<Input id="city" bind:value={formData.city} maxlength={30} disabled={loading} />
								</div>
								<div class="grid gap-2">
									<Label for="state">Estado</Label>
									<div class="flex gap-2">
										<Input
											id="state"
											bind:value={formData.state}
											maxlength={30}
											disabled={loading}
										/>
										<Button
											variant="outline"
											size="icon"
											onclick={() => (stateModalOpen = true)}
											disabled={loading}
											title="Buscar Estado"
										>
											<Search size={16} />
										</Button>
									</div>
								</div>
								<div class="grid gap-2">
									<Label for="country">País (ISO)</Label>
									<div class="flex gap-2">
										<Input
											id="country"
											bind:value={formData.country}
											placeholder="MEX"
											maxlength={3}
											disabled={loading}
										/>
										<Button
											variant="outline"
											size="icon"
											onclick={() => (countryModalOpen = true)}
											disabled={loading}
											title="Buscar País"
										>
											<Globe size={16} />
										</Button>
									</div>
								</div>
							</div>

							<Separator class="my-4" />

							<div class="grid grid-cols-1 gap-4 md:grid-cols-2">
								<div class="grid gap-2">
									<Label for="email">Email de Contacto</Label>
									<Input id="email" type="email" bind:value={formData.email} disabled={loading} />
								</div>
								<div class="grid gap-2">
									<Label for="phone">Teléfono</Label>
									<Input id="phone" bind:value={formData.phone} disabled={loading} />
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>

				<!-- Tab Panel: Programs -->
				<Tabs.Content value="programs">
					<Card.Root>
						<Card.Header>
							<Card.Title>Programas y Certificaciones</Card.Title>
							<Card.Description
								>Información sobre IMMEX, PROSEC y otras certificaciones.</Card.Description
							>
						</Card.Header>
						<Card.Content class="space-y-8">
							<!-- Section: Promotion Programs -->
							<div class="space-y-4">
								<div class="flex items-center gap-2 text-sm font-semibold text-white">
									<Briefcase size={18} />
									<span>Programas de Fomento</span>
								</div>
								<Separator />
								<div class="grid grid-cols-1 gap-6 md:grid-cols-2 lg:grid-cols-4">
									<div class="grid gap-2 lg:col-span-1">
										<Label for="program" class="flex items-center gap-2">
											<Building2 size={14} class="text-muted-foreground" />
											Programa
										</Label>
										<Select.Root
											type="single"
											value={formData.program}
											onValueChange={(v) => (formData.program = v)}
											disabled={loading}
										>
											<Select.Trigger id="program" class="w-full">
												{formData.program || 'Selecciona un programa'}
											</Select.Trigger>
											<Select.Content>
												{#each scaiiPrograms as prog}
													<Select.Item value={prog.value} label={prog.label}>
														{prog.label}
													</Select.Item>
												{/each}
											</Select.Content>
										</Select.Root>
									</div>
									<div class="grid gap-2">
										<Label for="program_num" class="flex items-center gap-2">
											<Hash size={14} class="text-muted-foreground" />
											Número de Programa
										</Label>
										<Input
											id="program_num"
											bind:value={formData.program_number}
											maxlength={40}
											disabled={loading}
											placeholder="P. ej. 1234-2024"
										/>
									</div>
									<div class="grid gap-2">
										<Label for="auth_date" class="flex items-center gap-2">
											<Calendar size={14} class="text-muted-foreground" />
											Fecha Autorización
										</Label>
										<Input
											id="auth_date"
											type="date"
											bind:value={formData.authorization_date_str}
											disabled={loading}
										/>
									</div>
									<div class="grid gap-2">
										<Label for="prosec" class="flex items-center gap-2">
											<Factory size={14} class="text-muted-foreground" />
											PROSEC (Sector)
										</Label>
										<div class="flex gap-2">
											<Input
												id="prosec"
												bind:value={formData.prosec}
												disabled={loading}
												placeholder="Ej: XII, IV"
											/>
											<Button
												variant="outline"
												size="icon"
												onclick={() => (sectorModalOpen = true)}
												disabled={loading}
												title="Buscar Sector"
											>
												<Search size={16} />
											</Button>
										</div>
									</div>
								</div>
							</div>

							<!-- Section: Industrial Identification -->
							<div class="space-y-4 pt-4">
								<div class="flex items-center gap-2 text-sm font-semibold text-white">
									<Fingerprint size={18} />
									<span>Identificación Industrial</span>
								</div>
								<Separator />
								<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="man_id" class="flex items-center gap-2">
											<FileText size={14} class="text-muted-foreground" />
											Manufacturer ID (MID)
										</Label>
										<Input
											id="man_id"
											bind:value={formData.manufacturer_id}
											maxlength={25}
											disabled={loading}
											placeholder="P. ej. MXABCD12345"
										/>
									</div>
								</div>
							</div>

							<!-- Section: Certifications & Security -->
							<div class="space-y-4 pt-4">
								<div class="flex items-center gap-2 text-sm font-semibold text-white">
									<ShieldCheck size={18} />
									<span>Certificaciones y Seguridad</span>
								</div>
								<Separator />
								<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
									<div class="grid gap-2">
										<Label for="ctpat" class="flex items-center gap-2">
											<Award size={14} class="text-muted-foreground" />
											C-TPAT / SVI
										</Label>
										<Input
											id="ctpat"
											bind:value={formData.ctpat_svi}
											maxlength={100}
											disabled={loading}
											placeholder="P. ej. SVI-12345"
										/>
									</div>
									<div class="flex items-center gap-3 rounded-lg border bg-card/50 p-4">
										<Switch
											id="is_certified"
											bind:checked={formData.is_certified_company}
											disabled={loading}
										/>
										<div class="grid gap-0.5">
											<Label for="is_certified">Empresa Certificada</Label>
											<p class="text-xs text-muted-foreground">
												Indica si cuenta con certificación de empresa
											</p>
										</div>
									</div>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>

				<!-- Tab Panel: Settings -->
				<Tabs.Content value="config">
					<Card.Root>
						<Card.Header>
							<Card.Title>Configuración</Card.Title>
							<Card.Description>Ajustes de estado y atributos especiales.</Card.Description>
						</Card.Header>
						<Card.Content class="space-y-4">
							<div class="grid grid-cols-1 gap-6 md:grid-cols-2">
								<div class="flex items-center gap-3 rounded-lg border bg-card p-4">
									<Switch id="is_active" bind:checked={formData.is_active} disabled={loading} />
									<div class="grid gap-0.5">
										<Label for="is_active">Registro Activo</Label>
										<p class="text-xs text-muted-foreground">
											Habilitar o deshabilitar este socio comercial
										</p>
									</div>
								</div>
							</div>
						</Card.Content>
					</Card.Root>
				</Tabs.Content>
			</Tabs.Root>
		</form>
	</div>
</div>

<!-- Sticky Footer -->
<div
	class="fixed right-0 bottom-0 left-0 z-[5] ml-[calc(var(--sidebar-width))] border-t bg-background/95 shadow-lg backdrop-blur group-has-data-[state=collapsed]/sidebar-wrapper:ml-[calc(var(--sidebar-width-icon))] supports-[backdrop-filter]:bg-background/80"
>
	<div class="mx-auto max-w-[1400px] space-y-4 px-4 py-4">
		<!-- Tabs Navigation in Footer -->
		<Tabs.Root bind:value={activeTab}>
			<div class="w-full overflow-x-auto pb-2">
				<Tabs.List class="inline-flex md:grid md:w-full md:grid-cols-4">
					<Tabs.Trigger value="general" class="whitespace-nowrap">
						<Building2 size={16} class="mr-2" /> General
					</Tabs.Trigger>
					<Tabs.Trigger value="address" class="whitespace-nowrap">
						<MapPin size={16} class="mr-2" /> Dirección
					</Tabs.Trigger>
					<Tabs.Trigger value="programs" class="whitespace-nowrap">
						<FileText size={16} class="mr-2" /> Programas
					</Tabs.Trigger>
					<Tabs.Trigger value="config" class="whitespace-nowrap">
						<Settings size={16} class="mr-2" /> Config
					</Tabs.Trigger>
				</Tabs.List>
			</div>
		</Tabs.Root>

		<!-- Actions -->
		<div class="flex justify-end gap-3">
			<Button variant="outline" onclick={handleCancel} disabled={loading}>Cancelar</Button>
			{#if !isEditing}
				<Button variant="outline" onclick={() => (formData = getEmptyForm())} disabled={loading}>
					<!-- <Trash2 size={16} class="mr-2" /> -->
					Limpiar
				</Button>
			{/if}
			<Button onclick={handleSubmit} disabled={loading}>
				{#if loading}
					<LoaderCircle class="mr-2 h-4 w-4 animate-spin" />
					Guardando...
				{:else}
					<Save size={16} class="mr-2" />
					{isEditing ? 'Actualizar Socio' : 'Guardar Socio'}
				{/if}
			</Button>
		</div>
	</div>
</div>

<!-- MODALES DE SELECCIÓN -->
<CountrySelectorDialog
	bind:open={countryModalOpen}
	onSelect={(country) => (formData.country = country.m3_key)}
/>

<StateSelectorDialog
	bind:open={stateModalOpen}
	onSelect={(state) => {
		formData.state = state.description;
		if (state.m3_key && !formData.country) {
			formData.country = state.m3_key;
		}
	}}
/>

<SectorSelectorDialog
	bind:open={sectorModalOpen}
	onSelect={(sector) => (formData.prosec = sector.key)}
/>
{/if}
