<script module lang="ts">
	import type { Track } from "$lib/player/types";

	export type GlobalPlayerNowPlaying = Track | null;

	export type QueueDisplayItem = {
		track: Track;
		queueIndex: number;
		isCurrent: boolean;
	};

	export type TrackLabel = {
		primary: string;
		secondary: string | null;
	};
</script>

<script lang="ts">
	import { browser } from "$app/environment";
	import { onDestroy, onMount, tick } from "svelte";
	import {
		clearQueue,
		jumpToTrack,
		next,
		nowPlayingLabel,
		prev,
		removeTrack,
		reorderTrackById,
		schedulePersistNow,
		setUiOpen,
		setVolume,
		subscribe,
		toggleShuffle,
		toggleUiOpen,
		toggleWrap,
		type PlayerSnapshot,
	} from "$lib/player/player.svelte";
	import { createMediaSessionBindings } from "$lib/player/media-session";
	import Portal from "$lib/components/util/Portal.svelte";
	import * as AlertDialog from "$lib/components/ui/alert-dialog";

	import {
		ChevronsUpDown,
		ListX,
		Pause as PauseIcon,
		PanelRightClose,
		PanelRightOpen,
		Play as PlayIcon,
		Repeat,
		Shuffle,
		SkipBack,
		SkipForward,
		Trash2,
		Volume2,
		X,
		GripVertical,
	} from "@lucide/svelte";

	const iconClass = "icon-btn";

	let audioEl: HTMLAudioElement | null = null;

	let isPlaying = $state(false);
	let currentTime = $state(0);
	let duration = $state(0);

	// local UI derived from viewport; not persisted
	let isMobile = $state(false);

	// IMPORTANT: Do not read `window` during SSR. Start with a safe snapshot and let
	// the player module + subscription populate the real values on mount.
	let snap = $state<PlayerSnapshot>({
		queue: [],
		currentIndex: null,
		currentTrack: null,
		shuffleEnabled: false,
		wrapEnabled: false,
		order: [],
		history: [],
		cursor: 0,
		volume: 1,
		uiOpen: false,
	});

	let unsubscribe: (() => void) | null = null;

	// Track breakpoint transitions so we can auto open/close on crossing:
	// - desktop -> mobile: auto close
	// - mobile -> desktop: auto open
	let prevIsMobile: boolean | null = $state(null);

	function updateIsMobile() {
		const nextIsMobile =
			window.matchMedia?.("(max-width: 1023px)")?.matches ?? false;

		// Update local derived flag
		isMobile = nextIsMobile;

		// On transitions, sync player UI open state
		if (prevIsMobile !== null && prevIsMobile !== nextIsMobile) {
			setUiOpen(!nextIsMobile);
		}

		prevIsMobile = nextIsMobile;
	}

	async function waitForEvent(el: HTMLMediaElement, eventName: string) {
		await new Promise<void>((resolve) => {
			const onEvent = () => {
				el.removeEventListener(eventName, onEvent);
				resolve();
			};
			el.addEventListener(eventName, onEvent, { once: true });
		});
	}

	async function syncAndAutoplay() {
		await tick();
		const el = audioEl;
		if (!el) return;

		// Centralized logic to sync and play the current track.
		const track = snap.currentTrack;
		if (!track) {
			if (el.src) {
				el.removeAttribute("src");
				el.load();
			}
			return;
		}

		const desiredSrc = track.src;
		const desiredAbs = new URL(desiredSrc, window.location.href).href;
		const srcChanged = el.src !== desiredAbs;

		if (srcChanged) {
			el.src = desiredSrc;
			el.load();
		}

		el.volume = snap.volume;

		// If src changed, we MUST wait until the browser says it's ready.
		if (srcChanged || el.readyState < 3) {
			try {
				await Promise.race([
					waitForEvent(el, "canplay"),
					// Add a timeout to prevent getting stuck forever
					new Promise((_, reject) =>
						setTimeout(() => reject(new Error("canplay timeout")), 8000),
					),
				]);
			} catch (e) {
				console.error("Audio load failed or timed out", e);
				return; // Don't try to play if loading failed
			}
		}

		// Now, try to play.
		try {
			await el.play();
		} catch (e) {
			console.warn("Autoplay was prevented.", e);
			// isPlaying state will be updated by onAudioPause handler.
		}
	}

	// Media Session bindings
	const media = createMediaSessionBindings({
		play: () => void audioEl?.play(),
		pause: () => void audioEl?.pause(),
		next: () => {
			next();
			void syncAndAutoplay();
		},
		prev: () => {
			prev(currentTime);
			void syncAndAutoplay();
		},
		seekTo: (t) => {
			if (!audioEl) return;
			audioEl.currentTime = Math.max(0, t);
		},
		seekBy: (d) => {
			if (!audioEl) return;
			audioEl.currentTime = Math.max(0, audioEl.currentTime + d);
		},
	});

	// Scrubber is now driven by `bind:currentTime` on the <audio> element and
	// `bind:value={currentTime}` on the sliders, so we don't need explicit handlers.

	function onAudioPlay() {
		isPlaying = true;
		media.setPlaybackState("playing");
	}
	function onAudioPause() {
		isPlaying = false;
		media.setPlaybackState("paused");
	}
	function onAudioTimeUpdate() {
		// `currentTime` is synced via `bind:currentTime` on <audio>.
		// Keep Media Session position state updated whenever we get timeupdate.
		if (!audioEl) return;

		media.updatePositionState({
			duration,
			position: currentTime,
			playbackRate: audioEl.playbackRate || 1,
		});
	}
	function onAudioLoadedMetadata() {
		// `duration` is synced via `bind:duration` on <audio>.
		if (!audioEl) return;

		media.updatePositionState({
			duration,
			position: currentTime,
			playbackRate: audioEl.playbackRate || 1,
		});
	}
	function onAudioEnded() {
		next();
		void syncAndAutoplay();
	}

	let clearQueueDialogOpen = $state(false);

	// --- Drag & drop reorder ---
	// Important: in shuffle mode, the UI is showing `queueDisplay` (shuffled traversal),
	// so we must compute targets against that order (not `snap.queue`).
	//
	// We still reorder by track.id (annSongId). The player module applies shuffle-aware
	// semantics (linear: reorder queue; shuffle: reorder upcoming play order).
	let dragId = $state<number | null>(null);
	let dragOverId = $state<number | null>(null);
	let dragOverEdge = $state<"top" | "bottom" | null>(null);

	function onDragStart(trackId: number, e: DragEvent) {
		dragId = trackId;
		dragOverId = null;
		dragOverEdge = null;

		try {
			e.dataTransfer?.setData("text/plain", String(trackId));
			e.dataTransfer!.effectAllowed = "move";
		} catch {
			// ignore
		}
	}

	function edgeFromPointer(e: DragEvent) {
		const el = e.currentTarget as HTMLElement | null;
		if (!el) return "bottom" as const;

		const rect = el.getBoundingClientRect();
		const mid = rect.top + rect.height / 2;
		return e.clientY < mid ? ("top" as const) : ("bottom" as const);
	}

	function onDragOver(trackId: number, e: DragEvent) {
		e.preventDefault();
		dragOverId = trackId;
		dragOverEdge = edgeFromPointer(e);

		try {
			e.dataTransfer!.dropEffect = "move";
		} catch {
			// ignore
		}
	}

	function onDrop(targetTrackId: number, e: DragEvent) {
		e.preventDefault();

		let sourceId = dragId;
		if (sourceId == null) {
			const raw = e.dataTransfer?.getData("text/plain");
			const parsed = raw ? Number(raw) : NaN;
			if (Number.isFinite(parsed)) sourceId = parsed;
		}

		if (sourceId == null) {
			dragId = null;
			dragOverId = null;
			dragOverEdge = null;
			return;
		}

		// Work in DISPLAY ORDER, then map to queue indices.
		const display = queueDisplay;
		const fromItem = display.find((it) => it.track.id === sourceId);
		const targetItem = display.find((it) => it.track.id === targetTrackId);

		if (!fromItem || !targetItem) {
			dragId = null;
			dragOverId = null;
			dragOverEdge = null;
			return;
		}

		const fromQueueIndex = fromItem.queueIndex;
		const targetQueueIndex = targetItem.queueIndex;

		// If dropping onto itself, no-op
		if (sourceId === targetTrackId) {
			dragId = null;
			dragOverId = null;
			dragOverEdge = null;
			return;
		}

		const edge = dragOverEdge ?? edgeFromPointer(e);

		// Compute insertion slot in display order (0..display.length)
		const fromPos = display.findIndex((it) => it.track.id === sourceId);
		const targetPos = display.findIndex((it) => it.track.id === targetTrackId);

		if (fromPos === -1 || targetPos === -1) {
			dragId = null;
			dragOverId = null;
			dragOverEdge = null;
			return;
		}

		let insertPos = edge === "top" ? targetPos : targetPos + 1;
		insertPos = Math.max(0, Math.min(display.length, insertPos));

		// Convert insert slot (0..len) into a destination position (0..len-1)
		// accounting for removal shift.
		let toPos: number;
		if (insertPos <= fromPos) toPos = insertPos;
		else toPos = insertPos - 1;

		if (toPos === fromPos) {
			dragId = null;
			dragOverId = null;
			dragOverEdge = null;
			return;
		}

		// Map destination display position back to a queue index:
		// - If inserting at the end, use the last item's queueIndex (the module will interpret appropriately)
		// - Otherwise, use the queueIndex of the item currently at `toPos`
		const anchor =
			toPos >= display.length ? display[display.length - 1] : display[toPos];
		const anchorQueueIndex = anchor?.queueIndex ?? targetQueueIndex;

		reorderTrackById(sourceId, anchorQueueIndex);

		dragId = null;
		dragOverId = null;
		dragOverEdge = null;
	}

	function onDragEnd() {
		dragId = null;
		dragOverId = null;
		dragOverEdge = null;
	}

	function draggableHint(trackId: number) {
		if (dragId == null) return "";
		if (dragId === trackId) return "opacity-70";
		if (dragOverId === trackId) return "ring-2 ring-primary/40 ring-offset-0";
		return "";
	}

	function dropIndicatorClass(trackId: number) {
		if (dragOverId !== trackId) return "";
		if (dragOverEdge === "top") return "border-t-2 border-t-primary/50";
		if (dragOverEdge === "bottom") return "border-b-2 border-b-primary/50";
		return "";
	}

	function formatTime(seconds: number) {
		if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
		const s = Math.floor(seconds);
		const m = Math.floor(s / 60);
		const r = s % 60;
		return `${m}:${String(r).padStart(2, "0")}`;
	}

	function typeNumberLabel(t: Track) {
		const type = t.type;
		const n = Number(t.number ?? 0);

		let typeLabel: string | null = null;
		if (typeof type === "number") {
			if (type === 1) typeLabel = "OP";
			else if (type === 2) typeLabel = "ED";
			else if (type === 3) typeLabel = "INS";
			else typeLabel = `T${type}`;
		}

		if (!typeLabel) return null;
		return `${typeLabel}${n ? String(n) : ""}`;
	}

	function animeLabel(t: Track) {
		return ((t.animeName ?? t.album ?? "").trim() || "Unknown anime").trim();
	}

	function trackLabel(t: Track): TrackLabel {
		const title = (t.title ?? "").trim() || "Unknown title";
		const artist = (t.artist ?? "").trim() || "Unknown Artist";
		const primary = `${title} — ${artist}`;

		const anime = (t.animeName ?? t.album ?? "").trim();
		const typeNo = typeNumberLabel(t);

		const secondary = [anime, typeNo].filter(Boolean).join(" • ") || null;

		return { primary, secondary };
	}

	function computeQueueDisplay(): QueueDisplayItem[] {
		const q = snap.queue;

		if (q.length === 0) return [];

		const current = snap.currentIndex;

		// Non-shuffle: display stable queue order.
		if (!snap.shuffleEnabled) {
			return q.map((track, queueIndex) => ({
				track,
				queueIndex,
				isCurrent: current === queueIndex,
			}));
		}

		// Shuffle: display play order (history up to cursor + future order).
		// This prevents the UI's "current position" from appearing to jump around.
		//
		// Invariants we try to preserve:
		// - Past (history[0..cursor]) stays in the same order.
		// - Current item is history[cursor] when available, otherwise currentIndex.
		// - Future comes from `order` (already excludes visited indices).
		const out: QueueDisplayItem[] = [];
		const seen = new Set<number>();

		const pushIndex = (queueIndex: number) => {
			if (!Number.isInteger(queueIndex)) return;
			if (queueIndex < 0 || queueIndex >= q.length) return;
			if (seen.has(queueIndex)) return;
			seen.add(queueIndex);

			out.push({
				track: q[queueIndex]!,
				queueIndex,
				isCurrent: current === queueIndex,
			});
		};

		// Past + current
		const hist = snap.history;
		const cursor = snap.cursor;

		for (let i = 0; i < hist.length; i += 1) {
			// Only show "past" up through current cursor; the rest would be "future via history"
			// and is confusing to duplicate (future is represented by `order`).
			if (i > cursor) break;
			pushIndex(hist[i]!);
		}

		// If history is empty or cursor doesn't match currentIndex, ensure currentIndex is shown.
		if (current != null) pushIndex(current);

		// Future
		for (const i of snap.order) pushIndex(i);

		// Any remaining items (not yet visited nor scheduled) go at the end (rare but possible after edits).
		for (let i = 0; i < q.length; i += 1) pushIndex(i);

		return out;
	}

	const queueDisplay = $derived(computeQueueDisplay());

	const canPrev = $derived(
		snap.queue.length > 0 &&
			snap.currentIndex != null &&
			(snap.wrapEnabled || snap.currentIndex > 0 || snap.shuffleEnabled),
	);
	const canNext = $derived(
		snap.queue.length > 0 &&
			(snap.wrapEnabled ||
				(snap.currentIndex != null &&
					snap.currentIndex < snap.queue.length - 1) ||
				snap.shuffleEnabled),
	);

	const uiVisible = $derived(isMobile ? snap.uiOpen : true);

	$effect(() => {
		media.setTrack(snap.currentTrack);
		schedulePersistNow();

		// When track changes for any reason, ensure volume is correct.
		if (audioEl) {
			audioEl.volume = snap.volume;
		}

		// If there's no track, ensure audio element is reset
		if (!snap.currentTrack && audioEl && audioEl.src) {
			audioEl.removeAttribute("src");
			audioEl.load();
		}
	});

	onMount(() => {
		updateIsMobile();
		if (browser) {
			window.addEventListener("resize", updateIsMobile);
		}

		// Subscribe to player changes instead of polling
		unsubscribe = subscribe((s) => {
			snap = s;
		});

		// Listen for play requests dispatched from anywhere (e.g. SongEntry buttons).
		// This ensures "Play" behaves like Next/Prev: it will reliably sync the new
		// source and start playback.
		if (browser) {
			const onAutoplayRequest = () => {
				void syncAndAutoplay();
			};
			window.addEventListener("amqtrain:player:autoplay", onAutoplayRequest);

			return () => {
				window.removeEventListener(
					"amqtrain:player:autoplay",
					onAutoplayRequest,
				);
			};
		}

		media.setPlaybackState("paused");
	});

	onDestroy(() => {
		if (browser) {
			window.removeEventListener("resize", updateIsMobile);
		}
		if (unsubscribe) unsubscribe();
		media.destroy();
	});
</script>

<svelte:head></svelte:head>

<!-- Mobile UI is portaled to document.body so the GlobalPlayer can be mounted
     in the desktop sidebar column while still showing the mobile overlay.
     Hidden on lg+ via CSS. -->
<Portal>
	<div
		class="lg:hidden fixed bottom-0 left-0 right-0 z-50 border-t bg-background/95 backdrop-blur shadow-2xl"
	>
		<div class="mx-auto flex max-w-4xl items-center gap-2 px-3 py-2">
			<button
				class="btn-icon"
				type="button"
				onclick={() => toggleUiOpen()}
				aria-label={snap.uiOpen ? "Close player" : "Open player"}
				title={snap.uiOpen ? "Close player" : "Open player"}
			>
				{#if snap.uiOpen}
					<X class={iconClass} />
				{:else}
					<ChevronsUpDown class={iconClass} />
				{/if}
			</button>

			<div
				class="min-w-0 flex-1"
				role="button"
				tabindex="0"
				aria-label={snap.uiOpen ? "Close player" : "Open player"}
				onclick={(e) => {
					const t = e.target as HTMLElement | null;
					// Only toggle when tapping the track info area. Avoid toggling from
					// the button zones (above/below/side) by not attaching handlers to the
					// whole bar.
					if (t?.closest("button,input,label,a")) return;
					toggleUiOpen();
				}}
				onkeydown={(e) => {
					if (e.key !== "Enter" && e.key !== " ") return;
					const t = e.target as HTMLElement | null;
					if (t?.closest("button,input,label,a")) return;
					e.preventDefault();
					toggleUiOpen();
				}}
			>
				{#if snap.currentTrack}
					<div class="flex flex-wrap items-baseline gap-x-2 gap-y-1">
						{#if typeNumberLabel(snap.currentTrack)}
							<span
								class="rounded bg-muted px-2 py-0.5 text-sm text-muted-foreground"
							>
								{typeNumberLabel(snap.currentTrack)}
							</span>
						{/if}
						<span>
							{(
								snap.currentTrack.animeName ??
								snap.currentTrack.album ??
								""
							).trim()}
						</span>
					</div>

					<div class="mt-1 text-foreground/80">
						{(snap.currentTrack.title ?? "").trim() || "Unknown title"}
						<span class="text-sm text-muted-foreground">
							— {(snap.currentTrack.artist ?? "").trim() || "Unknown Artist"}
						</span>
					</div>
				{:else}
					<div class="truncate text-sm font-medium">{nowPlayingLabel()}</div>
				{/if}

				<div class="text-xs text-muted-foreground">
					{formatTime(currentTime)} / {formatTime(duration)}
				</div>

				<label class="mt-2 block">
					<span class="sr-only">Seek</span>
					<input
						class="w-full"
						type="range"
						min="0"
						max={Math.max(0, duration)}
						step="0.1"
						bind:value={currentTime}
						disabled={!snap.currentTrack || duration <= 0}
					/>
				</label>
			</div>

			<button
				class="btn-icon"
				type="button"
				disabled={!canPrev}
				aria-label="Previous"
				title="Previous"
				onclick={() => {
					prev(currentTime);
					void syncAndAutoplay();
				}}
			>
				<SkipBack class={iconClass} />
			</button>

			<button
				class="btn-icon"
				type="button"
				aria-label={isPlaying ? "Pause" : "Play"}
				title={isPlaying ? "Pause" : "Play"}
				onclick={() => {
					if (!audioEl || !snap.currentTrack) return;

					// If src is not set, it's an initial play action.
					// Delegate to syncAndAutoplay to ensure src is set and loaded.
					if (!audioEl.src) {
						void syncAndAutoplay();
					} else {
						if (audioEl.paused) void audioEl.play();
						else audioEl.pause();
					}
				}}
				disabled={!snap.currentTrack}
			>
				{#if isPlaying}
					<PauseIcon class={iconClass} />
				{:else}
					<PlayIcon class={iconClass} />
				{/if}
			</button>

			<button
				class="btn-icon"
				type="button"
				disabled={!canNext}
				aria-label="Next"
				title="Next"
				onclick={() => {
					next();
					void syncAndAutoplay();
				}}
			>
				<SkipForward class={iconClass} />
			</button>
		</div>

		{#if snap.uiOpen}
			<div class="h-[65dvh] overflow-hidden border-t">
				<div class="mx-auto flex h-full max-w-4xl flex-col px-3 py-3">
					<!-- Controls stay visible while the queue scrolls -->
					<div class="flex flex-wrap items-center gap-2 pb-3">
						<button
							class={[
								"btn-icon transition-colors",
								snap.shuffleEnabled &&
									"border-primary/40 bg-primary/10 text-primary",
							]
								.filter(Boolean)
								.join(" ")}
							type="button"
							onclick={() => toggleShuffle()}
							aria-label={snap.shuffleEnabled ? "Shuffle on" : "Shuffle off"}
							title={snap.shuffleEnabled ? "Shuffle on" : "Shuffle off"}
						>
							<Shuffle class={iconClass} />
						</button>
						<button
							class={[
								"btn-icon transition-colors",
								snap.wrapEnabled &&
									"border-primary/40 bg-primary/10 text-primary",
							]
								.filter(Boolean)
								.join(" ")}
							type="button"
							onclick={() => toggleWrap()}
							aria-label={snap.wrapEnabled ? "Wrap on" : "Wrap off"}
							title={snap.wrapEnabled ? "Wrap on" : "Wrap off"}
						>
							<Repeat class={iconClass} />
						</button>

						<AlertDialog.Root bind:open={clearQueueDialogOpen}>
							<AlertDialog.Trigger
								class="btn-icon"
								type="button"
								disabled={snap.queue.length === 0}
								aria-label="Clear queue"
								title="Clear queue"
							>
								<Trash2 class={iconClass} />
							</AlertDialog.Trigger>

							<AlertDialog.Content>
								<AlertDialog.Header>
									<AlertDialog.Title>Clear queue?</AlertDialog.Title>
									<AlertDialog.Description>
										This will remove all queued tracks.
									</AlertDialog.Description>
								</AlertDialog.Header>

								<AlertDialog.Footer>
									<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
									<AlertDialog.Action
										onclick={() => {
											clearQueue();
											clearQueueDialogOpen = false;
										}}
									>
										Clear
									</AlertDialog.Action>
								</AlertDialog.Footer>
							</AlertDialog.Content>
						</AlertDialog.Root>

						<label class="ml-auto flex items-center gap-2 text-sm">
							<span class="text-muted-foreground" aria-hidden="true">
								<Volume2 class={iconClass} />
							</span>
							<span class="sr-only">Volume</span>
							<input
								type="range"
								min="0"
								max="1"
								step="0.01"
								value={snap.volume}
								oninput={(e) =>
									setVolume(
										Number((e.currentTarget as HTMLInputElement).value),
									)}
							/>
						</label>
					</div>

					<!-- Scroll area: only the queue scrolls -->
					<div class="min-h-0 flex-1 overflow-y-auto overscroll-contain">
						<div class="space-y-1">
							<div class="text-sm font-semibold">
								Queue ({snap.queue.length})
							</div>

							{#if snap.queue.length === 0}
								<p class="text-sm text-muted-foreground">Queue is empty.</p>
							{:else}
								<ul class="rounded border">
									{#each queueDisplay as item (item.track.id)}
										<li
											class={[
												"flex items-center gap-2 border-b px-2 py-2 last:border-b-0",
												// visual affordances
												draggableHint(item.track.id),
												dropIndicatorClass(item.track.id),
											]
												.filter(Boolean)
												.join(" ")}
											ondragover={(e) => onDragOver(item.track.id, e)}
											ondrop={(e) => onDrop(item.track.id, e)}
										>
											<button
												class="btn-icon"
												type="button"
												draggable="true"
												aria-label="Reorder"
												title="Drag to reorder"
												ondragstart={(e) => onDragStart(item.track.id, e)}
												ondragend={onDragEnd}
											>
												<GripVertical class={iconClass} />
											</button>

											<button
												class="min-w-0 flex-1 truncate text-left text-sm hover:underline"
												type="button"
												onclick={() => {
													jumpToTrack(item.track.id);
													void syncAndAutoplay();
												}}
											>
												{#if item.isCurrent}
													<span class="text-muted-foreground">▶ </span>
												{/if}
												<div class="min-w-0 flex-1">
													<div
														class="flex flex-wrap items-baseline gap-x-2 gap-y-1"
													>
														{#if typeNumberLabel(item.track)}
															<span
																class="rounded bg-muted px-2 py-0.5 text-sm text-muted-foreground"
															>
																{typeNumberLabel(item.track)}
															</span>
														{/if}
														<span class="truncate text-sm"
															>{animeLabel(item.track)}</span
														>
													</div>

													<div class="mt-1 text-foreground/80">
														{(item.track.title ?? "").trim() || "Unknown title"}
														<span class="text-sm text-muted-foreground">
															— {(item.track.artist ?? "").trim() ||
																"Unknown Artist"}
														</span>
													</div>
												</div>
											</button>

											<button
												class="btn-icon"
												type="button"
												onclick={() => removeTrack(item.track.id)}
												aria-label="Remove from queue"
												title="Remove from queue"
											>
												<ListX class={iconClass} />
											</button>
										</li>
									{/each}
								</ul>
							{/if}
						</div>
					</div>
				</div>
			</div>
		{/if}
	</div>
</Portal>

<!-- Desktop UI stays in-flow in the right grid column. Hide on small screens via CSS. -->
<aside
	class="hidden lg:flex sticky top-12 h-[calc(100dvh-4rem)] overflow-hidden bg-background flex-col"
>
	<div class="flex items-center gap-2 border-b px-3 py-3">
		<div class="min-w-0 flex-1">
			{#if snap.currentTrack}
				<div class="flex flex-wrap items-baseline gap-x-2 gap-y-1">
					{#if typeNumberLabel(snap.currentTrack)}
						<span
							class="rounded bg-muted px-2 py-0.5 text-sm text-muted-foreground"
						>
							{typeNumberLabel(snap.currentTrack)}
						</span>
					{/if}
					<span class="truncate">
						{(
							snap.currentTrack.animeName ??
							snap.currentTrack.album ??
							""
						).trim()}
					</span>
				</div>

				<div class="mt-1 text-foreground/80">
					{(snap.currentTrack.title ?? "").trim() || "Unknown title"}
					<span class="text-sm text-muted-foreground">
						— {(snap.currentTrack.artist ?? "").trim() || "Unknown Artist"}
					</span>
				</div>
			{:else}
				<div class="truncate text-xs text-muted-foreground">
					{nowPlayingLabel()}
				</div>
			{/if}
		</div>

		<button
			class="btn-icon"
			type="button"
			onclick={() => toggleUiOpen()}
			aria-label={snap.uiOpen ? "Hide player sidebar" : "Show player sidebar"}
			title={snap.uiOpen ? "Hide player sidebar" : "Show player sidebar"}
		>
			{#if snap.uiOpen}
				<PanelRightClose class={iconClass} />
			{:else}
				<PanelRightOpen class={iconClass} />
			{/if}
		</button>
	</div>

	{#if snap.uiOpen}
		<div class="flex min-h-0 flex-col">
			<div class="space-y-2 px-3 py-3">
				<div class="flex items-center justify-between gap-2">
					<div class="text-xs text-muted-foreground">
						{formatTime(currentTime)} / {formatTime(duration)}
					</div>

					<label class="ml-auto flex items-center gap-2 text-sm">
						<span class="text-muted-foreground" aria-hidden="true">
							<Volume2 class={iconClass} />
						</span>
						<span class="sr-only">Volume</span>
						<input
							type="range"
							min="0"
							max="1"
							step="0.01"
							value={snap.volume}
							oninput={(e) =>
								setVolume(Number((e.currentTarget as HTMLInputElement).value))}
						/>
					</label>
				</div>

				<label class="block">
					<span class="sr-only">Seek</span>
					<input
						class="w-full"
						type="range"
						min="0"
						max={Math.max(0, duration)}
						step="0.1"
						bind:value={currentTime}
						disabled={!snap.currentTrack || duration <= 0}
					/>
				</label>

				<div class="flex items-center gap-2">
					<button
						class="btn-icon"
						type="button"
						disabled={!canPrev}
						aria-label="Previous"
						title="Previous"
						onclick={() => {
							prev(currentTime);
							void syncAndAutoplay();
						}}
					>
						<SkipBack class={iconClass} />
					</button>

					<button
						class="btn-icon"
						type="button"
						aria-label={isPlaying ? "Pause" : "Play"}
						title={isPlaying ? "Pause" : "Play"}
						onclick={() => {
							if (!audioEl || !snap.currentTrack) return;

							// If src is not set, it's an initial play action.
							// Delegate to syncAndAutoplay to ensure src is set and loaded.
							if (!audioEl.src) {
								void syncAndAutoplay();
							} else {
								if (audioEl.paused) void audioEl.play();
								else audioEl.pause();
							}
						}}
						disabled={!snap.currentTrack}
					>
						{#if isPlaying}
							<PauseIcon class={iconClass} />
						{:else}
							<PlayIcon class={iconClass} />
						{/if}
					</button>

					<button
						class="btn-icon"
						type="button"
						disabled={!canNext}
						aria-label="Next"
						title="Next"
						onclick={() => {
							next();
							void syncAndAutoplay();
						}}
					>
						<SkipForward class={iconClass} />
					</button>

					<div class="ml-auto flex items-center gap-2">
						<button
							class={[
								"btn-icon transition-colors",
								snap.shuffleEnabled &&
									"border-primary/40 bg-primary/10 text-primary",
							]
								.filter(Boolean)
								.join(" ")}
							type="button"
							onclick={() => toggleShuffle()}
							aria-label={snap.shuffleEnabled ? "Shuffle on" : "Shuffle off"}
							title={snap.shuffleEnabled ? "Shuffle on" : "Shuffle off"}
						>
							<Shuffle class={iconClass} />
						</button>
						<button
							class={[
								"btn-icon transition-colors",
								snap.wrapEnabled &&
									"border-primary/40 bg-primary/10 text-primary",
							]
								.filter(Boolean)
								.join(" ")}
							type="button"
							onclick={() => toggleWrap()}
							aria-label={snap.wrapEnabled ? "Wrap on" : "Wrap off"}
							title={snap.wrapEnabled ? "Wrap on" : "Wrap off"}
						>
							<Repeat class={iconClass} />
						</button>

						<AlertDialog.Root bind:open={clearQueueDialogOpen}>
							<AlertDialog.Trigger
								class="btn-icon"
								type="button"
								disabled={snap.queue.length === 0}
								aria-label="Clear queue"
								title="Clear queue"
							>
								<Trash2 class={iconClass} />
							</AlertDialog.Trigger>

							<AlertDialog.Content>
								<AlertDialog.Header>
									<AlertDialog.Title>Clear queue?</AlertDialog.Title>
									<AlertDialog.Description>
										This will remove all queued tracks.
									</AlertDialog.Description>
								</AlertDialog.Header>

								<AlertDialog.Footer>
									<AlertDialog.Cancel>Cancel</AlertDialog.Cancel>
									<AlertDialog.Action
										onclick={() => {
											clearQueue();
											clearQueueDialogOpen = false;
										}}
									>
										Clear
									</AlertDialog.Action>
								</AlertDialog.Footer>
							</AlertDialog.Content>
						</AlertDialog.Root>
					</div>
				</div>

				<div class="border-t justify-between flex pt-2">
					<div class="text-sm font-semibold">Queue ({snap.queue.length})</div>
					{#if snap.currentIndex !== null}
						<button
							class="btn text-sm text-muted-foreground hover:underline"
							onclick={() => {
								const currentEl = document.querySelector(
									`[data-queue-id='${snap.currentTrack?.id}']`,
								);
								currentEl?.scrollIntoView({
									behavior: "smooth",
									block: "center",
								});
							}}
							title="Scroll to current track"
						>
							Scroll to current
						</button>
					{/if}
				</div>
			</div>

			<div class="min-h-0 flex-1 overflow-y-auto px-3 pb-3">
				{#if snap.queue.length === 0}
					<p class="text-sm text-muted-foreground">Queue is empty.</p>
				{:else}
					<ul class="rounded border">
						{#each queueDisplay as item (item.track.id)}
							<li
								class={[
									"flex items-center gap-2 border-b px-2 py-2 last:border-b-0",
									item.isCurrent && "bg-primary/10",
									// visual affordances
									draggableHint(item.track.id),
									dropIndicatorClass(item.track.id),
								]
									.filter(Boolean)
									.join(" ")}
								data-queue-id={item.track.id}
								ondragover={(e) => onDragOver(item.track.id, e)}
								ondrop={(e) => onDrop(item.track.id, e)}
							>
								<button
									class="btn-icon"
									type="button"
									draggable="true"
									aria-label="Reorder"
									title="Drag to reorder"
									ondragstart={(e) => onDragStart(item.track.id, e)}
									ondragend={onDragEnd}
								>
									<GripVertical class={iconClass} />
								</button>

								<button
									class="min-w-0 flex-1 truncate text-left text-sm hover:underline"
									type="button"
									onclick={() => {
										jumpToTrack(item.track.id);
										void syncAndAutoplay();
									}}
								>
									{#if item.isCurrent}
										<span class="text-muted-foreground">▶ </span>
									{/if}
									<div class="min-w-0 flex-1">
										<div class="flex flex-wrap items-baseline gap-x-2 gap-y-1">
											{#if typeNumberLabel(item.track)}
												<span
													class="rounded bg-muted px-2 py-0.5 text-sm text-muted-foreground"
												>
													{typeNumberLabel(item.track)}
												</span>
											{/if}
											<span class="truncate text-sm"
												>{animeLabel(item.track)}</span
											>
										</div>

										<div class="mt-1 text-foreground/80">
											{(item.track.title ?? "").trim() || "Unknown title"}
											<span class="text-sm text-muted-foreground">
												— {(item.track.artist ?? "").trim() || "Unknown Artist"}
											</span>
										</div>
									</div>
								</button>

								<button
									class="btn-icon"
									type="button"
									onclick={() => removeTrack(item.track.id)}
									aria-label="Remove from queue"
									title="Remove from queue"
								>
									<ListX class={iconClass} />
								</button>
							</li>
						{/each}
					</ul>
				{/if}
			</div>
		</div>
	{/if}
</aside>

<audio
	bind:this={audioEl}
	class="hidden"
	preload="metadata"
	bind:currentTime
	bind:duration
	onplay={onAudioPlay}
	onpause={onAudioPause}
	ontimeupdate={onAudioTimeUpdate}
	onloadedmetadata={onAudioLoadedMetadata}
	onended={onAudioEnded}
></audio>
