<script lang="ts">
	import { onMount, onDestroy } from 'svelte';
	import * as pdfjsLib from 'pdfjs-dist';
	import { api } from '$lib/api';

	pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.mjs';

	interface Props {
		pdfUrl: string;
		title?: string;
		key?: string;
	}

	let { pdfUrl, title = 'Partition', key = '' }: Props = $props();

	// Force re-render when key changes
	$effect(() => {
		if (key) {
			loadPdf();
		}
	});

	let canvas: HTMLCanvasElement;
	let pdfDoc: pdfjsLib.PDFDocumentProxy | null = null;
	let currentPage = $state(1);
	let totalPages = $state(0);
	let scale = $state(1.2);
	let loading = $state(true);
	let error = $state('');
	let rendering = $state(false);
	let isFullscreen = $state(false);

	async function loadPdf() {
		loading = true;
		error = '';
		try {
			// Load PDF via axios to include auth token
			const path = pdfUrl.split('/download/')[1];
			const response = await api.get(`/download/${path}`, {
				responseType: 'blob'
			});
			const blob = new Blob([response.data], { type: 'application/pdf' });
			const url = URL.createObjectURL(blob);
			
			const loadingTask = pdfjsLib.getDocument(url);
			pdfDoc = await loadingTask.promise;
			totalPages = pdfDoc.numPages;
			await renderPage(currentPage);
		} catch (err) {
			console.error('Error loading PDF:', err);
			error = 'Erreur lors du chargement du PDF';
		} finally {
			loading = false;
		}
	}

	async function renderPage(pageNum: number) {
		if (!pdfDoc || rendering) return;
		rendering = true;

		try {
			const page = await pdfDoc.getPage(pageNum);
			const viewport = page.getViewport({ scale });
			const context = canvas.getContext('2d');

			if (!context) return;

			canvas.height = viewport.height;
			canvas.width = viewport.width;

			await page.render({
				canvasContext: context,
				viewport
			}).promise;
		} catch (err) {
			console.error('Error rendering page:', err);
		} finally {
			rendering = false;
		}
	}

	function prevPage() {
		if (currentPage > 1) {
			currentPage--;
			renderPage(currentPage);
		}
	}

	function nextPage() {
		if (currentPage < totalPages) {
			currentPage++;
			renderPage(currentPage);
		}
	}

	function zoomIn() {
		scale = Math.min(scale + 0.2, 3);
		renderPage(currentPage);
	}

	function zoomOut() {
		scale = Math.max(scale - 0.2, 0.5);
		renderPage(currentPage);
	}

	function toggleFullscreen() {
		isFullscreen = !isFullscreen;
	}

	function handleKeydown(e: KeyboardEvent) {
		if (e.key === 'Escape' && isFullscreen) {
			isFullscreen = false;
		} else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
			prevPage();
		} else if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
			nextPage();
		}
	}

	onMount(() => {
		loadPdf();
		window.addEventListener('keydown', handleKeydown);
	});

	onDestroy(() => {
		window.removeEventListener('keydown', handleKeydown);
		if (pdfDoc) {
			pdfDoc.destroy();
		}
	});

	$effect(() => {
		if (pdfUrl) {
			loadPdf();
		}
	});
</script>

<div class="flex flex-col h-full" class:fixed={isFullscreen} class:inset-0={isFullscreen} class:z-50={isFullscreen} class:bg-gray-900={isFullscreen}>
	<div class="bg-ohmj-dark text-white px-4 py-2 flex items-center justify-between border-b border-gray-700">
		<div class="flex items-center gap-2">
			<span class="font-semibold">{title}</span>
			{#if totalPages > 0}
				<span class="text-gray-400">| Page {currentPage} / {totalPages}</span>
			{/if}
		</div>
		<div class="flex items-center gap-2">
			<button
				onclick={zoomOut}
				class="px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm"
				title="Zoom -"
			>
				<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
					<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 12H4" />
				</svg>
			</button>
			<span class="text-sm w-16 text-center">{Math.round(scale * 100)}%</span>
			<button
				onclick={zoomIn}
				class="px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm"
				title="Zoom +"
			>
				<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
					<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
				</svg>
			</button>
			<button
				onclick={toggleFullscreen}
				class="px-2 py-1 bg-gray-700 hover:bg-gray-600 rounded text-sm ml-2"
				title={isFullscreen ? 'Quitter plein écran' : 'Plein écran'}
			>
				{#if isFullscreen}
					<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25" />
					</svg>
				{:else}
					<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
						<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3.75 3.75v4.5m0-4.5h4.5m-4.5 0L9 9M3.75 20.25v-4.5m0 4.5h4.5m-4.5 0L9 15M20.25 3.75h-4.5m4.5 0v4.5m0-4.5L15 9m5.25 11.25h-4.5m4.5 0v-4.5m0 4.5L15 15" />
					</svg>
				{/if}
			</button>
		</div>
	</div>

	<div class="flex-1 overflow-auto bg-gray-800 flex items-start justify-center p-4">
		{#if loading}
			<div class="text-white">
				<div class="animate-spin rounded-full h-12 w-12 border-b-2 border-white mx-auto mb-4"></div>
				<p>Chargement du PDF...</p>
			</div>
		{:else if error}
			<div class="text-red-400 text-center">
				<p class="text-xl mb-2">⚠️</p>
				<p>{error}</p>
			</div>
		{:else}
			<canvas bind:this={canvas} class="shadow-2xl"></canvas>
		{/if}
	</div>

	<div class="bg-ohmj-dark text-white px-4 py-3 flex items-center justify-center gap-4 border-t border-gray-700">
		<button
			onclick={prevPage}
			disabled={currentPage <= 1}
			class="px-4 py-2 bg-ohmj-primary hover:bg-ohmj-secondary disabled:opacity-50 disabled:cursor-not-allowed rounded transition-colors"
		>
			◀ Précédent
		</button>
		
		<div class="flex gap-1">
			{#each Array(Math.min(5, totalPages)) as _, i}
				{@const pageNum = Math.max(1, Math.min(currentPage - 2, totalPages - 4)) + i}
				{#if pageNum <= totalPages}
					<button
						onclick={() => { currentPage = pageNum; renderPage(pageNum); }}
						class="w-8 h-8 rounded {currentPage === pageNum ? 'bg-ohmj-secondary text-ohmj-dark font-bold' : 'bg-gray-700 hover:bg-gray-600'}"
					>
						{pageNum}
					</button>
				{/if}
			{/each}
		</div>

		<button
			onclick={nextPage}
			disabled={currentPage >= totalPages}
			class="px-4 py-2 bg-ohmj-primary hover:bg-ohmj-secondary disabled:opacity-50 disabled:cursor-not-allowed rounded transition-colors"
		>
			Suivant ▶
		</button>
	</div>
</div>
