<template>
  <div id="app">
    <!-- Show layout for authenticated routes -->
    <AppLayout v-if="showLayout">
      <template #detail-panel>
        <slot name="detail-panel" />
      </template>
    </AppLayout>
    
    <!-- Show loading spinner while user data is being fetched -->
    <div v-else-if="isLoadingUser" class="min-h-screen flex items-center justify-center">
      <div class="text-center">
        <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto mb-4"></div>
        <p class="text-muted-foreground">Loading...</p>
      </div>
    </div>
    
    <!-- Show standalone pages for auth routes -->
    <router-view v-else />
    
    <!-- Global Toast Container -->
    <Toaster />
  </div>
</template>

<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import AppLayout from '@/components/layout/AppLayout.vue'
import { Toaster } from '@/components/ui/toast'

const route = useRoute()
const authStore = useAuthStore()

// Show layout only for authenticated routes (not login/register)
const showLayout = computed(() => {
  const isAuthRoute = route.meta?.requiresGuest || route.name === 'Login' || route.name === 'Register'
  
  // If it's an auth route (login/register), never show layout
  if (isAuthRoute) {
    return false
  }
  
  // For protected routes, show layout only if fully authenticated (has both token and user)
  return authStore.isAuthenticated
})

// Show loading state when we have a token but no user data yet
const isLoadingUser = computed(() => {
  const isAuthRoute = route.meta?.requiresGuest || route.name === 'Login' || route.name === 'Register'
  
  // Don't show loading for auth routes
  if (isAuthRoute) {
    return false
  }
  
  // Show loading if we have a token but no user data (and not currently loading)
  return !!authStore.accessToken && !authStore.user && !authStore.isLoading
})
</script>

<style scoped>
#app {
  min-height: 100vh;
}
</style>