import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useAuthStore } from '../stores/auth'

const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/auth/Login.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/auth/Register.vue'),
    meta: { requiresGuest: true }
  },
  {
    path: '/',
    component: () => import('../layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'Dashboard',
        component: () => import('../views/Dashboard.vue')
      },
      {
        path: 'qr/heatmap',
        name: 'QRHeatmap',
        component: () => import('../views/qr/Heatmap.vue')
      },
      {
        path: 'volunteers',
        name: 'Volunteers',
        component: () => import('../views/volunteers/Index.vue')
      },
      {
        path: 'volunteers/:id',
        name: 'VolunteerDetail',
        component: () => import('../views/volunteers/Detail.vue')
      },
      {
        path: 'territories',
        name: 'Territories',
        component: () => import('../views/territories/Index.vue')
      },
      {
        path: 'territories/:id',
        name: 'TerritoryDetail',
        component: () => import('../views/territories/Detail.vue')
      },
      {
        path: 'events',
        name: 'Events',
        component: () => import('../views/events/Index.vue')
      },
      {
        path: 'events/:id',
        name: 'EventDetail',
        component: () => import('../views/events/Detail.vue')
      },
      {
        path: 'pqrs',
        name: 'PQRS',
        component: () => import('../views/pqrs/Index.vue')
      },
      {
        path: 'pqrs/:id',
        name: 'PQRSDetail',
        component: () => import('../views/pqrs/Detail.vue')
      },
      {
        path: 'finance',
        name: 'Finance',
        component: () => import('../views/finance/Index.vue')
      },
      {
        path: 'proposals',
        name: 'Proposals',
        component: () => import('../views/proposals/Index.vue')
      },
      {
        path: 'proposals/:id',
        name: 'ProposalDetail',
        component: () => import('../views/proposals/Detail.vue')
      },
      {
        path: 'profile',
        name: 'Profile',
        component: () => import('../views/Profile.vue')
      },
    ]
  },
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const isAuthenticated = !!localStorage.getItem('auth_token')

  if (to.meta.requiresAuth && !isAuthenticated) {
    next('/login')
  } else if (to.meta.requiresGuest && isAuthenticated) {
    next('/')
  } else {
    next()
  }
})

export default router
