import { useCallback, useEffect } from "preact/hooks";

import { cn } from "@/lib/utils";
import { dragging } from "@/store";

const { isDragging } = dragging.value;

export default function Sidebar() {
	return (
		<aside
			className="relative flex h-[100dvh] w-full bg-secondary px-2 py-8"
			style={{ width: dragging.value.width }}
		>
			<div className=""></div>
			<nav className="">
				<a href="#">Lol</a>
			</nav>
			<Divider />
		</aside>
	);
}

function Divider() {
	function onMouseDown() {
		dragging.value = {
			...dragging.value,
			isDragging: true,
		};
	}

	function onMouseUp() {
		dragging.value = {
			...dragging.value,
			isDragging: false,
		};
	}

	const handler = useCallback(
		(event: MouseEvent) => {
			if (dragging.value.isDragging) {
				const width = Math.min(Math.max(200, event.clientX), 320);
				dragging.value = {
					...dragging.value,
					width,
				};
				localStorage.setItem("sidebar-width", width.toString());
			}
		},
		[dragging.value.isDragging],
	);

	useEffect(() => {
		window.addEventListener("mousemove", handler);
		window.addEventListener("mouseup", onMouseUp);

		return () => {
			window.removeEventListener("mousemove", handler);
			window.removeEventListener("mouseup", onMouseUp);
		};
	}, [isDragging]);

	return (
		<div
			className={cn(
				"group absolute -right-2 bottom-0 top-0 px-2 hover:cursor-col-resize",
				{},
			)}
			onMouseDown={onMouseDown}
			onMouseUp={onMouseUp}
		>
			<div className="h-full w-[1px] bg-border transition-colors group-hover:scale-x-[2] group-hover:bg-accent/50"></div>
		</div>
	);
}
