import { createRouter, createWebHistory } from 'vue-router';

// Nézetek importálása
import Dashboard from '../views/Dashboard.vue';
import Expenses from '../views/Expenses.vue';
import AddExpense from '../views/AddExpense.vue';
import Login from '../views/Login.vue';
import Register from '../views/Register.vue';
import ForgotPassword from '../views/ForgotPassword.vue';
import ResetPassword from '../views/ResetPassword.vue';
import AddVehicle from '../views/AddVehicle.vue';
import AdminStats from '../views/admin/AdminStats.vue';
import ProfileSelect from '../views/ProfileSelect.vue';
import Debug from '../views/Debug.vue';

const routes = [
  // Védett útvonalak
  { path: '/', name: 'Dashboard', component: Dashboard, meta: { requiresAuth: true } },
  { path: '/expenses', name: 'Expenses', component: Expenses, meta: { requiresAuth: true } },
  { path: '/expenses/add', name: 'AddExpense', component: AddExpense, meta: { requiresAuth: true } },
  { path: '/vehicles/add', name: 'AddVehicle', component: AddVehicle, meta: { requiresAuth: true } },
  
  // Profile selection (public but requires auth)
  { path: '/profile-select', name: 'ProfileSelect', component: ProfileSelect, meta: { requiresAuth: true } },

  // ADMIN útvonal
  { 
    path: '/admin', 
    name: 'Admin', 
    component: AdminStats, 
    meta: { requiresAuth: true, requiresAdmin: true } 
  },

  // Nyilvános útvonalak
  { path: '/login', name: 'Login', component: Login },
  { path: '/register', name: 'Register', component: Register },
  { path: '/forgot-password', name: 'ForgotPassword', component: ForgotPassword },
  { path: '/reset-password', name: 'ResetPassword', component: ResetPassword },
  
  // DEBUG útvonal (nyilvános, nincs auth check)
  { path: '/debug', name: 'Debug', component: Debug },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// Helper function to check if UI mode is selected
function hasUIModeSelected() {
  if (typeof window === 'undefined') return false;
  const saved = localStorage.getItem('ui_mode');
  // Accept both UI values (private_garage, corporate_fleet) and backend values (personal, fleet)
  return saved === 'private_garage' || saved === 'corporate_fleet' || saved === 'personal' || saved === 'fleet';
}

// A "SOROMPÓ" (Auth Guard) LOGIKA
router.beforeEach((to, from, next) => {
  console.group('🚀 Router Navigation Guard - Flight Recorder');
  console.log(`📊 Navigation: ${from.path} → ${to.path}`);
  console.log(`📍 To Route:`, to);
  
  const token = localStorage.getItem('token');
  const isAdmin = localStorage.getItem('is_admin') === 'true';
  const uiMode = localStorage.getItem('ui_mode');
  
  // Import stores to get real-time state
  let isAuthenticated = false;
  let appMode = null;
  
  try {
    // Try to get auth store state if available
    const authStore = window.__pinia?.state.value?.auth;
    if (authStore) {
      isAuthenticated = !!authStore.token;
      console.log('🔐 Auth Store State:', authStore);
    }
  } catch (e) {
    console.warn('⚠️ Could not access auth store:', e.message);
  }
  
  try {
    // Try to get app mode store state if available
    const appModeStore = window.__pinia?.state.value?.appMode;
    if (appModeStore) {
      appMode = appModeStore.mode;
      console.log('🎛️ App Mode Store State:', appModeStore);
    }
  } catch (e) {
    console.warn('⚠️ Could not access app mode store:', e.message);
  }
  
  console.log('📋 Authentication Status:');
  console.log('  • Token in localStorage:', token ? `YES (${token.substring(0, 20)}...)` : 'NO');
  console.log('  • isAdmin flag:', isAdmin);
  console.log('  • UI Mode in localStorage:', uiMode || 'NOT SET');
  console.log('  • Auth Store isAuthenticated:', isAuthenticated);
  console.log('  • App Mode Store mode:', appMode);
  console.log('  • Route requiresAuth:', to.meta.requiresAuth || false);
  console.log('  • Route requiresAdmin:', to.meta.requiresAdmin || false);
  
  // Auth check
  if (to.meta.requiresAuth && !token) {
    console.warn('❌ AUTH FAILED: Route requires auth but no token found');
    console.warn(`   ↳ Redirecting to /login (from ${to.path})`);
    console.groupEnd();
    next('/login');
    return;
  }

  // Admin check
  if (to.meta.requiresAdmin && !isAdmin) {
    console.warn('❌ ADMIN CHECK FAILED: Route requires admin but user is not admin');
    console.warn(`   ↳ Redirecting to / (from ${to.path})`);
    console.groupEnd();
    next('/');
    return;
  }

  // UI mode selection logic
  if (to.meta.requiresAuth && token) {
    const hasMode = hasUIModeSelected();
    console.log('🎯 UI Mode Check:');
    console.log('  • hasUIModeSelected():', hasMode);
    console.log('  • Target route name:', to.name);
    
    // If user tries to access dashboard without mode selection, redirect to profile-select
    if (to.name === 'Dashboard' && !hasMode) {
      console.warn('⚠️ UI MODE MISSING: Dashboard access without mode selection');
      console.warn(`   ↳ Redirecting to /profile-select (from ${to.path})`);
      console.groupEnd();
      next('/profile-select');
      return;
    }
    
    // If user tries to access profile-select but already has mode, redirect to dashboard
    if (to.name === 'ProfileSelect' && hasMode) {
      console.warn('⚠️ UI MODE ALREADY SET: Profile-select access with existing mode');
      console.warn(`   ↳ Redirecting to / (from ${to.path})`);
      console.groupEnd();
      next('/');
      return;
    }
  }

  console.log('✅ ALL CHECKS PASSED: Allowing navigation to', to.path);
  console.groupEnd();
  next();
});

export default router;