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

	interface Props {
		/** Current loudness analysis (null if not yet analyzed) */
		loudness: LoudnessInfo | null;
		/** Detected silence regions */
		silenceRegions: SilenceRegion[];
		/** Audio info */
		audioInfo: AudioInfo | null;
		/** Whether analysis is running */
		analyzing: boolean;
		/** Current EDL operations */
		operations: EdlOperation[];
		/** Active region from waveform selection */
		activeRegion: { start: number; end: number } | null;
		/** Callbacks */
		onanalyze: () => void;
		oncut: () => void;
		onaddop: (op: EdlOperation) => void;
		onremoveop: (index: number) => void;
		onrender: () => void;
		onundo: () => void;
		ontrimsilence: () => void;
	}

	let {
		loudness,
		silenceRegions,
		audioInfo,
		analyzing,
		operations,
		activeRegion,
		onanalyze,
		oncut,
		onaddop,
		onremoveop,
		onrender,
		onundo,
		ontrimsilence,
	}: Props = $props();

	// Tool settings
	let normTarget = $state(-16);
	let silenceThreshold = $state(-30);
	let silenceMinMs = $state(500);
	let fadeInMs = $state(1000);
	let fadeOutMs = $state(2000);
	let noiseStrength = $state(-25);
	let eqLow = $state(0);
	let eqMid = $state(0);
	let eqHigh = $state(0);
	let compThreshold = $state(-20);
	let compRatio = $state(4);

	function opLabel(op: EdlOperation): string {
		switch (op.type) {
			case 'cut': return `Klipp ${fmtMs(op.start_ms as number)}-${fmtMs(op.end_ms as number)}`;
			case 'normalize': return `Normaliser (${op.target_lufs} LUFS)`;
			case 'trim_silence': return `Trim stillhet (${op.threshold_db}dB)`;
			case 'fade_in': return `Fade inn (${op.duration_ms}ms)`;
			case 'fade_out': return `Fade ut (${op.duration_ms}ms)`;
			case 'noise_reduction': return `Noise reduction (${op.strength_db}dB)`;
			case 'equalizer': return `EQ (L:${op.low_gain} M:${op.mid_gain} H:${op.high_gain})`;
			case 'compressor': return `Kompressor (${op.threshold_db}dB, ${op.ratio}:1)`;
			default: return op.type;
		}
	}

	function fmtMs(ms: number): string {
		const sec = ms / 1000;
		const m = Math.floor(sec / 60);
		const s = Math.floor(sec % 60);
		return `${m}:${s.toString().padStart(2, '0')}`;
	}
</script>

<div class="flex flex-col gap-4 rounded-lg border border-gray-200 bg-white p-4">
	<!-- Analyse -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Analyse</h3>
		<button
			onclick={onanalyze}
			disabled={analyzing}
			class="w-full rounded bg-gray-100 px-3 py-2 text-sm transition-colors hover:bg-gray-200 disabled:opacity-50"
		>
			{analyzing ? 'Analyserer...' : 'Analyser lydfil'}
		</button>

		{#if loudness}
			<div class="mt-2 grid grid-cols-2 gap-1 text-xs text-gray-500">
				<span>Loudness:</span>
				<span class="font-mono">{loudness.input_i.toFixed(1)} LUFS</span>
				<span>True Peak:</span>
				<span class="font-mono">{loudness.input_tp.toFixed(1)} dBTP</span>
				<span>LRA:</span>
				<span class="font-mono">{loudness.input_lra.toFixed(1)} LU</span>
			</div>
		{/if}

		{#if audioInfo}
			<div class="mt-2 grid grid-cols-2 gap-1 text-xs text-gray-500">
				<span>Varighet:</span>
				<span class="font-mono">{fmtMs(audioInfo.duration_ms)}</span>
				<span>Format:</span>
				<span class="font-mono">{audioInfo.codec} / {audioInfo.sample_rate}Hz</span>
				<span>Kanaler:</span>
				<span class="font-mono">{audioInfo.channels}</span>
			</div>
		{/if}

		{#if silenceRegions.length > 0}
			<p class="mt-2 text-xs text-gray-400">
				{silenceRegions.length} stille regioner funnet
			</p>
		{/if}
	</section>

	<!-- Klipp -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Klipp</h3>
		<button
			onclick={oncut}
			disabled={!activeRegion}
			class="w-full rounded bg-red-50 px-3 py-2 text-sm text-red-700 transition-colors hover:bg-red-100 disabled:opacity-50"
		>
			{activeRegion ? 'Klipp markert region' : 'Marker en region forst'}
		</button>
	</section>

	<!-- Silence trimming -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Trim stillhet</h3>
		<div class="flex items-center gap-2">
			<label class="text-xs text-gray-500">Terskel</label>
			<input type="number" bind:value={silenceThreshold} class="w-16 rounded border px-1 py-0.5 text-xs" step="5" min="-96" max="0" />
			<span class="text-xs text-gray-400">dB</span>
		</div>
		<div class="mt-1 flex items-center gap-2">
			<label class="text-xs text-gray-500">Min varighet</label>
			<input type="number" bind:value={silenceMinMs} class="w-16 rounded border px-1 py-0.5 text-xs" step="100" min="1" max="60000" />
			<span class="text-xs text-gray-400">ms</span>
		</div>
		<button
			onclick={ontrimsilence}
			class="mt-2 w-full rounded bg-gray-100 px-3 py-2 text-sm transition-colors hover:bg-gray-200"
		>
			Trim all stillhet
		</button>
	</section>

	<!-- Normalisering -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Normaliser loudness</h3>
		<div class="flex items-center gap-2">
			<label class="text-xs text-gray-500">Mal</label>
			<input type="number" bind:value={normTarget} class="w-16 rounded border px-1 py-0.5 text-xs" step="1" min="-70" max="0" />
			<span class="text-xs text-gray-400">LUFS</span>
		</div>
		<button
			onclick={() => onaddop({ type: 'normalize', target_lufs: normTarget })}
			class="mt-2 w-full rounded bg-gray-100 px-3 py-2 text-sm transition-colors hover:bg-gray-200"
		>
			Legg til normalisering
		</button>
	</section>

	<!-- Fades -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Fades</h3>
		<div class="flex gap-2">
			<div class="flex-1">
				<label class="text-xs text-gray-500">Fade inn</label>
				<div class="flex items-center gap-1">
					<input type="number" bind:value={fadeInMs} class="w-16 rounded border px-1 py-0.5 text-xs" step="500" min="1" max="300000" />
					<span class="text-xs text-gray-400">ms</span>
				</div>
				<button
					onclick={() => onaddop({ type: 'fade_in', duration_ms: fadeInMs })}
					class="mt-1 w-full rounded bg-gray-100 px-2 py-1 text-xs transition-colors hover:bg-gray-200"
				>
					+ Fade inn
				</button>
			</div>
			<div class="flex-1">
				<label class="text-xs text-gray-500">Fade ut</label>
				<div class="flex items-center gap-1">
					<input type="number" bind:value={fadeOutMs} class="w-16 rounded border px-1 py-0.5 text-xs" step="500" min="1" max="300000" />
					<span class="text-xs text-gray-400">ms</span>
				</div>
				<button
					onclick={() => onaddop({ type: 'fade_out', duration_ms: fadeOutMs })}
					class="mt-1 w-full rounded bg-gray-100 px-2 py-1 text-xs transition-colors hover:bg-gray-200"
				>
					+ Fade ut
				</button>
			</div>
		</div>
	</section>

	<!-- Noise reduction -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Noise reduction</h3>
		<div class="flex items-center gap-2">
			<label class="text-xs text-gray-500">Styrke</label>
			<input type="range" min="-50" max="0" bind:value={noiseStrength} class="flex-1" />
			<span class="w-10 text-right font-mono text-xs text-gray-500">{noiseStrength}dB</span>
		</div>
		<button
			onclick={() => onaddop({ type: 'noise_reduction', strength_db: noiseStrength })}
			class="mt-2 w-full rounded bg-gray-100 px-3 py-2 text-sm transition-colors hover:bg-gray-200"
		>
			Legg til noise reduction
		</button>
	</section>

	<!-- EQ -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Equalizer</h3>
		<div class="space-y-1">
			<div class="flex items-center gap-2">
				<label class="w-8 text-xs text-gray-500">Lav</label>
				<input type="range" min="-12" max="12" step="0.5" bind:value={eqLow} class="flex-1" />
				<span class="w-10 text-right font-mono text-xs text-gray-500">{eqLow}dB</span>
			</div>
			<div class="flex items-center gap-2">
				<label class="w-8 text-xs text-gray-500">Mid</label>
				<input type="range" min="-12" max="12" step="0.5" bind:value={eqMid} class="flex-1" />
				<span class="w-10 text-right font-mono text-xs text-gray-500">{eqMid}dB</span>
			</div>
			<div class="flex items-center gap-2">
				<label class="w-8 text-xs text-gray-500">Hoy</label>
				<input type="range" min="-12" max="12" step="0.5" bind:value={eqHigh} class="flex-1" />
				<span class="w-10 text-right font-mono text-xs text-gray-500">{eqHigh}dB</span>
			</div>
		</div>
		<button
			onclick={() => onaddop({ type: 'equalizer', low_gain: eqLow, mid_gain: eqMid, high_gain: eqHigh })}
			class="mt-2 w-full rounded bg-gray-100 px-3 py-2 text-sm transition-colors hover:bg-gray-200"
		>
			Legg til EQ
		</button>
	</section>

	<!-- Compressor -->
	<section>
		<h3 class="mb-2 text-sm font-semibold text-gray-700">Kompressor</h3>
		<div class="space-y-1">
			<div class="flex items-center gap-2">
				<label class="text-xs text-gray-500">Terskel</label>
				<input type="number" bind:value={compThreshold} class="w-16 rounded border px-1 py-0.5 text-xs" step="1" min="-60" max="0" />
				<span class="text-xs text-gray-400">dB</span>
			</div>
			<div class="flex items-center gap-2">
				<label class="text-xs text-gray-500">Ratio</label>
				<input type="number" bind:value={compRatio} class="w-16 rounded border px-1 py-0.5 text-xs" step="0.5" min="1" max="20" />
				<span class="text-xs text-gray-400">:1</span>
			</div>
		</div>
		<button
			onclick={() => onaddop({ type: 'compressor', threshold_db: compThreshold, ratio: compRatio })}
			class="mt-2 w-full rounded bg-gray-100 px-3 py-2 text-sm transition-colors hover:bg-gray-200"
		>
			Legg til kompressor
		</button>
	</section>

	<!-- Operasjonsliste -->
	{#if operations.length > 0}
		<section>
			<div class="flex items-center justify-between">
				<h3 class="text-sm font-semibold text-gray-700">Operasjoner ({operations.length})</h3>
				<button
					onclick={onundo}
					class="text-xs text-gray-400 hover:text-gray-600"
				>
					Angre siste
				</button>
			</div>
			<ul class="mt-1 space-y-1">
				{#each operations as op, i}
					<li class="flex items-center justify-between rounded bg-gray-50 px-2 py-1">
						<span class="text-xs text-gray-600">{i + 1}. {opLabel(op)}</span>
						<button
							onclick={() => onremoveop(i)}
							class="text-xs text-red-400 hover:text-red-600"
						>
							x
						</button>
					</li>
				{/each}
			</ul>
		</section>
	{/if}

	<!-- Render -->
	<button
		onclick={onrender}
		disabled={operations.length === 0}
		class="w-full rounded bg-blue-600 px-4 py-2.5 text-sm font-medium text-white transition-colors hover:bg-blue-700 disabled:opacity-50"
	>
		Render ({operations.length} operasjoner)
	</button>
</div>
