import 'react-native-gesture-handler';

import React, { createContext, useContext, useRef, useState } from 'react';
import { Platform, StyleSheet, View } from 'react-native';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { MMKV } from 'react-native-mmkv';
import { WebView } from 'react-native-webview';

import ApplicationNavigator from '@/navigation/Application';
import { ThemeProvider } from '@/theme';
import '@/translations';

export const queryClient = new QueryClient({
  defaultOptions: {
    mutations: {
      retry: false,
    },
    queries: {
      retry: false,
    },
  },
});

export const storage = new MMKV();

// WebView预加载上下文
interface WebViewContextType {
  webViewRef: React.RefObject<WebView | null>;
  showWebView: boolean;
  setShowWebView: (show: boolean) => void;
}

const WebViewContext = createContext<WebViewContextType | null>(null);

export const useWebViewContext = () => {
  const context = useContext(WebViewContext);
  if (!context) {
    throw new Error('useWebViewContext must be used within WebViewProvider');
  }
  return context;
};

// 配置常量
const DEFAULT_URL = 'http://localhost:5173';

// WebView用户代理
const USER_AGENT = Platform.select({
  ios: 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Mobile/15E148 Safari/604.1',
  android: 'Mozilla/5.0 (Linux; Android 10; SM-G973F) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.120 Mobile Safari/537.36',
});

function App() {
  const webViewRef = useRef<WebView>(null);
  const [showWebView, setShowWebView] = useState(false);

  return (
    <GestureHandlerRootView style={styles.container}>
      <QueryClientProvider client={queryClient}>
        <ThemeProvider storage={storage}>
          <WebViewContext.Provider value={{ webViewRef, showWebView, setShowWebView }}>
            <View style={styles.container}>
              <ApplicationNavigator />
              
              {/* 预加载的WebView，通过样式控制显示/隐藏 */}
              <View style={[
                styles.webViewContainer,
                showWebView ? styles.webViewVisible : styles.webViewHidden,
              ]}>
                <WebView
                  ref={webViewRef}
                  source={{ uri: DEFAULT_URL }}
                  style={styles.webView}
                  userAgent={USER_AGENT}
                  javaScriptEnabled={true}
                  domStorageEnabled={true}
                  startInLoadingState={true}
                  scalesPageToFit={true}
                  allowsBackForwardNavigationGestures={Platform.OS === 'ios'}
                />
              </View>
            </View>
          </WebViewContext.Provider>
        </ThemeProvider>
      </QueryClientProvider>
    </GestureHandlerRootView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  webViewContainer: {
    position: 'absolute',
    top: 0,
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
  },
  webViewVisible: {
    opacity: 1,
  },
  webViewHidden: {
    opacity: 0,
    transform: [{ translateX: -9999 }], // 偏移到屏幕外
  },
  webView: {
    flex: 1,
  },
});

export default App;
