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

// 인증 관련 뷰
const Login = () => import('@/views/auth/Login.vue');
const Profile = () => import('@/views/auth/Profile.vue');

// 관리자 뷰
const AdminDashboard = () => import('@/views/admin/Dashboard.vue');
const ClubManagement = () => import('@/views/admin/ClubManagement.vue');
const UserManagement = () => import('@/views/admin/UserManagement.vue');
const SubscriptionManagement = () => import('@/views/admin/SubscriptionManagement.vue');
const ActivityLogManagement = () => import('@/views/admin/ActivityLogManagement.vue');

// 클럽 뷰
const ClubDashboard = () => import('@/views/club/Dashboard.vue');
const MemberManagement = () => import('@/views/club/MemberManagement.vue');
const Statistics = () => import('@/views/club/Statistics.vue');
const EventManagement = () => import('@/views/club/EventManagement.vue');
const EventCalendar = () => import('@/views/club/EventCalendar.vue');
const ScoreManagement = () => import('@/views/club/ScoreManagement.vue');
const UserClubCreate = () => import('@/views/club/ClubCreate.vue');
const ClubSettings = () => import('@/views/club/ClubSettings.vue');

// 구독 관리 컴포넌트 import
const ClubSubscriptionManagement = () => import('@/views/club/subscription/SubscriptionManagement.vue');

// 결제 관련 컴포넌트 import
const PaymentSuccess = () => import('@/views/payment/PaymentSuccess.vue');
const PaymentFail = () => import('@/views/payment/PaymentFail.vue');

const EventPublicPage = () => import('@/views/event/EventPublicPage.vue');

const routes = [
  // 공개 경로
  { 
    path: '/', 
    redirect: '/login' 
  },
  {
    path: '/bowlspeed',
    name: 'BowlingSpeed',
    beforeEnter() {
      window.location.href = '/bowlspeed/index.html';
    },
    meta: { title: '볼링공 속도 계산기', requiresAuth: false }
  },
  {
    path: '/public/:publicHash',
    name: 'EventPublicPage',
    component: EventPublicPage,
    meta: { title: 'LaneBow - 볼링 클럽 매니저', requiresAuth: false, layout: 'public' }
  },
  { 
    path: '/login', 
    name: 'Login', 
    component: Login,
    meta: { requiresAuth: false }
  },
  
  // 인증 필요 경로
  { 
    path: '/profile', 
    name: 'Profile', 
    component: Profile,
    meta: { requiresAuth: true }
  },
  
  // 관리자 경로
  { 
    path: '/admin', 
    name: 'AdminDashboard', 
    component: AdminDashboard,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  { 
    path: '/admin/clubs', 
    name: 'ClubManagement', 
    component: ClubManagement,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  { 
    path: '/admin/users', 
    name: 'UserManagement', 
    component: UserManagement,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  { 
    path: '/admin/subscriptions', 
    name: 'SubscriptionManagement', 
    component: SubscriptionManagement,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  { 
    path: '/admin/activity-logs', 
    name: 'ActivityLogManagement', 
    component: ActivityLogManagement,
    meta: { requiresAuth: true, requiresAdmin: true }
  },
  
  // 클럽 경로
  { 
    path: '/club', 
    component: () => import('@/layouts/ClubLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'ClubDashboard',
        component: () => import('@/views/club/Dashboard.vue')
      },
      {
        path: 'members',
        name: 'MemberManagement',
        component: () => import('@/views/club/MemberManagement.vue')
      },
      {
        path: 'events',
        name: 'EventManagement',
        component: () => import('@/views/club/EventManagement.vue')
      },
      {
        path: 'events/calendar',
        name: 'EventCalendar',
        component: () => import('@/views/club/EventCalendar.vue')
      },
      {
        path: 'events/:eventId/scores',
        name: 'ScoreManagement',
        component: () => import('@/views/club/ScoreManagement.vue'),
        props: true
      },
      {
        path: 'statistics',
        name: 'Statistics',
        component: () => import('@/views/club/Statistics.vue')
      },
      {
        path: 'subscription',
        name: 'ClubSubscription',
        component: ClubSubscriptionManagement,
        meta: { 
          requiresAuth: true,
          requiredRoles: ['admin', 'owner', 'manager']
        }
      },
      {
        path: 'settings',
        name: 'ClubSettings',
        component: ClubSettings,
        meta: {
          requiresAuth: true,
          requiredRoles: ['admin', 'owner', 'manager']
        }
      }
    ]
  },
  { 
    path: '/club/create', 
    name: 'UserClubCreate', 
    component: () => import('@/views/club/ClubCreate.vue'),
    meta: { requiresAuth: true }
  },
  
  // 결제 관련 경로
  {
    path: '/payment/success',
    name: 'PaymentSuccess',
    component: PaymentSuccess,
    meta: { requiresAuth: true }
  },
  {
    path: '/payment/fail',
    name: 'PaymentFail',
    component: PaymentFail,
    meta: { requiresAuth: true }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  linkActiveClass: 'router-link-active',
  linkExactActiveClass: 'router-link-active'
});

// 네비게이션 가드
router.beforeEach(async (to, from, next) => {
  const isAuthenticated = !!localStorage.getItem('token');
  const userRole = localStorage.getItem('userRole');
  const clubId = localStorage.getItem('clubId');
  const userClubRole = localStorage.getItem('userClubRole');
  
  // 인증이 필요한 페이지인데 로그인하지 않은 경우
  if (to.meta.requiresAuth && !isAuthenticated) {
    next({ name: 'Login' });
    return;
  }
  
  // 관리자 권한이 필요한 페이지인데 관리자가 아닌 경우
  if (to.meta.requiresAdmin && userRole !== 'admin' && userRole !== 'superadmin') {
    next({ name: 'ClubDashboard' });
    return;
  }
  
  // 이미 로그인한 상태에서 로그인 페이지로 이동하려는 경우
  if (to.name === 'Login' && isAuthenticated) {
    if (userRole === 'admin' || userRole === 'superadmin') {
      next({ name: 'AdminDashboard' });
    } else {
      next({ name: 'ClubDashboard' });
    }
    return;
  }
  
  // 일반 사용자가 클럽이 없는 경우, 클럽 생성 페이지로 리다이렉트 (관리자 제외)
  if (isAuthenticated && userRole !== 'admin' && userRole !== 'superadmin' && !clubId && 
      to.name !== 'UserClubCreate' && to.name !== 'Profile' && to.name !== 'Login') {
    next({ name: 'UserClubCreate' });
    return;
  }
  
  // 클럽 구독 관리 또는 설정 페이지에 접근하려는 경우, 권한 확인
  if ((to.name === 'ClubSubscription' || to.name === 'ClubSettings') && 
      (userClubRole !== 'admin' && userClubRole !== 'owner' && userClubRole !== 'manager')) {
    next({ name: 'ClubDashboard' });
    return;
  }
  
  next();
});

export default router;
