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)
    }
  })

  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
