import { ref, onMounted, onUnmounted } from 'vue'

export const useIsMobile = () => {
  const isMobile = ref(false)

  const checkDevice = () => {
    // 1. 现代 Client Hints API（Chrome/Edge 最准）
    if (navigator.userAgentData?.mobile !== undefined) {
      isMobile.value = navigator.userAgentData.mobile
      return
    }

    // 2. 综合判断（兼容所有浏览器）
    const ua = navigator.userAgent.toLowerCase()
    const mobileRegex = /android|webos|iphone|ipad|ipod|blackberry|iemobile|opera mini/i

    const hasTouch = 'ontouchstart' in window || navigator.maxTouchPoints > 1
    const smallScreen = window.innerWidth <= 768 // 你可以改成 1024 等

    isMobile.value = mobileRegex.test(ua) || (hasTouch && smallScreen)
  }

  onMounted(() => {
    checkDevice()
    window.addEventListener('resize', checkDevice)
    window.addEventListener('orientationchange', checkDevice) // 手机旋转必备
  })

  onUnmounted(() => {
    window.removeEventListener('resize', checkDevice)
    window.removeEventListener('orientationchange', checkDevice)
  })

  return { isMobile }
}
