import { createRouter, createWebHistory } from 'vue-router'
import routes, { preloadCriticalRoutes, preloadOnHover } from './routes'
import { useAuthStore } from '@/stores/auth'
import { performanceMonitor } from '@/utils/performance'
import { preloadCache } from '@/utils/cache'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
  scrollBehavior(to, from, savedPosition) {
    // Performance optimization: smooth scroll for better UX
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0, behavior: 'smooth' }
    }
  },
})

// Performance monitoring for route navigation
router.beforeEach((to, from, next) => {
  // Start route navigation timing
  performanceMonitor.startRouteNavigation(to.name as string || to.path)

  // Set document title with route meta
  if (to.meta.title) {
    document.title = `${to.meta.title} - Mitlist`
  }

  next()
})

router.afterEach((to, from) => {
  // End route navigation timing
  performanceMonitor.endRouteNavigation(to.name as string || to.path)

  // Track route change for analytics
  performanceMonitor.recordMetric('RouteChange', 0, {
    from: from.path,
    to: to.path,
    name: to.name
  })
})

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

  // Check if route requires authentication
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    // Preload auth components while redirecting
    preloadOnHover('Login')

    next({
      name: 'Login',
      query: { redirect: to.fullPath }
    })
    return
  }

  // Redirect authenticated users away from auth pages
  if (to.meta.public && authStore.isAuthenticated && to.name !== '404') {
    next({ name: 'Dashboard' })
    return
  }

  next()
})

// Preload critical routes on router initialization
router.isReady().then(() => {
  // Preload critical routes after initial navigation
  setTimeout(() => {
    preloadCriticalRoutes().catch(console.warn)
  }, 1000) // Delay to avoid blocking initial load
})

// Enhanced navigation methods with preloading
const originalPush = router.push
router.push = function (to) {
  // Preload route before navigation
  if (typeof to === 'object' && 'name' in to && to.name) {
    preloadOnHover(to.name as string)
  }

  return originalPush.call(this, to)
}

// Smart preloading on link hover (for use in components)
export function setupLinkPreloading() {
  // Add event listeners for link hover preloading
  document.addEventListener('mouseover', (e) => {
    const target = e.target as HTMLElement
    const link = target.closest('a[data-preload]')

    if (link) {
      const routeName = link.getAttribute('data-preload')
      if (routeName) {
        preloadOnHover(routeName)
      }
    }
  })

  // Add event listeners for focus preloading (accessibility)
  document.addEventListener('focusin', (e) => {
    const target = e.target as HTMLElement
    const link = target.closest('a[data-preload]')

    if (link) {
      const routeName = link.getAttribute('data-preload')
      if (routeName) {
        preloadOnHover(routeName)
      }
    }
  })
}

// Cache management for route data
export function preloadRouteData(routeName: string, params?: Record<string, string>) {
  switch (routeName) {
    case 'ListDetail':
      if (params?.id) {
        preloadCache(`list-${params.id}`, async () => {
          const { apiClient, API_ENDPOINTS } = await import('@/services/api')
          return apiClient.get(API_ENDPOINTS.LISTS.BY_ID(params.id))
        })
      }
      break

    case 'GroupDetail':
      if (params?.id) {
        preloadCache(`group-${params.id}`, async () => {
          const { groupService } = await import('@/services/groupService')
          return groupService.getGroupDetails(Number(params.id))
        })
      }
      break

    case 'Dashboard':
      // Preload dashboard data
      preloadCache('dashboard-stats', async () => {
        const { apiClient } = await import('@/services/api')
        return apiClient.get('/dashboard/stats')
      })
      break
  }
}

// Loading state management
export function createLoadingManager() {
  const loadingStates = new Map<string, boolean>()

  return {
    setLoading: (key: string, loading: boolean) => {
      loadingStates.set(key, loading)
    },

    isLoading: (key: string) => {
      return loadingStates.get(key) || false
    },

    clearAll: () => {
      loadingStates.clear()
    }
  }
}

// Performance budget monitoring
const performanceBudget = {
  FCP: 1800, // First Contentful Paint
  LCP: 2500, // Largest Contentful Paint
  FID: 100,  // First Input Delay
  CLS: 0.1,  // Cumulative Layout Shift
  RouteNavigation: 500 // Route change time
}

// Check performance budget after route changes
router.afterEach(() => {
  setTimeout(() => {
    const vitals = performanceMonitor.getCoreWebVitals()

    Object.entries(performanceBudget).forEach(([metric, budget]) => {
      const actual = vitals[metric as keyof typeof vitals]?.value || 0

      if (actual > budget) {
        console.warn(`⚠️ Performance budget exceeded: ${metric} = ${actual.toFixed(2)}ms (budget: ${budget}ms)`)

        // Track budget violations
        performanceMonitor.recordMetric('BudgetViolation', actual - budget, {
          metric,
          budget,
          actual
        })
      }
    })
  }, 100)
})

export default router
