import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '../layouts/MainLayout.vue'
import AdminLayout from '../layouts/AdminLayout.vue'

import Home from '../pages/user/Home.vue'
import ProductList from '../pages/user/ProductList.vue'
import ProductDetail from '../pages/user/ProductDetail.vue'
import Cart from '../pages/user/Cart.vue'
import Checkout from '../pages/user/Checkout.vue'
import Orders from '../pages/user/Orders.vue'
import Profile from '../pages/user/Profile.vue'
import Login from '../pages/user/Login.vue'
import Register from '../pages/user/Register.vue'

import AdminLogin from '../pages/admin/AdminLogin.vue'
import AdminUsers from '../pages/admin/AdminUsers.vue'
import AdminCategories from '../pages/admin/AdminCategories.vue'
import AdminProducts from '../pages/admin/AdminProducts.vue'
import AdminOrders from '../pages/admin/AdminOrders.vue'
import AdminCarousels from '../pages/admin/AdminCarousels.vue'
import AdminNotices from '../pages/admin/AdminNotices.vue'

const routes = [
  {
    path: '/',
    component: MainLayout,
    children: [
      { path: '', component: Home },
      { path: 'products', component: ProductList },
      { path: 'products/:id', component: ProductDetail },
      { path: 'cart', component: Cart },
      { path: 'checkout', component: Checkout },
      { path: 'orders', component: Orders },
      { path: 'profile', component: Profile },
      { path: 'login', component: Login },
      { path: 'register', component: Register }
    ]
  },
  {
    path: '/admin/login',
    component: AdminLogin
  },
  {
    path: '/admin',
    component: AdminLayout,
    children: [
      { path: 'users', component: AdminUsers },
      { path: 'categories', component: AdminCategories },
      { path: 'products', component: AdminProducts },
      { path: 'orders', component: AdminOrders },
      { path: 'carousels', component: AdminCarousels },
      { path: 'notices', component: AdminNotices }
    ]
  }
]

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

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const role = localStorage.getItem('role')
  if (to.path.startsWith('/admin') && to.path !== '/admin/login') {
    if (!token || role !== 'ADMIN') return next('/admin/login')
  }
  if (['/cart', '/checkout', '/orders', '/profile'].includes(to.path)) {
    if (!token) return next('/login')
  }
  next()
})

export default router
