<template>
  <div class="dashboard-router">
    <v-container v-if="loading" class="fill-height">
      <v-row justify="center" align="center">
        <v-col cols="auto" class="text-center">
          <v-progress-circular 
            indeterminate 
            color="primary" 
            size="64"
            width="6"
          />
          <p class="mt-4 text-h6">Loading your dashboard...</p>
        </v-col>
      </v-row>
    </v-container>
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  middleware: 'auth'
});

const { user, userTier, isAuthenticated, checkAuth } = useAuth();
const loading = ref(true);
const authChecked = ref(false);

// Check authentication on mount
onMounted(async () => {
  console.log('🔄 Dashboard mounted, checking authentication...');
  
  // Ensure auth is checked before routing
  await checkAuth();
  authChecked.value = true;
  
  console.log('✅ Auth check complete:', { 
    isAuthenticated: isAuthenticated.value, 
    user: user.value?.email,
    tier: userTier.value 
  });
  
  // Now route based on auth status
  if (isAuthenticated.value && user.value) {
    const tierRoute = `/dashboard/${userTier.value}`;
    console.log('🔄 Routing to tier-specific dashboard:', tierRoute);
    await navigateTo(tierRoute, { replace: true });
  } else {
    console.log('🔄 User not authenticated, redirecting to login');
    await navigateTo('/login');
  }
  
  loading.value = false;
});
</script>

<style scoped>
.dashboard-router {
  min-height: 100vh;
}

.v-progress-circular {
  margin-bottom: 1rem;
}
</style>
