import { defineComponent, onMounted, shallowRef, markRaw, computed, watch, h } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { usePageTypeSlug } from '@/shared/utils/slug'
import { resolvePagetypeDetailOverride } from '@/core/registry/pagetypeOverride'
import DefaultDetail from '@/core/pagetype/default.vue'

/**
 * 详情页路由分发器：决定使用覆盖组件还是默认组件
 * 位置：app/router/detailPage.ts - 与路由配置在同一目录，职责清晰
 */
export default defineComponent({
  name: 'DetailPage',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const { pagetypeSlug } = usePageTypeSlug(route)
    const overrideComponent = shallowRef<any | null>(null)

    // 为覆盖组件准备 context（可选，覆盖组件可独立工作）
    const context = computed(() => ({
      route,
      router,
      pagetypeSlug: pagetypeSlug.value,
      entity: route.params.entity as string,
      id: route.params.id as string
    }))

    onMounted(async () => {
      // 查找详情页覆盖组件
      const detailComp = await resolvePagetypeDetailOverride(pagetypeSlug.value)
      overrideComponent.value = detailComp ? markRaw(detailComp) : null
    })

    // 监听路由参数变化，当 entity 或 id 变化时重新加载覆盖组件
    watch(() => [route.params.entity, route.params.id], async ([newEntity, newId], [oldEntity, oldId]) => {
      if (newEntity !== oldEntity || newId !== oldId) {
        const detailComp = await resolvePagetypeDetailOverride(String(newEntity || pagetypeSlug.value))
        overrideComponent.value = detailComp ? markRaw(detailComp) : null
      }
    }, { immediate: false })

    return () => {
      if (overrideComponent.value) {
        return h(overrideComponent.value, { context: context.value })
      }
      return h(DefaultDetail)
    }
  }
})

