import React, { useState } from 'react'
import Taro, { useLaunch, useDidShow, useDidHide, getSystemInfoSync } from '@tarojs/taro'
import { View } from '@tarojs/components'
import { ConfigProvider } from '@nutui/nutui-react-taro'
import zhCN from '@nutui/nutui-react-taro/dist/locales/zh-CN'
import AppContext from './contexts/AppContext'
import { UserProvider } from './contexts/UserContext'
import { CartProvider } from './contexts/CartContext'
import ErrorBoundary from './components/ErrorBoundary'
import './app.scss'

type AppProps = {
  children?: React.ReactNode
}

function App(props: AppProps) {
  const [theme, setTheme] = useState<'light' | 'dark'>('light')

  useLaunch(() => {
    const systemInfo = getSystemInfoSync()
    const savedTheme = Taro.getStorageSync('app_theme')
    if (savedTheme === 'light' || savedTheme === 'dark') {
      setTheme(savedTheme)
    }

    // 微信隐私协议（基础库 3.16.1+ 强制）
    // 当调用 getPhoneNumber / chooseImage 等敏感 API 且用户未同意隐私协议时，
    // 微信会触发此回调。我们展示自定义弹窗，用户点击同意后再 resolve，
    // 否则微信会拒绝后续敏感 API 调用。
    const wxAny: any = Taro
    if (typeof wxAny.onNeedPrivacyAuthorization === 'function') {
      wxAny.onNeedPrivacyAuthorization((resolve: any) => {
        wxAny.getPrivacySetting({
          success: (setting: any) => {
            const privacyContractName = setting?.privacyContractName || '《用户隐私保护指引》'
            Taro.showModal({
              title: '隐私协议授权',
              content: `为提供完整服务，需您同意 ${privacyContractName}。点击同意后可继续使用手机号快捷登录、相册等功能。`,
              confirmText: '同意',
              cancelText: '拒绝',
              confirmColor: '#07c160',
              success: (res) => {
                if (res.confirm) {
                  resolve({ event: 'agree', button: 'agree' })
                } else {
                  resolve({ event: 'disagree', button: 'disagree' })
                }
              },
              fail: () => {
                resolve({ event: 'disagree', button: 'disagree' })
              },
            })
          },
          fail: () => {
            // 获取设置失败时，默认 resolve 同意，避免流程阻塞
            resolve({ event: 'agree', button: 'agree' })
          },
        })
      })
    }
  })

  useDidShow(() => {})

  useDidHide(() => {})

  const toggleTheme = () => {
    setTheme(prev => {
      const next = prev === 'light' ? 'dark' : 'light'
      try { Taro.setStorageSync('app_theme', next) } catch { /* ignore */ }
      return next
    })
  }

  return (
    <AppContext.Provider value={{ theme, toggleTheme }}>
      <UserProvider>
        <CartProvider>
          <ConfigProvider locale={zhCN}>
            <ErrorBoundary>
              <View className={theme === 'dark' ? 'dark' : ''}>
                {props.children}
              </View>
            </ErrorBoundary>
          </ConfigProvider>
        </CartProvider>
      </UserProvider>
    </AppContext.Provider>
  )
}

export default App
