/*
 * @Author: LiZhiWei
 * @Date: 2026-01-19 09:12:33
 * @LastEditors: LiZhiWei
 * @LastEditTime: 2026-01-19 09:12:36
 * @Description:
 */
// plugins/rem.client.ts
export default defineNuxtPlugin((nuxtApp) => {
  const setRem = () => {
    const designWidth = 1920 // 我们的设计稿宽度
    const baseSize = 16 // 我们希望的最大基准值 (1rem = 16px)
    const clientWidth = document.documentElement.clientWidth

    // 核心计算公式：缩放比例 = 当前视宽 / 设计稿宽度
    const remSize = (clientWidth / designWidth) * baseSize

    // 【关键】设置字体大小，并限制其在 12px 到 16px 之间
    // 这意味着：屏幕小于 1920px 时会缩小，大于 1920px 时根字体大小稳定在 16px
    document.documentElement.style.fontSize = `${Math.min(Math.max(remSize, 12), 16)}px`
  }

  let timer: NodeJS.Timeout | null = null
  const setRemDebounced = () => {
    if (timer) clearTimeout(timer)
    timer = setTimeout(setRem, 250) // 防抖优化
  }

  // App 挂载后设置并监听 resize
  nuxtApp.hook('app:mounted', () => {
    setRem()
    window.addEventListener('resize', setRemDebounced)
  })

  // App 卸载前清理
  nuxtApp.hook('app:beforeMount', () => {
    window.removeEventListener('resize', setRemDebounced)
    if (timer) clearTimeout(timer)
  })
})
