<template>
    <div class="app-layout" :class="{ 'sidebar-collapsed': collapsed, 'mobile-open': mobileOpen }" id="app">
        <AppSidebar :collapsed="collapsed" :mobileOpen="mobileOpen" @toggle-sidebar="toggleSidebar" />

        <div class="main-wrapper">
            <AppTopbar @toggle-sidebar="toggleSidebar" />

            <main class="page-content" :class="{ 'no-padding': noPadding }">
                <slot />
            </main>
        </div>

        <!-- Mobile Sidebar Backdrop Overlay -->
        <Transition name="fade">
            <div v-if="mobileOpen" class="sidebar-backdrop" @click="mobileOpen = false"></div>
        </Transition>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { usePage } from '@inertiajs/vue3';
import AppSidebar from '@/Components/AppSidebar.vue';
import AppTopbar from '@/Components/AppTopbar.vue';

defineProps({
    noPadding: {
        type: Boolean,
        default: false
    }
});

const collapsed = ref(
    typeof window !== 'undefined' ? localStorage.getItem('sidebar-collapsed') === 'true' : false
);
const mobileOpen = ref(false);

const toggleSidebar = () => {
    if (typeof window !== 'undefined' && window.innerWidth <= 1024) {
        mobileOpen.value = !mobileOpen.value;
    } else {
        collapsed.value = !collapsed.value;
        if (typeof window !== 'undefined') {
            localStorage.setItem('sidebar-collapsed', collapsed.value ? 'true' : 'false');
        }
    }
};

// Close mobile sidebar on page navigation
const page = usePage();
watch(() => page.url, () => {
    mobileOpen.value = false;
});
</script>

<style scoped>
.sidebar-backdrop {
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, 0.45);
    backdrop-filter: blur(2px);
    z-index: 10040;
}

.fade-enter-active,
.fade-leave-active {
    transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
    opacity: 0;
}
</style>
