import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import { AUTH_ENABLED } from '@/utils/featureFlags'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  scrollBehavior: () => ({ top: 0 }),
  routes: [
    // ── 公开页面 ──────────────────────────────────────
    {
      path: '/',
      name: 'home',
      component: () => import('@/views/HomeView.vue'),
      meta: { title: '首页' },
    },
    {
      path: '/market',
      name: 'market',
      component: () => import('@/views/MarketView.vue'),
      meta: { title: '行情' },
    },
    {
      path: '/market/:symbol',
      name: 'market-detail',
      component: () => import('@/views/MarketDetailView.vue'),
      meta: { title: '行情详情' },
    },
    {
      path: '/spot/:symbol?',
      name: 'spot',
      component: () => import('@/views/spot/SpotView.vue'),
      meta: { title: '现货交易' },
    },
    {
      path: '/trade',
      name: 'trade',
      component: () => import('@/views/TradeView.vue'),
      meta: { title: '合约介绍' },
    },
    {
      path: '/futures/:symbol',
      name: 'futures',
      component: () => import('@/views/FuturesView.vue'),
      meta: { title: 'U本位合约' },
    },
    {
      path: '/copy-trade',
      name: 'copy-trade',
      component: () => import('@/views/CopyTradeView.vue'),
      meta: { title: '跟单交易' },
    },
    {
      path: '/copy-trade/trader/:id',
      name: 'trader-detail',
      component: () => import('@/views/copy-trade/TraderDetailView.vue'),
      meta: { title: '交易员详情' },
    },
    {
      path: '/copy-trade/my-following',
      name: 'my-following',
      component: () => import('@/views/copy-trade/MyFollowingView.vue'),
      meta: { requiresAuth: true, title: '我的跟单' },
    },
    {
      path: '/copy-trade/my-lead',
      name: 'my-lead',
      component: () => import('@/views/copy-trade/MyLeadView.vue'),
      meta: { requiresAuth: true, title: '我的带单' },
      },
    {
      path: '/finance/ido',
      name: 'finance-ido',
      component: () => import('@/views/finance/StakeView.vue'),
      meta: { requiresAuth: true, title: 'IDO预售' },
    },
    {
      path: '/finance/stake/:configId',
      name: 'finance-stake',
      component: () => import('@/views/finance/StakeView.vue'),
      meta: { requiresAuth: true, title: 'IDO预售' },
    },
    {
      path: '/finance/airdrop',
      name: 'finance-airdrop',
      component: () => import('@/views/finance/AirdropView.vue'),
      meta: { requiresAuth: true, title: '领取空投' },
    },
    {
      path: '/finance/team',
      name: 'finance-team',
      component: () => import('@/views/finance/StakingTeamView.vue'),
      meta: { requiresAuth: true, title: '我的团队' },
    },
    // 费率页已下架，统一跳转首页
    { path: '/fees', redirect: '/' },
    {
      path: '/announcements',
      name: 'announcements',
      component: () => import('@/views/AnnouncementsView.vue'),
      meta: { title: '公告' },
    },
    {
      path: '/announcements/:id',
      name: 'announcement-detail',
      component: () => import('@/views/AnnouncementDetailView.vue'),
      meta: { title: '公告详情' },
    },
    {
      path: '/security',
      name: 'security',
      component: () => import('@/views/SecurityView.vue'),
      meta: { title: '安全中心' },
    },
    {
      path: '/download',
      name: 'download',
      component: () => import('@/views/DownloadView.vue'),
      meta: { title: '下载 App' },
    },
    {
      path: '/guide',
      name: 'guide',
      component: () => import('@/views/GuideView.vue'),
      meta: { title: '新手指南' },
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('@/views/AboutView.vue'),
      meta: { title: '关于我们' },
    },
    {
      path: '/brand',
      name: 'brand',
      component: () => import('@/views/BrandView.vue'),
      meta: { title: '品牌信息' },
    },
    {
      path: '/community',
      name: 'community',
      component: () => import('@/views/CommunityView.vue'),
      meta: { title: '加入iBit社群' },
    },

    // ── 认证流程 ──────────────────────────────────────
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/auth/LoginView.vue'),
      meta: { guestOnly: true, title: '登录' },
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('@/views/auth/RegisterView.vue'),
      meta: { guestOnly: true, title: '注册' },
    },
    {
      path: '/register/verify',
      name: 'register-verify',
      component: () => import('@/views/auth/VerifyView.vue'),
      meta: { guestOnly: true, title: '邮箱验证' },
    },
    {
      path: '/register/password',
      name: 'register-password',
      component: () => import('@/views/auth/PasswordView.vue'),
      meta: { guestOnly: true, title: '设置密码' },
    },
    {
      path: '/register/success',
      name: 'register-success',
      component: () => import('@/views/auth/SuccessView.vue'),
      meta: { title: '注册成功' },
    },
    {
      path: '/forgot-password',
      name: 'forgot-password',
      component: () => import('@/views/auth/ForgotPasswordView.vue'),
      meta: { guestOnly: true, title: '找回密码' },
    },

    // ── 登录后功能页 ───────────────────────────────────
    {
      path: '/account',
      name: 'account',
      component: () => import('@/views/account/AccountView.vue'),
      meta: { requiresAuth: true, title: '用户中心' },
    },
    {
      path: '/account/security',
      name: 'account-security',
      component: () => import('@/views/account/SecuritySettingsView.vue'),
      meta: { requiresAuth: true, title: '安全设置' },
    },
    {
      path: '/account/security/change-password',
      name: 'account-security-change-password',
      component: () => import('@/views/account/ChangePasswordView.vue'),
      meta: { requiresAuth: true, title: '修改登录密码' },
    },
    {
      path: '/account/security/fund-password',
      name: 'account-security-fund-password',
      component: () => import('@/views/account/FundPasswordView.vue'),
      meta: { requiresAuth: true, title: '资金密码' },
    },
    {
      path: '/account/security/google-auth',
      name: 'account-security-google-auth',
      component: () => import('@/views/account/GoogleAuthView.vue'),
      meta: { requiresAuth: true, title: 'Google 验证器' },
    },
    {
      path: '/account/security/google-auth/bind',
      name: 'account-security-google-auth-bind',
      component: () => import('@/views/account/GoogleAuthBindView.vue'),
      meta: { requiresAuth: true, title: '绑定 Google 验证器' },
    },
    {
      path: '/help',
      name: 'help',
      component: () => import('@/views/help/HelpView.vue'),
      meta: { title: '帮助与支持' },
    },
    {
      path: '/help/:id',
      name: 'help-detail',
      component: () => import('@/views/help/HelpDetailView.vue'),
      meta: { title: '帮助详情' },
    },
    {
      path: '/assets',
      name: 'assets',
      component: () => import('@/views/assets/AssetsView.vue'),
      meta: { requiresAuth: true, title: '我的资产' },
    },
    {
      path: '/assets/deposit',
      name: 'assets-deposit',
      component: () => import('@/views/assets/DepositView.vue'),
      meta: { requiresAuth: true, title: '充币' },
    },
    {
      path: '/assets/deposit/history',
      name: 'assets-deposit-history',
      component: () => import('@/views/assets/DepositHistoryView.vue'),
      meta: { requiresAuth: true, title: '充币记录' },
    },
    {
      path: '/assets/withdraw',
      name: 'assets-withdraw',
      component: () => import('@/views/assets/WithdrawView.vue'),
      meta: { requiresAuth: true, title: '提币' },
    },
    {
      path: '/assets/withdraw/history',
      name: 'assets-withdraw-history',
      component: () => import('@/views/assets/WithdrawHistoryView.vue'),
      meta: { requiresAuth: true, title: '提币记录' },
    },
    {
      path: '/assets/withdraw/:id',
      name: 'assets-withdraw-detail',
      component: () => import('@/views/assets/WithdrawDetailView.vue'),
      meta: { requiresAuth: true, title: '提币详情' },
    },
    {
      path: '/assets/transfer',
      name: 'assets-transfer',
      component: () => import('@/views/assets/TransferView.vue'),
      meta: { requiresAuth: true, title: '划转' },
    },
    {
      path: '/assets/transfer/history',
      name: 'assets-transfer-history',
      component: () => import('@/views/assets/TransferHistoryView.vue'),
      meta: { requiresAuth: true, title: '划转记录' },
    },
    {
      path: '/assets/history',
      name: 'assets-history',
      component: () => import('@/views/assets/AssetHistoryView.vue'),
      meta: { requiresAuth: true, title: '资产流水' },
    },
    {
      path: '/broker',
      name: 'broker',
      component: () => import('@/views/broker/BrokerView.vue'),
      meta: { requiresAuth: true, title: '经纪商' },
    },
    {
      path: '/invite',
      name: 'invite',
      component: () => import('@/views/InviteView.vue'),
      meta: { requiresAuth: true, title: '邀请好友' },
    },
    {
      path: '/agent-apply/list',
      name: 'agent-apply-list',
      component: () => import('@/views/agent-apply/AgentApplyListView.vue'),
      meta: { requiresAuth: true, title: '经纪商申请记录' },
    },

    // ── 法律条款 ───────────────────────────────────────
    {
      path: '/legal/:type',
      name: 'legal',
      component: () => import('@/views/LegalView.vue'),
      meta: { title: '法律条款' },
    },

    // ── 404（必须放最后）──────────────────────────────
    {
      path: '/:pathMatch(.*)*',
      name: 'not-found',
      component: () => import('@/views/NotFoundView.vue'),
      meta: { title: '页面未找到' },
    },
  ],
})

// ── 导航守卫 ────────────────────────────────────────────
const SITE_NAME = 'iBit'

router.afterEach((to) => {
  const title = to.meta.title as string | undefined
  document.title = title ? `${title} | ${SITE_NAME}` : SITE_NAME
})

router.beforeEach((to) => {
  // ── 上线初期：登录/注册/资产/个人中心相关路由全部跳回首页 ──
  if (!AUTH_ENABLED && (to.meta.requiresAuth || to.meta.guestOnly)) {
    return { name: 'home' }
  }

  const authStore = useAuthStore()

  // 需要登录但未登录 → 跳转登录页，登录后重定向回来
  if (to.meta.requiresAuth && !authStore.isLoggedIn) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }

  // 已登录用户访问 guestOnly 页面 → 跳回首页
  if (to.meta.guestOnly && authStore.isLoggedIn) {
    return { name: 'home' }
  }
})

export default router
