<script lang="ts" setup>
import { ref, provide, onMounted, onUnmounted, computed } from 'vue'

interface Props {
	sidebarWidth?: string
	sidebarCardStyle?: boolean
}

const props = withDefaults(defineProps<Props>(), {
	sidebarWidth: '260px',
	sidebarCardStyle: false
})

// Menu state
const isOpen = ref(true)
const isMobile = ref(false)

// Check if mobile
function checkMobile() {
	isMobile.value = window.innerWidth < 910
	if (isMobile.value) {
		isOpen.value = false
	}
}

// Toggle menu
function toggleMenu() {
	isOpen.value = !isOpen.value
}

// Close menu on mobile when clicking outside
function closeOnMobile() {
	if (isMobile.value) {
		isOpen.value = false
	}
}

// Computed styles for main content margin
const mainContentStyles = computed(() => {
	if (isMobile.value) {
		return { marginInlineStart: '0' }
	}
	const collapsedWidth = props.sidebarCardStyle ? '82px' : '66px'
	return {
		marginInlineStart: isOpen.value ? props.sidebarWidth : collapsedWidth
	}
})

// Provide state to child components
provide('menuState', {
	isOpen,
	isMobile,
	toggleMenu,
	closeOnMobile,
	sidebarWidth: props.sidebarWidth,
	sidebarCollapsedWidth: props.sidebarCardStyle ? '82px' : '66px'
})

// Provide sidebar card style based on prop
provide('sidebarCardStyle', { value: props.sidebarCardStyle })

// Initialize
onMounted(() => {
	checkMobile()
	window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
	window.removeEventListener('resize', checkMobile)
})
</script>

<template>
	<div class="app-layout vh-100 relative">
		<!-- Mobile Overlay -->
		<div
			v-if="isMobile && isOpen"
			class="overlay"
			@click="closeOnMobile"
		/>

		<!-- Sidebar Slot -->
		<slot name="sidebar" />

		<!-- Main Content Area -->
		<main
			class="main-content flex column ease-300"
			:style="mainContentStyles"
		>
			<!-- Header Slot -->
			<slot name="header" />

			<!-- Page Content -->
			<div class="page-content overflow w-100p h-100p">
				<slot />
			</div>
		</main>
	</div>
</template>

<style scoped>
.app-layout {
	display: flex;
	height: 100vh;
	overflow: hidden;
}
.app-layout:has(.cardWrapSide) {
	padding-inline-start: 0.5rem;
	padding-inline-end: 1rem;
}

.app-layout:has(.sidebar-collapsed .cardWrapSide) {
	padding-inline-start: 1.5rem;
}

/* Overlay for mobile */
.overlay {
	position: fixed;
	inset: 0;
	background: rgba(0, 0, 0, 0.5);
	z-index: 40;
}

/* Main Content */
.main-content {
	flex: 1;
	overflow: hidden;
	transition: margin-inline-start 400ms ease;
		min-height: 100vh
	}

	.page-content {
		overflow: auto;
	}
@media screen and (max-width: 910px) {
	.app-layout:has(.cardWrapSide),
	.app-layout:has(.sidebar-collapsed .cardWrapSide) {
		padding-inline-start: 0rem;
		padding-inline-end: 0rem;
	}
}
</style>
