<script lang="ts">
	import { pb } from '$lib/pb';
	import { onMount } from 'svelte';
	import iconPrinter from '$lib/assets/icons/printer.svg';

	const STATUS_LABEL: Record<string, string> = { ok: 'OK', abweichung: 'Abweichung', kritisch: 'Kritisch' };
	const STATUS_COLOR: Record<string, string> = { ok: '#16a34a', abweichung: '#ea580c', kritisch: '#dc2626' };

	const now = new Date();
	let selectedMonth = $state(now.getMonth() + 1);
	let selectedYear  = $state(now.getFullYear());

	let logs = $state<any[]>([]);
	let tenantName = $state('');
	let loading = $state(true);

	const months = ['Januar','Februar','März','April','Mai','Juni',
	                 'Juli','August','September','Oktober','November','Dezember'];

	onMount(() => loadData());

	async function loadData() {
		loading = true;
		try {
			const user = await pb.collection('users').getOne(pb.authStore.record!.id);
			const tenant = await pb.collection('tenants').getOne(user.tenant);
			tenantName = tenant.name;

			const from = `${selectedYear}-${String(selectedMonth).padStart(2,'0')}-01 00:00:00`;
			const lastDay = new Date(selectedYear, selectedMonth, 0).getDate();
			const to   = `${selectedYear}-${String(selectedMonth).padStart(2,'0')}-${lastDay} 23:59:59`;

			const result = await pb.collection('check_logs').getFullList({
				filter: `tenant = '${user.tenant}' && created >= '${from}' && created <= '${to}'`,
				expand: 'station',
				sort: 'created'
			});
			logs = result;
		} catch {
		} finally {
			loading = false;
		}
	}

	function formatDate(iso: string) {
		if (!iso) return '—';
		const d = new Date(iso);
		if (isNaN(d.getTime())) return '—';
		return d.toLocaleString('de-DE', { day:'2-digit', month:'2-digit', year:'2-digit', hour:'2-digit', minute:'2-digit' });
	}

	// Logs nach Station gruppieren
	const byStation = $derived(() => {
		const map: Record<string, any[]> = {};
		for (const log of logs) {
			const name = log.expand?.station?.name ?? 'Unbekannt';
			(map[name] ??= []).push(log);
		}
		return map;
	});
</script>

<svelte:head><title>Protokoll {months[selectedMonth-1]} {selectedYear} — checkflo</title></svelte:head>

<!-- Steuerung (nicht drucken) -->
<div class="controls no-print">
	<div class="controls-left">
		<h1>Monatsprotokoll</h1>
	</div>
	<div class="controls-right">
		<select bind:value={selectedMonth} onchange={loadData}>
			{#each months as m, i}
				<option value={i+1}>{m}</option>
			{/each}
		</select>
		<select bind:value={selectedYear} onchange={loadData}>
			{#each [2025, 2026, 2027] as y}
				<option value={y}>{y}</option>
			{/each}
		</select>
		<button class="btn-print" onclick={() => window.print()}>
			<img src={iconPrinter} alt="" class="btn-icon" /> Drucken / PDF
		</button>
	</div>
</div>

<!-- Protokoll (wird gedruckt) -->
<div class="protokoll">
	<div class="protokoll-header">
		<div>
			<div class="protokoll-title">HACCP-Temperatur & Hygieneprotokoll</div>
			<div class="protokoll-subtitle">{months[selectedMonth-1]} {selectedYear}</div>
		</div>
		<div class="protokoll-tenant">{tenantName}</div>
	</div>

	{#if loading}
		<p class="hint no-print">Lädt…</p>
	{:else if logs.length === 0}
		<p class="hint no-print">Keine Einträge im gewählten Zeitraum.</p>
		<p class="empty-print">Keine Einträge im {months[selectedMonth-1]} {selectedYear}.</p>
	{:else}
		{#each Object.entries(byStation()) as [stationName, stationLogs]}
			<div class="station-block">
				<div class="station-header">{stationName}</div>
				<table>
					<thead>
						<tr>
							<th>Datum / Zeit</th>
							<th>Temp. (°C)</th>
							<th>Status</th>
							<th>Notiz</th>
							<th>Geprüft von</th>
						</tr>
					</thead>
					<tbody>
						{#each stationLogs as log}
							<tr>
								<td>{formatDate(log.created)}</td>
								<td>{log.temperature ? log.temperature + ' °C' : '—'}</td>
								<td>
									<span class="badge" style="color:{STATUS_COLOR[log.status]}">
										{STATUS_LABEL[log.status] ?? log.status}
									</span>
								</td>
								<td>{log.notes || '—'}</td>
								<td>{log.checked_by}</td>
							</tr>
						{/each}
					</tbody>
				</table>
			</div>
		{/each}

		<div class="summary">
			<strong>Gesamt:</strong> {logs.length} Einträge ·
			{logs.filter(l=>l.status==='ok').length} OK ·
			{logs.filter(l=>l.status==='abweichung').length} Abweichungen ·
			{logs.filter(l=>l.status==='kritisch').length} Kritisch
		</div>
	{/if}

	<div class="protokoll-footer">
		<div>Erstellt: {new Date().toLocaleDateString('de-DE')} · checkflo.de</div>
		<div class="signature-block">
			<div class="signature-line">___________________________</div>
			<div class="signature-label">Unterschrift Verantwortlicher</div>
		</div>
	</div>
</div>

<style>
	.controls {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 2rem;
		flex-wrap: wrap;
		gap: 1rem;
	}
	h1 { font-size: 1.6rem; font-weight: 800; color: #0B1023; }
	.controls-right { display: flex; gap: 0.75rem; align-items: center; flex-wrap: wrap; }

	select {
		padding: 0.5rem 0.75rem;
		border: 1.5px solid #ddd;
		border-radius: 8px;
		font-size: 0.9rem;
		background: #fff;
	}

	.btn-print {
		padding: 0.6rem 1.25rem;
		background: #0B1023;
		color: #fff;
		border: none;
		border-radius: 8px;
		font-size: 0.9rem;
		font-weight: 600;
		cursor: pointer;
	}
	.btn-print:hover { background: #1a2640; }
	.btn-icon { width: 16px; height: 16px; vertical-align: middle; margin-right: 0.25rem; filter: brightness(0) invert(1); }
	.hint { color: #aaa; }
	.empty-print { display: none; }

	/* Protokoll-Layout */
	.protokoll {
		background: #fff;
		border-radius: 12px;
		padding: 2rem;
		box-shadow: 0 1px 4px rgba(0,0,0,0.06);
		max-width: 900px;
	}

	.protokoll-header {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		border-bottom: 2px solid #0B1023;
		padding-bottom: 1rem;
		margin-bottom: 1.5rem;
	}
	.protokoll-title { font-size: 1.1rem; font-weight: 800; color: #0B1023; }
	.protokoll-subtitle { font-size: 0.9rem; color: #666; margin-top: 0.25rem; }
	.protokoll-tenant { font-weight: 700; color: #0B1023; text-align: right; }

	.station-block { margin-bottom: 2rem; }
	.station-header {
		background: #F5F7FA;
		padding: 0.5rem 1rem;
		font-weight: 700;
		font-size: 0.95rem;
		color: #0B1023;
		border-left: 3px solid #F97316;
		margin-bottom: 0.5rem;
		border-radius: 0 4px 4px 0;
	}

	table { width: 100%; border-collapse: collapse; font-size: 0.85rem; }
	th { background: #F5F7FA; padding: 0.5rem 0.75rem; text-align: left; font-size: 0.75rem; color: #888; text-transform: uppercase; }
	td { padding: 0.5rem 0.75rem; border-bottom: 1px solid #f0f0f0; }
	tr:last-child td { border-bottom: none; }

	.badge { font-weight: 700; }

	.summary {
		margin-top: 1.5rem;
		padding: 0.75rem 1rem;
		background: #F5F7FA;
		border-radius: 8px;
		font-size: 0.9rem;
		color: #555;
	}

	.protokoll-footer {
		margin-top: 3rem;
		display: flex;
		justify-content: space-between;
		align-items: flex-end;
		font-size: 0.8rem;
		color: #aaa;
	}
	.signature-block { text-align: center; }
	.signature-line { border-top: 1px solid #999; width: 200px; margin-bottom: 0.25rem; }
	.signature-label { font-size: 0.75rem; color: #888; }

	@media print {
		.no-print { display: none !important; }
		.empty-print { display: block; }
		.protokoll {
			box-shadow: none;
			padding: 0;
			border-radius: 0;
		}
		table { font-size: 0.8rem; }
		@page { margin: 15mm; size: A4; }
	}
</style>
