<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import { invoke } from '@tauri-apps/api/core';
	import { listen, type UnlistenFn } from '@tauri-apps/api/event';
	import { updateDialogOpen, updateCheckManual } from '$lib/stores/updateTrigger';

	interface UpdateStatus {
		available: boolean;
		current_version: string;
		latest_version: string | null;
		release_notes: string | null;
		download_url: string | null;
		download_size: number | null;
		sha256: string | null;
	}

	interface DownloadProgress {
		downloaded: number;
		total: number;
		percent: number;
	}

	let updateInfo: UpdateStatus | null = null;
	let downloading = false;
	let progress: DownloadProgress | null = null;
	let error: string | null = null;
	let downloadedPath: string | null = null;
	let checking = false;
	let manualMode = false;

	let progressListener: UnlistenFn | null = null;
	let manualUnsub: (() => void) | null = null;

	// Reaktiv: wenn Store schließt → State zurücksetzen
	$: if (!$updateDialogOpen) {
		resetState();
	}

	// Manueller Check-Trigger aus dem Settings-Panel
	$: manualMode = $updateCheckManual;

	onMount(async () => {
		// Progress-Events vom Backend
		progressListener = await listen<DownloadProgress>('update-progress', (event) => {
			progress = event.payload;
		});

		// Manueller Check wird via Store gestartet
		manualUnsub = updateCheckManual.subscribe((active) => {
			if (active) {
				// Store-Reset, bevor wir starten — damit erneutes Klicken wieder triggert
				updateCheckManual.set(false);
				runCheck(true);
			}
		});

		// Auto-Check 3s nach Start (nur wenn Dialog nicht bereits offen)
		setTimeout(() => runCheck(false), 3000);
	});

	onDestroy(() => {
		progressListener?.();
		manualUnsub?.();
	});

	async function runCheck(manual: boolean) {
		checking = true;
		error = null;
		try {
			const status: UpdateStatus = await invoke('check_for_update');
			updateInfo = status;
			if (status.available) {
				manualMode = manual;
				updateDialogOpen.set(true);
			} else if (manual) {
				// Bei manuellem Check auch "kein Update"-Dialog zeigen
				manualMode = true;
				updateDialogOpen.set(true);
			}
		} catch (err) {
			if (manual) {
				error = String(err);
				updateDialogOpen.set(true);
			} else {
				console.debug('Auto-Update-Check fehlgeschlagen:', err);
			}
		} finally {
			checking = false;
		}
	}

	async function startDownload() {
		if (!updateInfo?.download_url) return;

		downloading = true;
		error = null;
		progress = { downloaded: 0, total: 0, percent: 0 };

		try {
			downloadedPath = await invoke('download_update', {
				downloadUrl: updateInfo.download_url,
				expectedSha256: updateInfo.sha256,
			});
			console.log('✅ Download abgeschlossen:', downloadedPath);
		} catch (err) {
			error = String(err);
			downloading = false;
		}
	}

	async function applyUpdate() {
		if (!downloadedPath) return;
		try {
			await invoke('apply_update', { updatePath: downloadedPath });
			// App startet neu, kein weiterer Code erreicht
		} catch (err) {
			error = String(err);
		}
	}

	function closeDialog() {
		updateDialogOpen.set(false);
	}

	function resetState() {
		downloading = false;
		progress = null;
		error = null;
		downloadedPath = null;
		manualMode = false;
	}

	function formatSize(bytes: number): string {
		if (bytes < 1024) return `${bytes} B`;
		if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
		return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
	}

	$: isNoUpdateDialog = $updateDialogOpen && updateInfo && !updateInfo.available && !error;
</script>

{#if $updateDialogOpen && updateInfo}
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="modal-overlay" on:click={closeDialog}>
		<div class="modal" on:click|stopPropagation>
			<div class="modal-header">
				{#if isNoUpdateDialog}
					<h2>✅ Aktuell</h2>
				{:else if error && !updateInfo.available}
					<h2>⚠️ Update-Check fehlgeschlagen</h2>
				{:else}
					<h2>🔄 Update verfügbar</h2>
				{/if}
				<button class="close-btn" on:click={closeDialog}>✕</button>
			</div>

			<div class="modal-body">
				{#if isNoUpdateDialog}
					<p class="no-update-text">
						Du verwendest bereits die neueste Version:
						<strong>v{updateInfo.current_version}</strong>
					</p>
				{:else if updateInfo.available}
					<div class="version-info">
						<span class="current">v{updateInfo.current_version}</span>
						<span class="arrow">→</span>
						<span class="new">v{updateInfo.latest_version}</span>
					</div>

					{#if updateInfo.release_notes}
						<div class="release-notes">
							<h3>Änderungen:</h3>
							<div class="notes-content">
								{@html updateInfo.release_notes.replace(/\n/g, '<br>')}
							</div>
						</div>
					{/if}

					{#if downloading && progress}
						<div class="progress-container">
							<div class="progress-bar">
								<div class="progress-fill" style="width: {progress.percent}%"></div>
							</div>
							<span class="progress-text">
								{#if progress.total > 0}
									{formatSize(progress.downloaded)} / {formatSize(progress.total)}
									({progress.percent.toFixed(0)}%)
								{:else}
									{formatSize(progress.downloaded)} geladen...
								{/if}
							</span>
						</div>
					{/if}
				{/if}

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

			<div class="modal-footer">
				{#if isNoUpdateDialog}
					<button class="btn btn-primary" on:click={closeDialog}>OK</button>
				{:else if downloadedPath}
					<button class="btn btn-primary" on:click={applyUpdate}>
						Jetzt installieren & neustarten
					</button>
				{:else if downloading}
					<button class="btn btn-disabled" disabled>
						Wird heruntergeladen...
					</button>
				{:else if updateInfo.available}
					<button class="btn btn-secondary" on:click={closeDialog}>Später</button>
					<button class="btn btn-primary" on:click={startDownload}>
						Jetzt aktualisieren
					</button>
				{:else}
					<button class="btn btn-primary" on:click={closeDialog}>Schließen</button>
				{/if}
			</div>
		</div>
	</div>
{/if}

<style>
	.modal-overlay {
		position: fixed;
		inset: 0;
		background: rgba(0, 0, 0, 0.6);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.modal {
		background: var(--bg-primary);
		border: 1px solid var(--border);
		border-radius: var(--radius-lg);
		width: 90%;
		max-width: 450px;
		box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
	}

	.modal-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: var(--spacing-md);
		border-bottom: 1px solid var(--border);
	}

	.modal-header h2 {
		font-size: 1rem;
		margin: 0;
	}

	.close-btn {
		background: none;
		border: none;
		font-size: 1.2rem;
		cursor: pointer;
		color: var(--text-secondary);
		padding: 4px;
	}

	.close-btn:hover {
		color: var(--text-primary);
	}

	.modal-body {
		padding: var(--spacing-md);
	}

	.version-info {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: var(--spacing-md);
		font-size: 1.1rem;
		margin-bottom: var(--spacing-md);
	}

	.version-info .current {
		color: var(--text-secondary);
	}

	.version-info .arrow {
		color: var(--accent);
	}

	.version-info .new {
		color: var(--success);
		font-weight: 600;
	}

	.no-update-text {
		text-align: center;
		font-size: 0.95rem;
		margin: var(--spacing-md) 0;
	}

	.release-notes {
		background: var(--bg-secondary);
		border-radius: var(--radius-md);
		padding: var(--spacing-sm);
		margin-bottom: var(--spacing-md);
		max-height: 150px;
		overflow-y: auto;
	}

	.release-notes h3 {
		font-size: 0.8rem;
		color: var(--text-secondary);
		margin: 0 0 var(--spacing-xs) 0;
	}

	.notes-content {
		font-size: 0.85rem;
		line-height: 1.5;
	}

	.progress-container {
		margin: var(--spacing-md) 0;
	}

	.progress-bar {
		height: 8px;
		background: var(--bg-tertiary);
		border-radius: 4px;
		overflow: hidden;
	}

	.progress-fill {
		height: 100%;
		background: var(--accent);
		transition: width 0.2s ease;
	}

	.progress-text {
		display: block;
		text-align: center;
		font-size: 0.75rem;
		color: var(--text-secondary);
		margin-top: var(--spacing-xs);
	}

	.error {
		background: rgba(239, 68, 68, 0.1);
		border: 1px solid rgba(239, 68, 68, 0.3);
		color: #ef4444;
		padding: var(--spacing-sm);
		border-radius: var(--radius-md);
		font-size: 0.85rem;
		margin-top: var(--spacing-md);
	}

	.modal-footer {
		display: flex;
		justify-content: flex-end;
		gap: var(--spacing-sm);
		padding: var(--spacing-md);
		border-top: 1px solid var(--border);
	}

	.btn {
		padding: var(--spacing-sm) var(--spacing-md);
		border-radius: var(--radius-md);
		font-size: 0.85rem;
		font-weight: 500;
		cursor: pointer;
		transition: all 0.15s ease;
	}

	.btn-primary {
		background: var(--accent);
		color: white;
		border: none;
	}

	.btn-primary:hover {
		background: var(--accent-hover);
	}

	.btn-secondary {
		background: transparent;
		color: var(--text-secondary);
		border: 1px solid var(--border);
	}

	.btn-secondary:hover {
		background: var(--bg-hover);
	}

	.btn-disabled {
		background: var(--bg-tertiary);
		color: var(--text-secondary);
		border: none;
		cursor: not-allowed;
	}
</style>
