import React, { useEffect, useState } from 'react';
import { View, Text, StyleSheet, ActivityIndicator } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import TrackPlayer from 'react-native-track-player';
import { ThemeProvider } from './src/theme/ThemeContext';
import { RootNavigator } from './src/navigation/RootNavigator';
import { usePlayerSync } from './src/hooks/usePlayer';
import { useLibraryStore } from './src/store/libraryStore';
import { setupPlayer, PlaybackService } from './src/utils/audioService';

// Register playback service (must be outside component)
TrackPlayer.registerPlaybackService(() => PlaybackService);

function AppContent() {
  const [isPlayerReady, setIsPlayerReady] = useState(false);
  const loadLibrary = useLibraryStore((s) => s.loadLibrary);

  // Sync player state with our store
  usePlayerSync();

  useEffect(() => {
    async function init() {
      try {
        await setupPlayer();
        await loadLibrary();
        setIsPlayerReady(true);
      } catch (error) {
        console.error('Failed to initialize:', error);
        setIsPlayerReady(true); // Show app anyway
      }
    }
    init();
  }, [loadLibrary]);

  if (!isPlayerReady) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#1DB954" />
        <Text style={styles.loadingText}>Loading Vinyl...</Text>
      </View>
    );
  }

  return <RootNavigator />;
}

export default function App() {
  return (
    <SafeAreaProvider>
      <ThemeProvider>
        <AppContent />
      </ThemeProvider>
    </SafeAreaProvider>
  );
}

const styles = StyleSheet.create({
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#121212',
  },
  loadingText: {
    color: '#fff',
    marginTop: 16,
    fontSize: 16,
  },
});
