/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 *
 * @format
 */

import React, { useEffect, useState } from 'react';
import { ActivityIndicator, StatusBar, View, StyleSheet } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { NavigationContainer, DefaultTheme, DarkTheme } from '@react-navigation/native';
import { Provider, useDispatch } from 'react-redux';

import store, { type AppDispatch } from './src/store';
import AppNavigator from './src/navigation';
import { ThemeProvider, useTheme } from './src/theme/ThemeProvider';
import { loadAgents } from './src/store/agentsSlice';
import { rehydrateChat } from './src/store/chatSlice';
import { loadChatState } from './src/store/persistence';

function InnerApp() {
  const { scheme, colors } = useTheme();
  const isDarkMode = scheme === 'dark';
  const dispatch = useDispatch<AppDispatch>();
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const init = async () => {
      // Run both in parallel — neither depends on the other.
      const [persisted] = await Promise.all([
        loadChatState(),
        dispatch(loadAgents()),
      ]);
      if (persisted) {
        dispatch(rehydrateChat(persisted));
      }
      setReady(true);
    };
    init();
  }, [dispatch]);

  const navTheme = isDarkMode
    ? {
        ...DarkTheme,
        colors: {
          ...DarkTheme.colors,
          background: colors.background,
          card: colors.card,
        },
      }
    : {
        ...DefaultTheme,
        colors: {
          ...DefaultTheme.colors,
          background: colors.background,
          card: colors.card,
        },
      };

  const containerStyle = { backgroundColor: colors.background };

  if (!ready) {
    return (
      <View style={[styles.center, containerStyle]}>
        <ActivityIndicator size="large" color={colors.primary} />
      </View>
    );
  }

  return (
    <>
      <StatusBar
        barStyle={isDarkMode ? 'light-content' : 'dark-content'}
        hidden={true}
      />
      <NavigationContainer theme={navTheme}>
        <AppNavigator />
      </NavigationContainer>
    </>
  );
}

function App() {
  return (
    <Provider store={store}>
      <SafeAreaProvider>
        <ThemeProvider>
          <InnerApp />
        </ThemeProvider>
      </SafeAreaProvider>
    </Provider>
  );
}

const styles = StyleSheet.create({
  center: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;
