<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import Header from './components/Header.vue'
import Footer from './components/Footer.vue'
import Sidebar from './components/Sidebar.vue'
import InstallPrompt from './components/InstallPrompt.vue'

const isSidebarOpen = ref(window.innerWidth >= 768)
const router = useRouter()

// Close sidebar on route change for mobile
router.afterEach(() => {
  if (window.innerWidth < 768) {
    isSidebarOpen.value = false
  }
})

let lastWidth = window.innerWidth

const handleResize = () => {
  const width = window.innerWidth
  // Only change state when crossing the breakpoint
  if (width >= 768 && lastWidth < 768) {
    isSidebarOpen.value = true
  } else if (width < 768 && lastWidth >= 768) {
    isSidebarOpen.value = false
  }
  lastWidth = width
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

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

<template>
  <Header @toggle-sidebar="isSidebarOpen = !isSidebarOpen" />
  <div class="app-body">
    <div
      class="sidebar-overlay"
      :class="{ 'is-visible': isSidebarOpen }"
      @click="isSidebarOpen = false"
    ></div>
    <Sidebar :is-open="isSidebarOpen" />
    <main class="main-content">
      <router-view />
    </main>
  </div>
  <Footer />
  <InstallPrompt />
</template>

<style scoped>
.app-body {
  display: flex;
  flex: 1;
  width: 100%;
  position: relative;
}

.main-content {
  flex: 1;
  padding: 2rem;
  width: 100%;
  max-width: 100%;
  /* Space for fixed footer on mobile + extra margin (match top padding 2rem + footer height ~40px) */
  padding-bottom: calc(2rem + 40px + env(safe-area-inset-bottom));
}

@media (min-width: 768px) {
  .app-body {
    overflow: hidden;
  }

  .main-content {
    overflow-y: auto;
    height: 100%;
    padding-bottom: 2rem;
  }
}

.sidebar-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 900; /* Below sidebar (1000), above content */
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s ease;
  backdrop-filter: blur(2px);
}

.sidebar-overlay.is-visible {
  opacity: 1;
  pointer-events: auto;
}

@media (min-width: 768px) {
  .sidebar-overlay {
    display: none;
  }
}
</style>
