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

	const TYPE_LABEL: Record<string, string> = {
		kuehlschrank: 'Kühlschrank',
		tiefkuehl:    'Tiefkühl',
		warmhalte:    'Warmhalte',
		hygiene:      'Hygiene',
		sonstiges:    'Sonstiges'
	};

	let stations = $state<any[]>([]);
	let qrCodes = $state<Record<string, string>>({});
	let loading = $state(true);
	let tenantName = $state('');

	onMount(async () => {
		try {
			const user = await pb.collection('users').getOne(pb.authStore.record!.id);
			const tenantId = user.tenant;
			const tenant = await pb.collection('tenants').getOne(tenantId);
			tenantName = tenant.name;

			const result = await pb.collection('stations').getFullList({
				filter: `tenant = '${tenantId}' && active = true`,
				sort: 'name'
			});
			stations = result;

				// QR-Codes mit Logo generieren
			const codes: Record<string, string> = {};
			for (const s of result) {
				codes[s.qr_id] = await generateQRWithLogo(qrUrl(s.qr_id));
			}
			qrCodes = codes;
		} catch {
		} finally {
			loading = false;
		}
	});

	function qrUrl(qrId: string) {
		return `https://checkflo.de/s/${qrId}`;
	}

	async function generateQRWithLogo(url: string): Promise<string> {
		const size = 400;
		const canvas = document.createElement('canvas');
		canvas.width = size;
		canvas.height = size;

		await QRCode.toCanvas(canvas, url, {
			width: size,
			margin: 1,
			errorCorrectionLevel: 'H',
			color: { dark: '#0B1023', light: '#ffffff' }
		});

		const ctx = canvas.getContext('2d')!;
		const logoSize = Math.round(size * 0.22);
		const x = (size - logoSize) / 2;
		const y = (size - logoSize) / 2;
		const pad = 6;
		const r = 10;

		// Weißer abgerundeter Hintergrund
		ctx.fillStyle = '#ffffff';
		ctx.beginPath();
		ctx.roundRect(x - pad, y - pad, logoSize + pad * 2, logoSize + pad * 2, r);
		ctx.fill();

		// Logo laden und zeichnen
		const img = new Image();
		img.src = '/favicon.svg';
		await new Promise<void>(resolve => { img.onload = () => resolve(); });
		ctx.drawImage(img, x, y, logoSize, logoSize);

		return canvas.toDataURL('image/png');
	}

	function printAll() {
		window.print();
	}
</script>

<svelte:head><title>Stationen — checkflo</title></svelte:head>

<div class="page no-print">
	<div class="header-row">
		<div>
			<h1>Stationen</h1>
			<p class="hint-text">QR-Codes ausdrucken und an den Stationen befestigen.</p>
		</div>
		{#if stations.length > 0}
			<button class="btn-print" onclick={printAll}>
			<img src={iconPrinter} alt="" class="btn-icon" /> Alle drucken
		</button>
		{/if}
	</div>

	{#if loading}
		<p class="hint">Lädt…</p>
	{:else}
		<div class="list">
			{#each stations as s}
				<div class="card">
					<div class="card-body">
						<div class="card-info">
							<div class="station-name">{s.name}</div>
							<div class="station-type">{TYPE_LABEL[s.type] ?? s.type}
								{#if s.target_temp_min || s.target_temp_max}
									· {s.target_temp_min}° bis {s.target_temp_max}°C
								{/if}
							</div>
							<code class="qr-url">{qrUrl(s.qr_id)}</code>
						</div>
						{#if qrCodes[s.qr_id]}
							<img src={qrCodes[s.qr_id]} alt="QR {s.name}" class="qr-img" />
						{/if}
					</div>
				</div>
			{/each}
		</div>
	{/if}
</div>

<!-- Druckansicht -->
{#if !loading}
	<div class="print-sheet">
		{#each stations as s}
			<div class="print-card">
				<div class="print-tenant">{tenantName}</div>
				<div class="print-name">{s.name}</div>
				<div class="print-type">{TYPE_LABEL[s.type] ?? s.type}
					{#if s.target_temp_min || s.target_temp_max}
						· Zielbereich {s.target_temp_min}° bis {s.target_temp_max}°C
					{/if}
				</div>
				{#if qrCodes[s.qr_id]}
					<img src={qrCodes[s.qr_id]} alt="QR" class="print-qr" />
				{/if}
				<div class="print-url">{qrUrl(s.qr_id)}</div>
				<div class="print-footer">Scan → Checkliste ausfüllen → fertig</div>
			</div>
		{/each}
	</div>
{/if}

<style>
	.page { max-width: 800px; }
	.header-row { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 2rem; }
	h1 { font-size: 1.6rem; font-weight: 800; color: #0B1023; margin-bottom: 0.25rem; }
	.hint-text { color: #666; font-size: 0.9rem; }
	.hint { color: #aaa; }

	.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;
		white-space: nowrap;
	}
	.btn-print:hover { background: #1a2640; }
	.btn-icon {
		width: 16px;
		height: 16px;
		vertical-align: middle;
		margin-right: 0.25rem;
		filter: brightness(0) invert(1);
	}

	.list { display: flex; flex-direction: column; gap: 1rem; }
	.card {
		background: #fff;
		border-radius: 12px;
		padding: 1.25rem 1.5rem;
		box-shadow: 0 1px 4px rgba(0,0,0,0.06);
	}
	.card-body { display: flex; align-items: center; justify-content: space-between; gap: 1rem; }
	.card-info { flex: 1; }
	.station-name { font-weight: 700; font-size: 1.05rem; color: #0B1023; }
	.station-type { font-size: 0.85rem; color: #888; margin: 0.2rem 0 0.75rem; }
	.qr-url {
		font-size: 0.75rem;
		background: #F5F7FA;
		padding: 0.4rem 0.6rem;
		border-radius: 5px;
		color: #555;
		display: block;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
		max-width: 400px;
	}
	.qr-img { width: 100px; height: 100px; flex-shrink: 0; }

	/* Druckansicht — nur beim Drucken sichtbar */
	.print-sheet { display: none; }

	@media print {
		.no-print { display: none !important; }

		.print-sheet {
			display: grid;
			grid-template-columns: repeat(2, 1fr);
			gap: 0;
		}

		.print-card {
			border: 1px solid #ddd;
			padding: 1.5rem;
			text-align: center;
			page-break-inside: avoid;
			break-inside: avoid;
		}

		.print-tenant { font-size: 0.7rem; color: #888; text-transform: uppercase; letter-spacing: 1px; margin-bottom: 0.5rem; }
		.print-name { font-size: 1.2rem; font-weight: 800; color: #0B1023; margin-bottom: 0.25rem; }
		.print-type { font-size: 0.8rem; color: #666; margin-bottom: 1rem; }
		.print-qr { width: 160px; height: 160px; margin: 0 auto 0.75rem; display: block; }
		.print-url { font-size: 0.65rem; color: #888; margin-bottom: 0.5rem; word-break: break-all; }
		.print-footer { font-size: 0.7rem; color: #F97316; font-weight: 600; }
	}
</style>
