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+ 强制）
    // 当小程序使用 chooseImage/chooseMedia/getLocation 等接口时，若用户未在隐私协议中同意，
    // 微信会回调这里，开发者必须弹一个自定义的协议确认弹窗，并提供"同意并继续"/"拒绝"两个分支。
    const wxAny: any = Taro
    if (typeof wxAny.onNeedPrivacyAuthorization === 'function') {
      wxAny.onNeedPrivacyAuthorization((resolve: any) => {
        wxAny.showModal({
          title: '用户隐私协议',
          content: '为了正常使用图片上传、拍照、定位等功能，需要您同意《用户隐私协议》。',
          confirmText: '同意',
          cancelText: '拒绝',
          success: (modalRes: any) => {
            if (modalRes.confirm) {
              resolve({ event: 'agree', button: 'agree' })
            } else {
              resolve({ event: 'disagree' })
            }
          },
          fail: () => resolve({ event: 'disagree' }),
        })
      })
    }
  })

  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
