import { Tabs } from 'expo-router'
import { useEffect, useState } from 'react'
import { StatusBar } from 'expo-status-bar'
import { ActivityIndicator, View } from 'react-native'
import { SafeAreaProvider } from 'react-native-safe-area-context'
import { initDatabase } from '../src/db/database'
import { CategoriesProvider } from '../src/features/settings/CategoriesContext'

export default function RootLayout() {
  const [dbReady, setDbReady] = useState(false)

  useEffect(() => {
    initDatabase()
      .then(() => setDbReady(true))
      .catch((err) => {
        console.error('数据库初始化失败:', err)
        setDbReady(true)
      })
  }, [])

  if (!dbReady) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <ActivityIndicator size="large" />
      </View>
    )
  }

  return (
    <SafeAreaProvider>
      <StatusBar style="auto" />
      <CategoriesProvider>
        <Tabs
          screenOptions={{
            headerShown: true,
            tabBarActiveTintColor: '#10B981',
          }}
        >
          <Tabs.Screen
            name="index"
            options={{
              title: '登记',
              tabBarLabel: '登记',
              headerShown: false,
            }}
          />
          <Tabs.Screen
            name="summary"
            options={{
              title: '汇总',
              tabBarLabel: '汇总',
            }}
          />
          <Tabs.Screen
            name="settings"
            options={{
              title: '设置',
              tabBarLabel: '设置',
            }}
          />
        </Tabs>
      </CategoriesProvider>
    </SafeAreaProvider>
  )
}
