<script lang="ts">
	import { untrack } from 'svelte';
	import type { PdfState } from '$lib/server/pdf/state';

	let {
		agenziaId,
		state: initialState,
		generatoIl,
		compact = false
	}: { agenziaId: number; state: PdfState; generatoIl: string | null; compact?: boolean } = $props();

	// stato locale: parte dal valore SSR (snapshot iniziale), poi gestito dal polling in autonomia.
	// untrack() impedisce a Svelte 5 di tracciare initialState come dipendenza reattiva —
	// il prop serve solo come seed; dopodiché il componente gestisce la transizione di stato.
	let state = $state<PdfState>(untrack(() => initialState));
	let timer: ReturnType<typeof setInterval> | null = null;

	async function trigger() {
		const r = await fetch(`/api/dvr/${agenziaId}/pdf`, { method: 'POST' });
		if (r.ok || r.status === 202) {
			state = 'generating';
			startPolling();
		}
	}

	function startPolling() {
		if (timer) return;
		timer = setInterval(async () => {
			const r = await fetch(`/api/dvr/${agenziaId}/pdf?mode=status`);
			const j = await r.json();
			if (j.state !== 'generating') {
				state = j.state;
				if (timer) {
					clearInterval(timer);
					timer = null;
				}
			}
		}, 12000);
	}

	// Il polling riparte anche se la pagina è stata aperta con il PDF già in generazione
	$effect(() => {
		if (untrack(() => state) === 'generating') startPolling();
		return () => {
			if (timer) clearInterval(timer);
		};
	});

	// compact = pillola da lista; altrimenti bottone grande da scheda
	const base = $derived(
		compact
			? 'inline-flex w-32 items-center justify-center gap-1 rounded px-2 py-0.5 text-xs font-medium'
			: 'inline-flex items-center gap-1.5 rounded-md px-4 py-2 text-sm font-semibold text-white shadow-sm transition'
	);
	const cls = $derived({
		brand: `${base} ${compact ? 'bg-brand-50 text-brand-700 hover:bg-brand-100' : 'bg-brand-500 hover:bg-brand-600'}`,
		amber: `${base} ${compact ? 'bg-amber-100 text-amber-800 hover:bg-amber-200' : 'bg-amber-500 hover:bg-amber-600'}`,
		red: `${base} ${compact ? 'bg-red-50 text-red-700 hover:bg-red-100' : 'bg-red-500 hover:bg-red-600'}`
	});
	const wait = $derived(compact ? 'in preparazione…' : 'PDF in aggiornamento, pronto tra ~1 min…');
</script>

{#if state === 'ready'}
	<a href={`/api/dvr/${agenziaId}/pdf`} class={cls.brand} title="Il PDF è allineato ai dati attuali">⬇ Scarica PDF</a>
	{#if generatoIl && !compact}
		<span class="ml-2 text-xs text-slate-500">generato il {generatoIl.slice(0, 10)}</span>
	{/if}
{:else if state === 'generating'}
	<span class="inline-flex items-center gap-1.5 {compact ? 'w-32 justify-center text-xs text-amber-700' : 'text-sm text-slate-600'}">
		<span class="inline-block animate-spin select-none">↻</span>
		{wait}
	</span>
	{#if !compact}
		<a href={`/api/dvr/${agenziaId}/pdf?allowStale=1`} class="ml-2 text-xs text-slate-500 underline">scarica versione precedente</a>
	{/if}
{:else if state === 'stale'}
	<button onclick={trigger} class={cls.amber} title="I dati del DVR sono cambiati dopo l'ultimo PDF: rigeneralo prima di scaricarlo">
		{compact ? '↻ Rigenera PDF' : 'Aggiorna PDF'}
	</button>
	{#if !compact}
		<a href={`/api/dvr/${agenziaId}/pdf?allowStale=1`} class="ml-2 text-xs text-slate-500 underline">scarica versione precedente</a>
	{/if}
{:else if state === 'error'}
	<button onclick={trigger} class={cls.red}>Errore — riprova</button>
{:else}
	<!-- missing -->
	<button onclick={trigger} class={cls.brand}>⚙ Genera PDF</button>
{/if}
