<script lang="ts">
	import { ArrowLeft, Ship, Plus, Trash2, Check, X, Receipt, ListChecks, Upload, Lock, CalendarClock, GitBranch } from '@lucide/svelte';
	import { page } from '$app/state';
	import { goto } from '$app/navigation';
	import * as Card from '$lib/components/ui/card';
	import * as Table from '$lib/components/ui/table';
	import { Button } from '$lib/components/ui/button';
	import { companyStore } from '$lib/stores/company.svelte';
	import { accountsAPI, suppliersAPI, type Account, type Supplier } from '$lib/api/crm';
	import {
		shipmentsAPI, shipmentDocumentsAPI, shipmentEventsAPI,
		type Shipment, type ShipmentInput, type ShipmentDocument, type ShipmentDocumentInput, type ShipmentEvent
	} from '$lib/api/ops';
	import { invoicesAPI } from '$lib/api/fin';
	import { uploadFile, uploadUrl } from '$lib/api/uploads';
	import {
		OPERATION_TYPES, TRANSPORT_MODES, SERVICE_TYPES, SHIPMENT_STATUS,
		DOC_KINDS, SHIPMENT_DOC_TYPES, EVENT_STATUS, labelOf, formatDate
	} from '$lib/components/crm/format';
	import { toast } from 'svelte-sonner';

	const shipmentId = $derived(Number(page.params.id));
	const companyId = $derived(companyStore.activeCompany?.id ?? null);

	let shipment = $state<Shipment | null>(null);
	let form = $state<ShipmentInput>({});
	let accounts = $state<Account[]>([]);
	let suppliers = $state<Supplier[]>([]);
	let docs = $state<ShipmentDocument[]>([]);
	let events = $state<ShipmentEvent[]>([]);
	let tab = $state('datos');
	let loading = $state(false);
	let saving = $state(false);
	let busy = $state(false);
	let addingDoc = $state(false);
	let uploading = $state(false);
	let newDoc = $state<ShipmentDocumentInput>({ shipment_id: 0, doc_kind: 'master', doc_type: 'MBL' });
	let addingEvent = $state(false);
	let newEvent = $state<{ title: string; notes?: string }>({ title: '' });
	let showClose = $state(false);
	let closeForm = $state<{ actual_cost_total: number | null; cost_currency: string; notes: string }>({ actual_cost_total: null, cost_currency: 'MXN', notes: '' });
	let showReschedule = $state(false);
	let rescheduleForm = $state<{ etd: string; cutoff_date: string; reason: string }>({ etd: '', cutoff_date: '', reason: '' });

	const canInvoice = $derived(shipment?.status === 'cerrada');
	const canClose = $derived(!!shipment && shipment.status !== 'cerrada' && shipment.status !== 'cancelada');

	$effect(() => {
		const cid = companyId;
		const id = shipmentId;
		if (!cid || !id) return;
		void load(cid, id);
	});

	async function load(cid: number, id: number) {
		loading = true;
		try {
			[shipment, accounts, suppliers, docs, events] = await Promise.all([
				shipmentsAPI.get(id, cid), accountsAPI.list(cid), suppliersAPI.list(cid),
				shipmentsAPI.documents(id, cid), shipmentsAPI.events(id, cid)
			]);
			form = { ...shipment };
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo cargar el embarque');
		} finally {
			loading = false;
		}
	}

	async function save() {
		if (!companyId || !shipment) return;
		saving = true;
		try {
			shipment = await shipmentsAPI.update(shipment.id, form, companyId);
			form = { ...shipment };
			toast.success('Cambios guardados');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo guardar');
		} finally {
			saving = false;
		}
	}

	async function generateInvoice() {
		if (!companyId || !shipment) return;
		if (!confirm('¿Generar la factura de este embarque?')) return;
		busy = true;
		try {
			const inv = await invoicesAPI.fromShipment(shipment.id, companyId);
			toast.success('Factura generada');
			await goto(`/dashboard/fin/facturas/${inv.id}`);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo generar la factura');
		} finally {
			busy = false;
		}
	}

	async function closeOperation() {
		if (!companyId || !shipment) return;
		if (closeForm.actual_cost_total == null || Number.isNaN(Number(closeForm.actual_cost_total))) {
			toast.error('Captura el costo final de la operación');
			return;
		}
		busy = true;
		try {
			shipment = await shipmentsAPI.close(
				shipment.id,
				{ actual_cost_total: Number(closeForm.actual_cost_total), cost_currency: closeForm.cost_currency, notes: closeForm.notes || null },
				companyId
			);
			form = { ...shipment };
			showClose = false;
			toast.success('Cierre operativo registrado; el embarque ya puede facturarse');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo cerrar la operación');
		} finally {
			busy = false;
		}
	}

	async function doReschedule() {
		if (!companyId || !shipment) return;
		busy = true;
		try {
			shipment = await shipmentsAPI.reschedule(
				shipment.id,
				{ etd: rescheduleForm.etd || null, cutoff_date: rescheduleForm.cutoff_date || null, reason: rescheduleForm.reason || null },
				companyId
			);
			form = { ...shipment };
			events = await shipmentsAPI.events(shipmentId, companyId);
			showReschedule = false;
			rescheduleForm = { etd: '', cutoff_date: '', reason: '' };
			toast.success('Salida reprogramada');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo reprogramar');
		} finally {
			busy = false;
		}
	}

	// ----- Documentos -----
	function startDoc() { newDoc = { shipment_id: shipmentId, doc_kind: 'master', doc_type: 'MBL' }; addingDoc = true; }

	async function onFilePicked(e: Event) {
		const input = e.target as HTMLInputElement;
		const file = input.files?.[0];
		if (!file || !companyId) return;
		uploading = true;
		try {
			const up = await uploadFile(file, companyId);
			newDoc = { ...newDoc, file_key: up.file_key, file_url: up.file_url, number: newDoc.number };
			if (!newDoc.number) newDoc.number = up.name;
			toast.success('Archivo subido');
		} catch (err) {
			toast.error(err instanceof Error ? err.message : 'No se pudo subir el archivo');
		} finally {
			uploading = false;
		}
	}

	async function saveDoc() {
		if (!companyId) return;
		try {
			await shipmentDocumentsAPI.create({ ...newDoc, shipment_id: shipmentId }, companyId);
			addingDoc = false;
			docs = await shipmentsAPI.documents(shipmentId, companyId);
			toast.success('Documento agregado');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo agregar');
		}
	}

	async function openDoc(d: ShipmentDocument) {
		if (!companyId) return;
		try {
			const url = d.file_key ? await uploadUrl(d.file_key, companyId) : d.file_url;
			if (url) window.open(url, '_blank', 'noopener');
			else toast.error('El documento no tiene archivo');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo abrir el archivo');
		}
	}

	async function removeDoc(d: ShipmentDocument) {
		if (!companyId || !confirm('¿Eliminar documento?')) return;
		await shipmentDocumentsAPI.remove(d.id, companyId);
		docs = await shipmentsAPI.documents(shipmentId, companyId);
	}

	// ----- Bitácora -----
	async function seedEvents() {
		if (!companyId) return;
		busy = true;
		try {
			events = await shipmentsAPI.seedEvents(shipmentId, companyId);
			toast.success('Hitos generados');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudieron generar los hitos');
		} finally {
			busy = false;
		}
	}
	async function completeEvent(ev: ShipmentEvent) {
		if (!companyId) return;
		try {
			await shipmentEventsAPI.complete(ev.id, companyId);
			events = await shipmentsAPI.events(shipmentId, companyId);
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo completar el hito');
		}
	}
	async function decideEvent(ev: ShipmentEvent, outcome: 'autorizado' | 'rechazado') {
		if (!companyId) return;
		let notes: string | null = null;
		if (outcome === 'rechazado') notes = window.prompt('Motivo del rechazo (se abrirá un hito de corrección):') ?? null;
		try {
			await shipmentEventsAPI.decide(ev.id, outcome, companyId, notes);
			events = await shipmentsAPI.events(shipmentId, companyId);
			toast.success(outcome === 'autorizado' ? 'Decisión autorizada' : 'Rechazado; se generó el hito de corrección');
		} catch (e) {
			toast.error(e instanceof Error ? e.message : 'No se pudo registrar la decisión');
		}
	}
	async function saveEvent() {
		if (!companyId || !newEvent.title.trim()) { toast.error('El título es obligatorio'); return; }
		await shipmentEventsAPI.create({ shipment_id: shipmentId, title: newEvent.title, notes: newEvent.notes, position: events.length }, companyId);
		newEvent = { title: '' };
		addingEvent = false;
		events = await shipmentsAPI.events(shipmentId, companyId);
	}
	async function removeEvent(ev: ShipmentEvent) {
		if (!companyId || !confirm('¿Eliminar hito?')) return;
		await shipmentEventsAPI.remove(ev.id, companyId);
		events = await shipmentsAPI.events(shipmentId, companyId);
	}

	const inputCls = 'rounded-md border bg-transparent px-3 py-2 text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring';
</script>

<div class="space-y-6">
	<Button variant="ghost" size="sm" href="/dashboard/ops/embarques"><ArrowLeft class="mr-1 h-4 w-4" /> Embarques</Button>

	{#if loading && !shipment}
		<p class="text-sm text-muted-foreground">Cargando…</p>
	{:else if shipment}
		<div class="flex flex-wrap items-start justify-between gap-3">
			<div>
				<h1 class="flex items-center gap-2 text-2xl font-bold tracking-tight"><Ship class="h-6 w-6" /> {shipment.reference ?? `Embarque #${shipment.id}`}</h1>
				<p class="mt-1 text-sm text-muted-foreground">{labelOf(SHIPMENT_STATUS, shipment.status)}{#if shipment.booking_number} · Booking {shipment.booking_number}{/if}</p>
			</div>
			<div class="flex flex-wrap gap-2">
					{#if canClose}
						<Button size="sm" variant="outline" onclick={() => (showReschedule = !showReschedule)} disabled={busy}><CalendarClock class="mr-1 h-4 w-4" /> Reprogramar salida</Button>
						<Button size="sm" onclick={() => (showClose = !showClose)} disabled={busy}><Lock class="mr-1 h-4 w-4" /> Cerrar operación</Button>
					{/if}
					{#if canInvoice}
						<Button size="sm" variant="outline" onclick={generateInvoice} disabled={busy}><Receipt class="mr-1 h-4 w-4" /> Generar factura</Button>
					{/if}
				</div>
		</div>

		{#if showReschedule}
			<Card.Root><Card.Content class="grid gap-3 pt-6 sm:grid-cols-3">
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Nueva ETD</span><input type="date" class={inputCls} bind:value={rescheduleForm.etd} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Nuevo Cut Off</span><input type="datetime-local" class={inputCls} bind:value={rescheduleForm.cutoff_date} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Motivo</span><input class={inputCls} bind:value={rescheduleForm.reason} placeholder="Cut Off no alcanzado" /></label>
				<div class="flex justify-end gap-2 sm:col-span-3"><Button variant="outline" size="sm" onclick={() => (showReschedule = false)}>Cancelar</Button><Button size="sm" onclick={doReschedule} disabled={busy}>Reprogramar</Button></div>
			</Card.Content></Card.Root>
		{/if}
		{#if showClose}
			<Card.Root><Card.Content class="grid gap-3 pt-6 sm:grid-cols-3">
				<p class="text-sm text-muted-foreground sm:col-span-3">El cierre operativo registra los costos finales y habilita la facturación. Requiere resolver todos los puntos de decisión de la bitácora.</p>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Costo final total</span><input type="number" step="0.01" min="0" class={inputCls} bind:value={closeForm.actual_cost_total} /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Moneda</span><input class={inputCls} bind:value={closeForm.cost_currency} maxlength="3" /></label>
				<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Notas</span><input class={inputCls} bind:value={closeForm.notes} /></label>
				<div class="flex justify-end gap-2 sm:col-span-3"><Button variant="outline" size="sm" onclick={() => (showClose = false)}>Cancelar</Button><Button size="sm" onclick={closeOperation} disabled={busy}><Lock class="mr-1 h-4 w-4" /> Confirmar cierre</Button></div>
			</Card.Content></Card.Root>
		{/if}

		<Card.Root>
			<Card.Content class="pt-6">
				<div class="mb-5 flex flex-wrap gap-1 border-b">
					{#each [{ id: 'datos', label: 'Datos del embarque' }, { id: 'documentos', label: 'Documentos' }, { id: 'bitacora', label: 'Bitácora' }] as t (t.id)}
						<button type="button" class="border-b-2 px-3 py-2 text-sm font-medium transition-colors {tab === t.id ? 'border-primary text-foreground' : 'border-transparent text-muted-foreground hover:text-foreground'}" onclick={() => (tab = t.id)}>{t.label}</button>
					{/each}
				</div>

				{#if tab === 'datos'}
					<div class="grid gap-4 sm:grid-cols-2">
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Folio</span><input class={inputCls} bind:value={form.reference} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cliente</span><select class={inputCls} bind:value={form.account_id}><option value={undefined}>—</option>{#each accounts as a (a.id)}<option value={a.id}>{a.name}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Operación</span><select class={inputCls} bind:value={form.operation_type}><option value={undefined}>—</option>{#each OPERATION_TYPES as o (o.value)}<option value={o.value}>{o.label}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Medio</span><select class={inputCls} bind:value={form.transport_mode}><option value={undefined}>—</option>{#each TRANSPORT_MODES as m (m.value)}<option value={m.value}>{m.label}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Tipo de servicio</span><select class={inputCls} bind:value={form.service_type}><option value={undefined}>—</option>{#each SERVICE_TYPES as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Estatus</span><select class={inputCls} bind:value={form.status}>{#each SHIPMENT_STATUS as s (s.value)}<option value={s.value}>{s.label}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Origen</span><input class={inputCls} bind:value={form.origin} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Destino</span><input class={inputCls} bind:value={form.destination} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">No. de Booking</span><input class={inputCls} bind:value={form.booking_number} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cut Off</span><input type="datetime-local" class={inputCls} bind:value={form.cutoff_date} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Cita / ventana de recolección</span><input type="datetime-local" class={inputCls} bind:value={form.pickup_at} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">ETD (salida)</span><input type="date" class={inputCls} bind:value={form.etd} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">ETA (llegada)</span><input type="date" class={inputCls} bind:value={form.eta} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Buque / Vuelo</span><input class={inputCls} bind:value={form.vessel_flight} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Contenedor</span><input class={inputCls} bind:value={form.container_number} /></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Naviera / Aerolínea / Transportista</span><select class={inputCls} bind:value={form.carrier_supplier_id}><option value={undefined}>—</option>{#each suppliers as s (s.id)}<option value={s.id}>{s.name}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Transportista terrestre</span><select class={inputCls} bind:value={form.ground_carrier_supplier_id}><option value={undefined}>—</option>{#each suppliers as s (s.id)}<option value={s.id}>{s.name}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Agente aduanal</span><select class={inputCls} bind:value={form.customs_agent_id}><option value={undefined}>—</option>{#each suppliers as s (s.id)}<option value={s.id}>{s.name}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Agente en destino</span><select class={inputCls} bind:value={form.destination_agent_id}><option value={undefined}>—</option>{#each suppliers as s (s.id)}<option value={s.id}>{s.name}</option>{/each}</select></label>
						<label class="flex flex-col gap-1 text-sm sm:col-span-2"><span class="font-medium">Notas</span><textarea rows="2" class={inputCls} bind:value={form.notes}></textarea></label>
					</div>
					<div class="mt-6 flex justify-end border-t pt-4"><Button onclick={save} disabled={saving}>{saving ? 'Guardando…' : 'Guardar cambios'}</Button></div>
				{:else if tab === 'documentos'}
					<div class="mb-3 flex justify-end"><Button size="sm" variant="outline" onclick={startDoc}><Plus class="mr-1 h-4 w-4" /> Agregar documento</Button></div>
					{#if addingDoc}
						<div class="mb-4 grid gap-3 rounded-md border p-3 sm:grid-cols-2">
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Clase</span><select class={inputCls} bind:value={newDoc.doc_kind}>{#each DOC_KINDS as k (k.value)}<option value={k.value}>{k.label}</option>{/each}</select></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Documento</span><select class={inputCls} bind:value={newDoc.doc_type}>{#each SHIPMENT_DOC_TYPES as t (t.value)}<option value={t.value}>{t.label}</option>{/each}</select></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Número</span><input class={inputCls} bind:value={newDoc.number} /></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Fecha emisión</span><input type="date" class={inputCls} bind:value={newDoc.issue_date} /></label>
							<label class="flex flex-col gap-1 text-sm sm:col-span-2">
								<span class="font-medium flex items-center gap-1"><Upload class="h-3.5 w-3.5" /> Archivo {#if uploading}<span class="text-xs text-muted-foreground">(subiendo…)</span>{:else if newDoc.file_key}<span class="text-xs text-emerald-600">(cargado)</span>{/if}</span>
								<input type="file" class={inputCls} onchange={onFilePicked} />
							</label>
							<div class="flex justify-end gap-2 sm:col-span-2"><Button variant="outline" size="sm" onclick={() => (addingDoc = false)}>Cancelar</Button><Button size="sm" onclick={saveDoc} disabled={uploading}>Guardar</Button></div>
						</div>
					{/if}
					{#if docs.length === 0}
						<p class="text-sm text-muted-foreground">Sin documentos.</p>
					{:else}
						<Table.Root>
							<Table.Header><Table.Row><Table.Head>Clase</Table.Head><Table.Head>Documento</Table.Head><Table.Head>Número</Table.Head><Table.Head>Emisión</Table.Head><Table.Head>Archivo</Table.Head><Table.Head></Table.Head></Table.Row></Table.Header>
							<Table.Body>
								{#each docs as d (d.id)}
									<Table.Row>
										<Table.Cell>{labelOf(DOC_KINDS, d.doc_kind)}</Table.Cell>
										<Table.Cell class="font-medium">{labelOf(SHIPMENT_DOC_TYPES, d.doc_type)}</Table.Cell>
										<Table.Cell class="font-mono text-xs">{d.number ?? '—'}</Table.Cell>
										<Table.Cell>{formatDate(d.issue_date)}</Table.Cell>
										<Table.Cell>{#if d.file_key || d.file_url}<button type="button" class="text-primary hover:underline" onclick={() => openDoc(d)}>Ver</button>{:else}—{/if}</Table.Cell>
										<Table.Cell class="text-right"><Button variant="ghost" size="sm" onclick={() => removeDoc(d)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button></Table.Cell>
									</Table.Row>
								{/each}
							</Table.Body>
						</Table.Root>
					{/if}
				{:else}
					<div class="mb-3 flex flex-wrap justify-end gap-2">
						{#if events.length === 0}<Button size="sm" variant="outline" onclick={seedEvents} disabled={busy}><ListChecks class="mr-1 h-4 w-4" /> Generar hitos</Button>{/if}
						<Button size="sm" variant="outline" onclick={() => (addingEvent = true)}><Plus class="mr-1 h-4 w-4" /> Agregar hito</Button>
					</div>
					{#if addingEvent}
						<div class="mb-4 grid gap-3 rounded-md border p-3">
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Título del hito</span><input class={inputCls} bind:value={newEvent.title} /></label>
							<label class="flex flex-col gap-1 text-sm"><span class="font-medium">Notas</span><input class={inputCls} bind:value={newEvent.notes} /></label>
							<div class="flex justify-end gap-2"><Button variant="outline" size="sm" onclick={() => (addingEvent = false)}>Cancelar</Button><Button size="sm" onclick={saveEvent}>Guardar</Button></div>
						</div>
					{/if}
					{#if events.length === 0}
						<p class="text-sm text-muted-foreground">Sin hitos. Usa "Generar hitos" para crear la secuencia según el tipo de operación.</p>
					{:else}
						<ol class="space-y-2">
							{#each events as ev (ev.id)}
								<li class="flex items-center gap-3 rounded-md border p-3 {ev.status === 'rechazado' ? 'border-destructive/40' : ''}">
									<span class="flex h-6 w-6 shrink-0 items-center justify-center rounded-full text-xs {ev.status === 'completado' ? 'bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40 dark:text-emerald-400' : ev.status === 'rechazado' ? 'bg-destructive/10 text-destructive' : ev.kind === 'decision' ? 'bg-amber-100 text-amber-700 dark:bg-amber-950/40 dark:text-amber-400' : 'bg-muted text-muted-foreground'}">
										{#if ev.status === 'completado'}✓{:else if ev.kind === 'decision'}?{:else}{ev.position + 1}{/if}
									</span>
									<div class="flex-1">
										<p class="text-sm font-medium {ev.status === 'completado' ? 'line-through text-muted-foreground' : ''}">
											{ev.title}
											{#if ev.kind === 'decision'}<span class="ml-1 rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-amber-700 dark:bg-amber-950/40 dark:text-amber-400">decisión</span>{/if}
											{#if ev.parent_event_id}<span class="ml-1 inline-flex items-center gap-0.5 rounded bg-muted px-1.5 py-0.5 text-[10px] font-semibold uppercase text-muted-foreground"><GitBranch class="h-2.5 w-2.5" /> corrección · intento {ev.attempt}</span>{/if}
										</p>
										<p class="text-xs text-muted-foreground">
											{labelOf(EVENT_STATUS, ev.status)}{#if ev.outcome} → {ev.outcome}{/if}{#if ev.actual_date} · {formatDate(ev.actual_date)}{/if}
										</p>
										{#if ev.notes}<p class="text-xs text-muted-foreground">{ev.notes}</p>{/if}
									</div>
									{#if ev.kind === 'decision' && !ev.outcome}
										<Button variant="ghost" size="sm" onclick={() => decideEvent(ev, 'autorizado')} aria-label="Autorizar"><Check class="h-4 w-4 text-emerald-600" /></Button>
										<Button variant="ghost" size="sm" onclick={() => decideEvent(ev, 'rechazado')} aria-label="Rechazar"><X class="h-4 w-4 text-destructive" /></Button>
									{:else if ev.kind !== 'decision' && ev.status !== 'completado'}
										<Button variant="ghost" size="sm" onclick={() => completeEvent(ev)} aria-label="Completar"><Check class="h-4 w-4 text-emerald-600" /></Button>
									{/if}
									<Button variant="ghost" size="sm" onclick={() => removeEvent(ev)} aria-label="Eliminar"><Trash2 class="h-4 w-4 text-destructive" /></Button>
								</li>
							{/each}
						</ol>
					{/if}
				{/if}
			</Card.Content>
		</Card.Root>
	{/if}
</div>
