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

// 扩展 ImportMeta 接口
declare global {
  interface ImportMeta {
    glob: (pattern: string) => Record<string, () => Promise<any>>
  }
}

// 定义路由项类型
interface RouteItem {
  path: string
  name: string
}

// 布局组件
const SharedLayout = defineAsyncComponent(
  () => import('../layouts/SharedLayout.vue')
)

// 首页组件
const Home = {
  props: {
    routes: {
      type: Array as () => RouteItem[],
      required: true
    }
  },
  template: `
    <div>
      <h2>Welcome</h2>
      <p>This is the shared components demo home.</p>
      <ul>
        <li v-for="route in routes" :key="route.path">
          <router-link :to="route.path">
            {{ route.path === '/' ? 'Home' : route.path.slice(1) }}
          </router-link>
        </li>
      </ul>
    </div>
  `
}

// 生成路由配置
const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: SharedLayout,
    children: [
      { 
        path: '', 
        component: Home,
        props: {
          routes: [] as RouteItem[]
        }
      }
    ]
  }
]

// 自动导入所有以 Example.vue 结尾的组件
const testComponents = import.meta.glob('../components/**/*Example.vue')

// 为每个测试组件创建路由
Object.entries(testComponents).forEach(([path, component]) => {
  // 保持完整的路径结构
  // ../components/base/button/ButtonExample.vue -> /base/button
  // ../components/fileupload/FileUploadExample.vue -> /fileupload
  const pathSegments = path
    .replace('../components/', '')
    .replace(/Test\.vue$/, '')
    .split('/')
    .filter(Boolean)
  
  const routePath = `/${pathSegments.join('/').toLowerCase()}`
  const componentName = pathSegments[pathSegments.length - 1].toLowerCase()
  
  const routeConfig: RouteRecordRaw = {
    path: routePath,
    name: componentName,
    component: SharedLayout,
    children: [
      {
        path: '',
        name: `${componentName}-content`,
        component: defineAsyncComponent(component as any),
        meta: { title: `${componentName.charAt(0).toUpperCase() + componentName.slice(1)} Demo` }
      }
    ]
  }

  // 添加路由
  if (routePath === '/') {
    // 如果是根路径，合并到现有路由
    const rootRoute = routes[0]
    if (rootRoute.children) {
      rootRoute.children.push(...routeConfig.children!)
    }
  } else {
    routes.push(routeConfig)
  }

  // 将路由添加到首页的 props 中
  const homeRoute = routes[0]
  if (homeRoute.props && typeof homeRoute.props === 'object' && !Array.isArray(homeRoute.props)) {
    const props = homeRoute.props as { routes: RouteItem[] }
    props.routes.push({
      path: routePath,
      name: componentName
    })
  }
})

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

// 设置页面标题
router.beforeEach((to) => {
  document.title = (to.meta.title as string) || 'Component Demo'
})

export default router
