<script lang="ts">
	import { pb } from '$lib/pb';

	let { data } = $props();
	const station = $derived(data.station);
	const tenant = $derived(station.expand?.tenant);
	const primaryColor = $derived(tenant?.primary_color ?? '#e85d04');

	type Status = 'ok' | 'abweichung' | 'kritisch';

	let temperature = $state<string>('');
	let status = $state<Status | null>(null);
	let notes = $state('');
	let checkedBy = $state('');
	let photo = $state<File | null>(null);
	let photoPreview = $state<string | null>(null);

	let submitting = $state(false);
	let submitted = $state(false);
	let submittedAt = $state('');
	let error = $state('');

	const statusLabels: Record<Status, string> = {
		ok: '✓  Alles in Ordnung',
		abweichung: '⚠  Abweichung',
		kritisch: '✗  Kritisch'
	};

	const showTemp = $derived(
		station.type === 'kuehlschrank' ||
		station.type === 'tiefkuehl' ||
		station.type === 'warmhalte'
	);

	function onPhoto(e: Event) {
		const file = (e.target as HTMLInputElement).files?.[0];
		if (!file) return;
		photo = file;
		photoPreview = URL.createObjectURL(file);
	}

	async function submit() {
		if (!status) { error = 'Bitte Status auswählen.'; return; }
		if (!checkedBy.trim()) { error = 'Bitte Namen eintragen.'; return; }
		error = '';
		submitting = true;

		try {
			const fd = new FormData();
			fd.append('station', station.id);
			fd.append('tenant', station.tenant);
			fd.append('status', status);
			fd.append('notes', notes);
			fd.append('checked_by', checkedBy.trim());
			if (temperature) fd.append('temperature', temperature);
			if (photo) fd.append('photo', photo);

			await pb.collection('check_logs').create(fd);

			submittedAt = new Date().toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' });
			submitted = true;
		} catch (e) {
			error = 'Fehler beim Speichern. Bitte erneut versuchen.';
		} finally {
			submitting = false;
		}
	}

	function reset() {
		temperature = '';
		status = null;
		notes = '';
		photo = null;
		photoPreview = null;
		submitted = false;
		error = '';
	}
</script>

<svelte:head>
	<title>{station.name} — checkflo</title>
</svelte:head>

<div class="page" style="--brand: {primaryColor}">

	<!-- HEADER -->
	<header>
		{#if tenant?.name}<div class="tenant-name">{tenant.name}</div>{/if}
		<div class="station-name">{station.name}</div>
		{#if station.target_temp_min || station.target_temp_max}
			<div class="temp-range">
				Zielbereich: {station.target_temp_min}° bis {station.target_temp_max}°C
			</div>
		{/if}
	</header>

	<!-- ERFOLG -->
	{#if submitted}
		<div class="success">
			<div class="success-icon">✓</div>
			<h2>Erfasst um {submittedAt} Uhr</h2>
			<p>Der Eintrag wurde gespeichert.</p>
			<button class="btn-primary" onclick={reset}>Neuen Eintrag erfassen</button>
		</div>

	<!-- FORMULAR -->
	{:else}
		<form onsubmit={(e) => { e.preventDefault(); submit(); }}>

			<!-- TEMPERATUR -->
			{#if showTemp}
				<div class="field">
					<label for="temp">Temperatur (°C)</label>
					<input
						id="temp"
						type="number"
						inputmode="decimal"
						step="0.1"
						placeholder="z.B. 4.5"
						bind:value={temperature}
					/>
				</div>
			{/if}

			<!-- STATUS -->
			<div class="field">
				<span class="field-label">Status *</span>
				<div class="status-buttons">
					{#each (Object.keys(statusLabels) as Status[]) as s}
						<button
							type="button"
							class="status-btn status-{s}"
							class:active={status === s}
							onclick={() => status = s}
						>
							{statusLabels[s]}
						</button>
					{/each}
				</div>
			</div>

			<!-- NOTIZ -->
			{#if status === 'abweichung' || status === 'kritisch'}
				<div class="field">
					<label for="notes">Beschreibung der Abweichung *</label>
					<textarea id="notes" rows="3" placeholder="Was wurde festgestellt?" bind:value={notes}></textarea>
				</div>
			{/if}

			<!-- FOTO -->
			<div class="field">
				<span class="field-label">Foto (optional)</span>
				{#if photoPreview}
					<img src={photoPreview} alt="Vorschau" class="photo-preview" />
				{/if}
				<label class="file-btn">
					📷 {photo ? 'Foto ändern' : 'Foto aufnehmen'}
					<input type="file" accept="image/*" capture="environment" onchange={onPhoto} hidden />
				</label>
			</div>

			<!-- NAME -->
			<div class="field">
				<label for="name">Ihr Name *</label>
				<input id="name" type="text" placeholder="Max Mustermann" bind:value={checkedBy} />
			</div>

			{#if error}
				<p class="error">{error}</p>
			{/if}

			<button type="submit" class="btn-primary btn-submit" disabled={submitting}>
				{submitting ? 'Wird gespeichert…' : 'Eintrag speichern'}
			</button>
		</form>
	{/if}

	<footer>
		{#if tenant?.name}<span>{tenant.name}</span>{/if}
	</footer>
</div>

<style>
	.page {
		min-height: 100dvh;
		display: flex;
		flex-direction: column;
		max-width: 480px;
		margin: 0 auto;
		padding: 0 0 0.5rem;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
	}

	/* HEADER */
	header {
		background: var(--brand);
		color: #fff;
		padding: 2rem 1.5rem 1.5rem;
	}
	.tenant-name {
		font-size: 0.8rem;
		opacity: 0.8;
		text-transform: uppercase;
		letter-spacing: 1px;
		margin-bottom: 0.25rem;
	}
	.station-name {
		font-size: 1.6rem;
		font-weight: 800;
		line-height: 1.2;
	}
	.temp-range {
		margin-top: 0.5rem;
		font-size: 0.85rem;
		opacity: 0.85;
	}

	/* FORMULAR */
	form {
		padding: 1.5rem;
		display: flex;
		flex-direction: column;
		gap: 1.5rem;
		flex: 1;
	}

	.field { display: flex; flex-direction: column; gap: 0.5rem; }

	label, .field-label {
		font-size: 0.9rem;
		font-weight: 600;
		color: #333;
	}

	input[type='text'],
	input[type='number'],
	textarea {
		border: 1.5px solid #ddd;
		border-radius: 8px;
		padding: 0.75rem 1rem;
		font-size: 1rem;
		width: 100%;
		transition: border-color 0.15s;
	}
	input:focus, textarea:focus {
		outline: none;
		border-color: var(--brand);
	}
	textarea { resize: vertical; }

	/* STATUS BUTTONS */
	.status-buttons {
		display: flex;
		flex-direction: column;
		gap: 0.6rem;
	}
	.status-btn {
		padding: 1rem;
		border-radius: 10px;
		border: 2px solid transparent;
		font-size: 1rem;
		font-weight: 600;
		cursor: pointer;
		text-align: left;
		transition: all 0.15s;
	}
	.status-ok         { background: #f0fdf4; color: #166534; border-color: #bbf7d0; }
	.status-abweichung { background: #fff7ed; color: #9a3412; border-color: #fed7aa; }
	.status-kritisch   { background: #fef2f2; color: #991b1b; border-color: #fecaca; }

	.status-ok.active         { background: #dcfce7; border-color: #16a34a; }
	.status-abweichung.active { background: #ffedd5; border-color: #ea580c; }
	.status-kritisch.active   { background: #fee2e2; border-color: #dc2626; }

	/* FOTO */
	.photo-preview {
		width: 100%;
		border-radius: 8px;
		margin-bottom: 0.5rem;
	}
	.file-btn {
		display: inline-flex;
		align-items: center;
		gap: 0.5rem;
		padding: 0.75rem 1.25rem;
		border: 1.5px dashed #ccc;
		border-radius: 8px;
		cursor: pointer;
		font-size: 0.95rem;
		font-weight: 500;
		color: #555;
		transition: border-color 0.15s;
	}
	.file-btn:hover { border-color: var(--brand); color: var(--brand); }

	/* BUTTONS */
	.btn-primary {
		background: var(--brand);
		color: #fff;
		border: none;
		border-radius: 10px;
		padding: 1rem;
		font-size: 1.05rem;
		font-weight: 700;
		cursor: pointer;
		width: 100%;
		transition: opacity 0.15s;
	}
	.btn-primary:disabled { opacity: 0.6; cursor: not-allowed; }
	.btn-submit { margin-top: 0.5rem; }

	/* FEHLER */
	.error {
		color: #dc2626;
		font-size: 0.9rem;
		padding: 0.75rem 1rem;
		background: #fef2f2;
		border-radius: 8px;
	}

	/* ERFOLG */
	.success {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 2rem;
		text-align: center;
		gap: 1rem;
	}
	.success-icon {
		width: 4rem;
		height: 4rem;
		background: #dcfce7;
		color: #16a34a;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 1.8rem;
		font-weight: 700;
	}
	.success h2 { font-size: 1.4rem; }
	.success p  { color: #666; }

	/* FOOTER */
	footer {
		text-align: center;
		padding: 0.5rem;
		font-size: 0.75rem;
		color: #ccc;
		margin-top: auto;
	}
</style>
