<template>
  <div class="agreement">
    <van-nav-bar
      fixed
      :title="title"
      left-arrow
      @click-left="onClickLeft"
      placeholder
      safe-area-inset-top
    />
    <div class="agreementContent">
      <component :is="currentComponent" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { onBeforeMount, shallowRef, ref } from 'vue'
import { useRoute } from 'vue-router'

type AgreementType = 'auth' | 'privacy'

const route = useRoute()
const title = ref('协议')
const currentComponent = shallowRef<any>(null) // ✅ 关键：用 shallowRef 存放组件，避免被代理

// 动态组件映射
const componentsMap: Record<
  AgreementType,
  { title: string; loader: () => Promise<{ default: any }> }
> = {
  auth: { title: '授权协议', loader: () => import('./components/AuthAgreement.vue') },
  privacy: { title: '隐私权政策', loader: () => import('./components/PrivacyAgreement.vue') },
}

onBeforeMount(async () => {
  // 读取 ?type=auth|privacy，兜底为 auth
  const rawType = (route.query.type as string) || 'auth'
  const type = (['auth', 'privacy'].includes(rawType) ? rawType : 'auth') as AgreementType

  const match = componentsMap[type]

  try {
    const mod = await match.loader()
    currentComponent.value = mod.default // ✅ shallowRef 不会触发“组件被做成响应式”的告警
  } catch (e) {
    console.log('err', e)

    // 兜底：加载失败时给出一个简单占位组件
    currentComponent.value = {
      name: 'LoadFailed',
      template: `<div style="color:#f56c6c;">协议内容加载失败，请稍后重试。</div>`,
    }
  }

  title.value = match.title
  document.title = match.title
})

const onClickLeft = () => history.back()
</script>

<style lang="scss" scoped>
.van-nav-bar {
  background-color: #fff;
  border-bottom: 1px solid #f2f2f2;
  font-weight: 600;
}

/* 修改左侧返回图标颜色与大小 */

:deep(.van-icon-arrow-left) {
  color: #0072f8;
  font-size: 28px;
}
.agreementContent {
  padding: 16px;
  overflow-y: auto;
}
</style>
