import React, {useEffect} from 'react';
import {GestureHandlerRootView} from 'react-native-gesture-handler';
import {SafeAreaProvider} from 'react-native-safe-area-context';
import {StyleSheet} from 'react-native';
import AppNavigator from './src/navigation/AppNavigator';
import {useAddonStore} from './src/store/addonStore';
import {useSettingsStore} from './src/store/settingsStore';
import {useLibraryStore} from './src/store/libraryStore';
import {useWatchLaterStore} from './src/store/watchLaterStore';
import {preloadTorrent} from './src/utils/torrentStreamService';

export default function App() {
  const {load: loadAddons} = useAddonStore();
  const {load: loadSettings} = useSettingsStore();
  const {load: loadLibrary} = useLibraryStore();
  const {load: loadWatchLater} = useWatchLaterStore();
  const watchLaterItems = useWatchLaterStore(s => s.items);
  const watchLaterLoaded = useWatchLaterStore(s => s.loaded);
  const updateProgress = useWatchLaterStore(s => s.updateProgress);
  const updateStatus = useWatchLaterStore(s => s.updateStatus);

  useEffect(() => {
    loadAddons();
    loadSettings();
    loadLibrary();
    loadWatchLater();
  }, [loadAddons, loadSettings, loadLibrary, loadWatchLater]);

  // Auto-resume queued downloads after app restart
  useEffect(() => {
    if (!watchLaterLoaded) return;
    const queued = watchLaterItems.filter(i => i.status === 'queued');
    if (queued.length === 0) return;
    for (const item of queued) {
      // Keep existing progress value — libtorrent will hash-check existing
      // data on disk and resume from where it left off, so don't reset to 0
      updateStatus(item.infoHash, 'resolving');
      preloadTorrent(item.infoHash, p => {
        if (p.status === 'complete') {
          updateProgress(item.infoHash, 100, 'ready');
        } else {
          updateProgress(
            item.infoHash,
            p.progress,
            p.status === 'resolving' ? 'resolving' : 'downloading',
          );
        }
      }).catch(e => {
        updateStatus(item.infoHash, 'error', String(e));
      });
    }
    // Only run once when loaded — don't re-trigger on item changes
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [watchLaterLoaded]);

  return (
    <GestureHandlerRootView style={styles.root}>
      <SafeAreaProvider>
        <AppNavigator />
      </SafeAreaProvider>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  root: {flex: 1},
});
