<script lang="ts">
	import Library from "./Library.svelte";
	import NowPlaying from "./NowPlaying.svelte";
	import { settings } from "./app.svelte.js";

	let dragging = $state(false);

	function onMouseDown(e: MouseEvent) {
		dragging = true;
		window.addEventListener("mousemove", onMouseMove);
		window.addEventListener("mouseup", onMouseUp);
	}

	function onMouseMove(e: MouseEvent) {
		if (!dragging) return;
		const base = parseFloat(
			getComputedStyle(document.documentElement).fontSize,
		);
		settings.sidebarWidth = Math.max(16, Math.min(48, e.clientX / base));
	}

	function onMouseUp() {
		dragging = false;
		window.removeEventListener("mousemove", onMouseMove);
		window.removeEventListener("mouseup", onMouseUp);
	}

	$effect(() => {
		if (dragging) {
			document.body.style.cursor = "col-resize";
			return () => (document.body.style.cursor = "");
		}
	});
</script>

<div id="sidebar">
	<Library />
	<NowPlaying />
	<!-- svelte-ignore a11y_no_static_element_interactions -->
	<div class="resizer" onmousedown={onMouseDown}></div>
</div>

<style>
	#sidebar {
		background: var(--bg-secondary);
		grid-area: sidebar;
		display: flex;
		flex-direction: column;
		border-inline-end: 1px solid var(--border);
		overflow: hidden;
		position: relative;
	}
	.resizer {
		position: absolute;
		inset-block: 0;
		inset-inline-end: 0;
		inline-size: 4px;
		cursor: col-resize;
		z-index: 10;
	}
	.resizer:hover {
		background: var(--text);
	}
	@media (max-width: 32rem) {
		#sidebar {
			border-inline-end: none;
			border-block-start: 1px solid var(--border);
		}
		.resizer {
			display: none;
		}
	}
</style>
