import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import { useAuthStore } from '@/stores/auth'
import { useUiStore } from '@/stores/ui'
import { demo } from '@/demo'

// 둘러보기(데모)에서 더미로 진입 가능한 화면
const DEMO_ALLOWED = new Set(['account-entries', 'account-recurrings', 'account-wallets', 'account-categories'])

// Electron(데스크톱)은 file:// 로 로드 → 해시 히스토리라야 새로고침/딥링크가 안전
const isDesktop = typeof navigator !== 'undefined' && /electron/i.test(navigator.userAgent)

const router = createRouter({
  history: isDesktop ? createWebHashHistory() : createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      // 둘러보기(데모)에서 미지원(로그인 필요) 화면 진입 시 — 잠금 안내 (공개)
      path: '/demo-locked',
      name: 'demo-locked',
      component: () => import('../views/DemoLockedView.vue'),
    },
    {
      // 유료 멤버십 안내/업그레이드 (로그인 필요, 무료 회원도 접근 가능)
      path: '/upgrade',
      name: 'upgrade',
      component: () => import('../views/UpgradeView.vue'),
      meta: { requiresAuth: true },
    },
    {
      // 개인정보처리방침 (공개 — 웹에서도 접근, 앱 마켓 정책 URL)
      path: '/privacy',
      name: 'privacy',
      component: () => import('../views/LegalView.vue'),
      meta: { public: true, doc: 'privacy' },
    },
    {
      // 이용약관 (공개)
      path: '/terms',
      name: 'terms',
      component: () => import('../views/LegalView.vue'),
      meta: { public: true, doc: 'terms' },
    },
    {
      // 계정·데이터 삭제 안내 (공개 — 앱 마켓 데이터 삭제 정책 URL)
      path: '/account-deletion',
      name: 'account-deletion',
      component: () => import('../views/AccountDeletionView.vue'),
      meta: { public: true },
    },
    {
      path: '/users',
      name: 'users',
      component: () => import('../views/UsersView.vue'),
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    // 게시판: 카테고리(community/saving/tips)별 목록·작성·상세·수정
    { path: '/board', redirect: '/board/community' },
    {
      path: '/board/:category(community|saving|tips)',
      name: 'board',
      component: () => import('../views/board/BoardListView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/my-board',
      name: 'my-board',
      component: () => import('../views/board/MyBoardView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/board/:category(community|saving|tips)/write',
      name: 'board-write',
      component: () => import('../views/board/BoardWriteView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/board/:category(community|saving|tips)/:id(\\d+)',
      name: 'board-detail',
      component: () => import('../views/board/BoardDetailView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/board/:category(community|saving|tips)/:id(\\d+)/edit',
      name: 'board-edit',
      component: () => import('../views/board/BoardWriteView.vue'),
      meta: { requiresAuth: true },
    },
    // 구버전 링크(/board/123) 호환 — 커뮤니티 상세로 이동
    { path: '/board/:id(\\d+)', redirect: (to) => `/board/community/${to.params.id}` },
    {
      path: '/admin/tags',
      name: 'admin-tags',
      component: () => import('../views/admin/TagAdminView.vue'),
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    {
      path: '/admin/default-categories',
      name: 'admin-default-categories',
      component: () => import('../views/admin/DefaultCategoryView.vue'),
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    {
      path: '/admin/reports',
      name: 'admin-reports',
      component: () => import('../views/admin/ReportAdminView.vue'),
      meta: { requiresAuth: true, requiresAdmin: true },
    },
    {
      // 구 가계부 대시보드 → 내역으로 (대시보드 정보는 홈/통계로 이전)
      path: '/account',
      redirect: '/account/entries',
    },
    {
      path: '/account/entries',
      name: 'account-entries',
      component: () => import('../views/account/AccountView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/stats',
      name: 'account-stats',
      component: () => import('../views/account/AccountDashboardView.vue'),
      meta: { requiresAuth: true, requiresPremium: true },
    },
    {
      path: '/account/tags',
      name: 'account-tags',
      component: () => import('../views/account/AccountTagView.vue'),
      meta: { requiresAuth: true, requiresPremium: true },
    },
    {
      path: '/account/wallets',
      name: 'account-wallets',
      component: () => import('../views/account/AccountWalletView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/wallets/new',
      name: 'account-wallet-new',
      component: () => import('../views/account/WalletFormView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/wallets/:id(\\d+)/edit',
      name: 'account-wallet-edit',
      component: () => import('../views/account/WalletFormView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/wallets/:id(\\d+)',
      name: 'account-wallet-detail',
      component: () => import('../views/account/AccountWalletDetailView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/repayments',
      name: 'account-repayments',
      component: () => import('../views/account/RepaymentScheduleView.vue'),
      meta: { requiresAuth: true, requiresPremium: true },
    },
    {
      path: '/account/categories',
      name: 'account-categories',
      component: () => import('../views/account/CategoryView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/budget',
      name: 'account-budget',
      component: () => import('../views/account/BudgetView.vue'),
      meta: { requiresAuth: true, requiresPremium: true },
    },
    {
      path: '/account/recurrings',
      name: 'account-recurrings',
      component: () => import('../views/account/RecurringView.vue'),
      // 정기결제은 무료도 2건까지 체험(초과 시 업셀) — 유료 게이트 해제
      meta: { requiresAuth: true },
    },
    {
      path: '/account/recurrings/new',
      name: 'account-recurring-new',
      component: () => import('../views/account/RecurringFormView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/account/recurrings/:id(\\d+)/edit',
      name: 'account-recurring-edit',
      component: () => import('../views/account/RecurringFormView.vue'),
      meta: { requiresAuth: true },
    },
    // 설정 (앱 하단 내비게이션 → 설정)
    {
      path: '/settings',
      name: 'settings',
      component: () => import('../views/settings/SettingsView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/settings/account',
      name: 'settings-account',
      component: () => import('../views/settings/AccountInfoView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/settings/account/edit',
      name: 'settings-account-edit',
      component: () => import('../views/settings/ProfileEditView.vue'),
      meta: { requiresAuth: true },
    },
    {
      path: '/settings/shop',
      name: 'settings-shop',
      component: () => import('../views/settings/ShopView.vue'),
      meta: { requiresAuth: true },
    },
  ],
})

// 전역 네비게이션 가드
router.beforeEach((to, from) => {
  const auth = useAuthStore()
  // 둘러보기(데모): 지원 화면은 더미로 진입, 그 외 보호 화면은 잠금 안내로
  if (demo.on && !auth.isAuthenticated) {
    if (to.name === 'home') return { name: 'account-entries' }
    if (to.meta.requiresAuth) {
      if (DEMO_ALLOWED.has(to.name)) return true
      return { name: 'demo-locked', query: { from: to.name || '' } }
    }
    return true // 공개 라우트(잠금 안내 등)
  }
  // 인증이 필요한 페이지인데 미로그인 → 로그인 팝업 오픈 (원래 목적지 보존), 이동은 취소/홈
  if (to.meta.requiresAuth && !auth.isAuthenticated) {
    const ui = useUiStore()
    ui.openLogin(to.fullPath)
    return from.name ? false : { name: 'home' }
  }
  // 관리자 전용 페이지 — 비관리자는 홈으로
  if (to.meta.requiresAdmin && auth.user?.role !== 'ADMIN') {
    return { name: 'home' }
  }
  // 유료 전용 페이지 — 무료 회원은 업그레이드 안내로
  if (to.meta.requiresPremium && !auth.isPremium) {
    return { name: 'upgrade' }
  }
})

// 새 배포로 청크 해시가 바뀐 뒤, 캐시된 옛 index.html 이 삭제된 옛 청크를 부르면
// 동적 import 가 실패한다. 이 경우 목적지로 1회 전체 새로고침해 최신 index.html 을 받게 한다.
// (경로별 1회만 — 새로고침 후에도 실패하면 무한 새로고침/로그인 루프를 막기 위해 중단)
router.onError((err, to) => {
  const msg = (err && err.message) || ''
  const chunkError = /dynamically imported module|Importing a module script failed|Failed to fetch dynamically imported module|ChunkLoadError|error loading dynamically imported module/i.test(msg)
  if (!chunkError) return
  const path = to?.fullPath || window.location.pathname
  const key = 'chunk-reload:' + path
  if (sessionStorage.getItem(key)) return // 이미 한 번 새로고침했는데 또 실패 → 루프 방지
  sessionStorage.setItem(key, '1')
  window.location.assign(path)
})
// 정상 진입 시 해당 경로의 새로고침 플래그 정리 (다음 배포 때 다시 동작하도록)
router.afterEach((to) => {
  sessionStorage.removeItem('chunk-reload:' + to.fullPath)
})

export default router
