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

	interface Props {
		operations: EdlOperation[];
		rendering: boolean;
		jobId: string | null;
		resultNodeId: string | null;
		errorMessage: string | null;
		onconfirm: (format: string) => void;
		onclose: () => void;
	}

	let { operations, rendering, jobId, resultNodeId, errorMessage, onconfirm, onclose }: Props = $props();

	let format = $state('mp3');

	/** Trekk ut brukerlesbar FFmpeg-feil fra stderr-dump. */
	function formatFfmpegError(raw: string): { summary: string; detail: string | null } {
		// Fjern "ffmpeg feilet: "-prefiks fra maskinrommet
		let cleaned = raw.replace(/^ffmpeg feilet:\s*/i, '');

		// Finn siste linje som inneholder en feilmelding (typisk FFmpeg-mønster)
		const lines = cleaned.split('\n').filter((l) => l.trim());
		const errorLine = lines.findLast(
			(l) =>
				/error|invalid|no such|not found|unknown|unsupported|conversion failed/i.test(l) &&
				!/^frame=/i.test(l)
		);

		const summary = errorLine?.trim() || lines.at(-1)?.trim() || 'Ukjent FFmpeg-feil';
		const detail = lines.length > 1 ? cleaned.trim() : null;

		return { summary, detail };
	}
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
	class="fixed inset-0 z-50 flex items-center justify-center bg-black/50"
	onkeydown={(e) => { if (e.key === 'Escape') onclose(); }}
>
	<!-- svelte-ignore a11y_click_events_have_key_events -->
	<div
		class="w-full max-w-md rounded-lg bg-white p-6 shadow-xl"
		onclick={(e) => e.stopPropagation()}
	>
		<h2 class="mb-4 text-lg font-semibold text-gray-800">Render lyd</h2>

		{#if errorMessage}
			<!-- Error -->
			{@const parsed = formatFfmpegError(errorMessage)}
			<div class="rounded bg-red-50 p-4">
				<div class="flex items-start gap-2">
					<svg class="mt-0.5 h-5 w-5 shrink-0 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
						<path stroke-linecap="round" stroke-linejoin="round" d="M12 9v2m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
					</svg>
					<div class="flex-1 min-w-0">
						<p class="text-sm font-medium text-red-800">Rendering feilet</p>
						<p class="mt-1 text-sm text-red-700">{parsed.summary}</p>
						{#if parsed.detail}
							<details class="mt-2">
								<summary class="cursor-pointer text-xs text-red-500 hover:text-red-700">Vis full feilmelding</summary>
								<pre class="mt-1 max-h-48 overflow-auto whitespace-pre-wrap break-all rounded bg-red-100 p-2 text-xs text-red-800 font-mono">{parsed.detail}</pre>
							</details>
						{/if}
					</div>
				</div>
			</div>
			<button
				onclick={onclose}
				class="mt-4 w-full rounded bg-gray-100 px-4 py-2 text-sm hover:bg-gray-200"
			>
				Lukk
			</button>
		{:else if resultNodeId}
			<!-- Done -->
			<div class="rounded bg-green-50 p-4 text-center">
				<p class="text-sm text-green-700">Rendering fullfort!</p>
				<p class="mt-1 text-xs text-green-600">Node: {resultNodeId}</p>
			</div>
			<button
				onclick={onclose}
				class="mt-4 w-full rounded bg-gray-100 px-4 py-2 text-sm hover:bg-gray-200"
			>
				Lukk
			</button>
		{:else if rendering}
			<!-- In progress -->
			<div class="flex flex-col items-center gap-3 py-4">
				<svg class="h-8 w-8 animate-spin text-blue-500" fill="none" viewBox="0 0 24 24">
					<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
					<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path>
				</svg>
				<p class="text-sm text-gray-600">Rendrer lyd...</p>
				{#if jobId}
					<p class="text-xs text-gray-400">Jobb: {jobId.slice(0, 8)}...</p>
				{/if}
			</div>
		{:else}
			<!-- Config -->
			<div class="space-y-3">
				<div>
					<label class="text-sm text-gray-600">Format</label>
					<select bind:value={format} class="mt-1 w-full rounded border px-2 py-1.5 text-sm">
						<option value="mp3">MP3 (standard)</option>
						<option value="wav">WAV (ukomprimert)</option>
						<option value="flac">FLAC (lossless)</option>
						<option value="ogg">OGG Vorbis</option>
					</select>
				</div>

				<div class="rounded bg-gray-50 p-3">
					<p class="text-xs font-medium text-gray-500">Operasjoner ({operations.length})</p>
					<ul class="mt-1 space-y-0.5">
						{#each operations as op, i}
							<li class="text-xs text-gray-600">{i + 1}. {op.type}</li>
						{/each}
					</ul>
				</div>
			</div>

			<div class="mt-4 flex gap-2">
				<button
					onclick={onclose}
					class="flex-1 rounded bg-gray-100 px-4 py-2 text-sm hover:bg-gray-200"
				>
					Avbryt
				</button>
				<button
					onclick={() => onconfirm(format)}
					class="flex-1 rounded bg-blue-600 px-4 py-2 text-sm font-medium text-white hover:bg-blue-700"
				>
					Render
				</button>
			</div>
		{/if}
	</div>
</div>
