import { useEffect, useState } from 'react'
import Taro from '@tarojs/taro'
import { View, Button, Text } from '@tarojs/components'
import { privacyManager } from '@/utils/privacy'
import './index.scss'

/**
 * 微信隐私协议授权弹窗（基础库 3.16.1+ 强制）
 * 必须使用 open-type="agreePrivacyAuthorization" 的 Button 组件，
 * 用户点击后微信才会真正认为隐私协议已授权，后续敏感 API 才能调用。
 */
const PrivacyModal = () => {
  const [visible, setVisible] = useState(false)
  const [contractName, setContractName] = useState(privacyManager.getPrivacyContractName())

  useEffect(() => {
    privacyManager.setShowCallback((show) => {
      setVisible(show)
      if (show) {
        setContractName(privacyManager.getPrivacyContractName())
      }
    })
  }, [])

  if (!visible) return null

  return (
    <View className='privacy-modal'>
      <View className='privacy-modal__mask' />
      <View className='privacy-modal__content'>
        <Text className='privacy-modal__title'>隐私协议授权</Text>
        <Text className='privacy-modal__desc'>
          {`为提供完整服务，需您同意 ${contractName}。点击同意后可继续使用手机号快捷登录、相册等功能。`}
        </Text>
        <View className='privacy-modal__footer'>
          <Button
            className='privacy-modal__btn'
            onClick={() => privacyManager.disagree()}
          >
            拒绝
          </Button>
          <Button
            className='privacy-modal__btn privacy-modal__btn--primary'
            openType='agreePrivacyAuthorization'
            onAgreePrivacyAuthorization={() => privacyManager.agree()}
            onDisagreePrivacyAuthorization={() => privacyManager.disagree()}
          >
            同意
          </Button>
        </View>
      </View>
    </View>
  )
}

export default PrivacyModal
