import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import AppLayout from '../views/AppLayout.vue'

// Auto-discover all route modules from routes/ directory
const routeModules = import.meta.glob('./routes/*.js', { eager: true })
const appChildren = Object.values(routeModules).flatMap(m => m.default)

const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/Login.vue'),
    meta: { guest: true }
  },
  // Standalone full-screen dashboards (no sidebar, no auth required)
  {
    path: '/shopfloor',
    name: 'shopfloor',
    component: () => import('../views/ShopfloorDashboard.vue')
  },
  {
    path: '/tv',
    name: 'tv',
    component: () => import('../views/TVDashboard.vue')
  },
  // Print pages (standalone, no sidebar/header)
  {
    path: '/print/equipment-badge/:id',
    name: 'print-equipment-badge',
    component: () => import('../views/print/EquipmentBadge.vue')
  },
  {
    path: '/print/printer-qr',
    name: 'print-printer-qr-batch',
    component: () => import('../views/print/PrinterQRBatch.vue')
  },
  {
    path: '/print/printer-qr/:id',
    name: 'print-printer-qr-single',
    component: () => import('../views/print/PrinterQRSingle.vue')
  },
  {
    path: '/print/usb-labels',
    name: 'print-usb-labels',
    component: () => import('../views/print/USBLabelBatch.vue')
  },
  {
    path: '/',
    component: AppLayout,
    children: appChildren
  }
]

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

// Navigation guard
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()

  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.meta.requiresAdmin && !authStore.isAdmin) {
    next('/')
  } else if (to.meta.guest && authStore.isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
