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

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/setup',
    name: 'SetupAdmin',
    component: () => import('../views/SetupAdmin.vue')
  },
  {
    path: '/reset-password',
    name: 'ResetPassword',
    component: () => import('../views/ResetPassword.vue')
  },
  {
    path: '/consent',
    name: 'Consent',
    component: () => import('../views/Consent.vue')
  },
  {
    path: '/auto-login',
    name: 'AutoLogin',
    component: () => import('../views/AutoLogin.vue')
  },
  {
    path: '/auto-logout',
    name: 'AutoLogout',
    component: () => import('../views/AutoLogout.vue')
  },
  {
    path: '/mobile/login',
    name: 'MobileLogin',
    component: () => import('../views/mobile/MobileLogin.vue')
  },
  {
    path: '/mobile/reset-password',
    name: 'MobileResetPassword',
    component: () => import('../views/mobile/MobileResetPassword.vue')
  },
  {
    path: '/mobile/dashboard',
    name: 'MobileDashboard',
    component: () => import('../views/mobile/MobileDashboard.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/dashboard',
    component: () => import('../views/Dashboard.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '', 
        name: 'DashboardHome',
        redirect: to => {
          // We can't easily access user store here synchronously if it's not loaded.
          // But we can check if there's a token.
          // Better logic: Redirect to a default, and let Dashboard.vue or a Guard handle role-based redirect.
          // Or we use a component that decides.
          return '/dashboard/launchpad'
        }
      },
      {
        path: 'launchpad',
        name: 'PlatformLaunchpad',
        component: () => import('../views/PlatformLaunchpad.vue')
      },
      {
        path: 'apps',
        name: 'AppList',
        component: () => import('../views/apps/AppList.vue')
      },
      {
        path: 'apps/:id/mapping',
        name: 'MappingImport',
        component: () => import('../views/apps/MappingImport.vue')
      },
      {
        path: 'apps/:id/sync',
        name: 'AppSync',
        component: () => import('../views/apps/AppSync.vue')
      },
      {
        path: 'mappings',
        name: 'MyMappings',
        component: () => import('../views/MyMappings.vue')
      },
      {
        path: 'users',
        name: 'UserList',
        component: () => import('../views/UserList.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'system-logs',
        name: 'SystemLogs',
        component: () => import('../views/admin/maintenance/SystemLogs.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'system-status',
        name: 'SystemStatus',
        component: () => import('../views/admin/maintenance/SystemStatus.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'login-logs',
        name: 'LoginLogs',
        component: () => import('../views/admin/maintenance/LoginLogs.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'backup',
        name: 'DataBackup',
        component: () => import('../views/admin/maintenance/DataBackup.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'restore',
        name: 'DataRestore',
        component: () => import('../views/admin/maintenance/DataRestore.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'ssl-config',
        name: 'SSLConfig',
        component: () => import('../views/admin/maintenance/SSLConfig.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'login-config',
        name: 'LoginConfig',
        component: () => import('../views/admin/maintenance/LoginConfig.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'app-categories',
        name: 'AppCategories',
        component: () => import('../views/admin/maintenance/AppCategories.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'admin-api-keys',
        name: 'AdminApiKeys',
        component: () => import('../views/admin/maintenance/AdminApiKeys.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'message-search',
        name: 'MessageSearch',
        component: () => import('../views/admin/maintenance/MessageSearch.vue')
      },
      {
        path: 'app-categories/:id',
        name: 'CategoryDetail',
        component: () => import('../views/admin/maintenance/CategoryDetail.vue'),
        meta: { requiresAdmin: true }
      },
      {
        path: 'changelog',
        name: 'Changelog',
        component: () => import('../views/Changelog.vue')
      },
      {
        path: 'help',
        name: 'Help',
        component: () => import('../views/Help.vue')
      },
      {
        path: 'api-skill',
        name: 'ApiSkill',
        component: () => import('../views/ApiSkill.vue')
      },
      {
        path: 'admin-api-skill',
        name: 'AdminApiSkill',
        component: () => import('../views/AdminApiSkill.vue')
      },
      {
        path: 'messages',
        name: 'Messages',
        component: () => import('../views/message/index.vue')
      },
      {
        path: 'client-distributions',
        name: 'ClientDistributions',
        component: () => import('../views/distribution/DistributionList.vue')
      },
      {
        path: 'client-distributions/:id',
        name: 'DistributionDetail',
        component: () => import('../views/distribution/DistributionDetail.vue')
      }
    ]
  },
  {
    path: '/d/:id',
    name: 'DownloadPage',
    component: () => import('../views/distribution/DownloadPage.vue')
  }
]

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

router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')

  // Detect Mobile Device
  const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  const isMobilePath = to.path.startsWith('/mobile')

  // 1. Mobile Device accessing PC path -> Redirect to Mobile
  if (isMobile && !isMobilePath) {
    if (to.path === '/' || to.path === '/login') {
      next('/mobile/login')
      return
    }
    if (to.path === '/reset-password') {
      next('/mobile/reset-password')
      return
    }
    // PC Dashboard and children -> Mobile Dashboard
    if (to.path.startsWith('/dashboard')) {
      next('/mobile/dashboard')
      return
    }
  }

  // 2. PC Device accessing Mobile path -> Redirect to PC
  if (!isMobile && isMobilePath) {
    if (to.path === '/mobile/login') {
      next('/login')
      return
    }
    if (to.path === '/mobile/reset-password') {
      next('/reset-password')
      return
    }
    if (to.path === '/mobile/dashboard') {
      next('/dashboard')
      return
    }
  }

  // If user is already logged in and tries to access login page, redirect to dashboard
  if (token) {
    if (to.path === '/login') {
      next('/dashboard')
      return
    }
    if (to.path === '/mobile/login') {
      next('/mobile/dashboard')
      return
    }
  }

  // Public routes (including /d/:id for download page)
  const publicRoutes = ['/login', '/register', '/consent', '/reset-password', '/setup', '/mobile/login', '/mobile/reset-password', '/auto-login', '/auto-logout']
  if (publicRoutes.includes(to.path) || to.path.startsWith('/d/')) {
    next()
    return
  }

  if (to.meta.requiresAuth && !token) {
    if (to.path.startsWith('/mobile')) {
      next('/mobile/login')
    } else {
      next('/login')
    }
  } else {
    // Check for Admin role if needed
    // Note: We need user info to check role. Since fetchUser is async,
    // in a real app we might wait for it. For simplicity, we rely on API 403 
    // or assume component will handle it (e.g. v-if="isAdmin").
    // Or we could check authStore if we imported it (pinia must be active).
    next()
  }
})

export default router
