<script lang="ts">
	import Sidebar from './Sidebar.svelte';
	import Navbar from './Navbar.svelte';
	import { Toast } from '$lib/components';
	import { sidebar } from '$lib/stores/sidebar.svelte';

	let { children }: { children: import('svelte').Snippet } = $props();

	let touchStartX = 0;
	let touchStartY = 0;

	function onTouchStart(e: TouchEvent) {
		touchStartX = e.touches[0].clientX;
		touchStartY = e.touches[0].clientY;
	}

	function onTouchEnd(e: TouchEvent) {
		const dx = e.changedTouches[0].clientX - touchStartX;
		const dy = e.changedTouches[0].clientY - touchStartY;
		// Only trigger if swipe is mostly horizontal
		if (Math.abs(dx) < Math.abs(dy) * 1.5) return;
		if (dx > 60) sidebar.open || sidebar.toggle();
		if (dx < -60 && sidebar.open) sidebar.close();
	}
</script>

<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="layout" ontouchstart={onTouchStart} ontouchend={onTouchEnd}>
	<Sidebar />
	{#if sidebar.open}
		<!-- svelte-ignore a11y_click_events_have_key_events -->
		<!-- svelte-ignore a11y_no_static_element_interactions -->
		<div class="overlay" onclick={() => sidebar.close()}></div>
	{/if}
	<div class="main">
		<Navbar />
		<div class="content">
			{@render children()}
		</div>
	</div>
</div>
<Toast />

<style>
	.layout {
		display: flex;
		min-height: 100vh;
	}
	.main {
		flex: 1;
		min-width: 0;
		overflow: hidden;
		margin-left: var(--sidebar-width);
		display: flex;
		flex-direction: column;
	}
	.content {
		flex: 1;
		min-width: 0;
		padding: 24px;
		overflow-y: auto;
		overflow-x: hidden;
		max-height: calc(100vh - var(--navbar-height));
	}
	.overlay { display: none; }

	@media (max-width: 768px) {
		.main { margin-left: 0; }
		.content { padding: 16px; }
		.overlay {
			display: block;
			position: fixed;
			inset: 0;
			background: rgba(0, 0, 0, 0.5);
			z-index: 99;
		}
	}
</style>
