/**
 * 萝卜BBS - 主应用入口
 * 配置导航、主题、状态管理等
 */

import React, { useEffect, useRef } from 'react';
import { AppState, AppStateStatus, Platform, StyleSheet } from 'react-native';
import { StatusBar } from 'expo-status-bar';
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { SafeAreaProvider } from 'react-native-safe-area-context';
import { PaperProvider } from 'react-native-paper';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import * as Notifications from 'expo-notifications';

// 配置通知处理器 - 必须在应用启动时设置
Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,       // 即使在后台也要显示通知
    shouldPlaySound: true,       // 播放声音
    shouldSetBadge: true,        // 设置角标
    shouldShowBanner: true,      // 显示横幅
    shouldShowList: true,        // 显示通知列表
  }),
});

import MainNavigator from './src/navigation/MainNavigator';
import { paperTheme } from './src/theme';
import AppPromptBar from './src/components/common/AppPromptBar';
import AppDialogHost from './src/components/common/AppDialogHost';
import { installAlertOverride } from './src/services/alertOverride';
// 数据库初始化移到 authStore 中，根据用户ID创建用户专属数据库

// 创建 QueryClient 实例
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      retry: 2,
      staleTime: 5 * 60 * 1000, // 5分钟
    },
  },
});

installAlertOverride();

// 注入全局CSS来移除React Native Web在浏览器中的默认focus outline
if (Platform.OS === 'web') {
  const style = document.createElement('style');
  style.textContent = `
    /* 移除TextInput focus时的浏览器默认outline */
    input:focus, textarea:focus, select:focus {
      outline: none !important;
      outline-width: 0 !important;
      box-shadow: none !important;
    }
    
    /* 移除focus-visible时的默认outline */
    input:focus-visible, textarea:focus-visible {
      outline: none !important;
    }
    
    /* 移除所有:focus相关的默认样式 */
    *:focus {
      outline: none !important;
    }
    
    *:focus-visible {
      outline: none !important;
    }
  `;
  document.head.appendChild(style);
}

export default function App() {
  const appState = useRef<AppStateStatus>(AppState.currentState);
  const notificationResponseListener = useRef<Notifications.EventSubscription | null>(null);

  // 系统通知功能初始化
  useEffect(() => {
    const initNotifications = async () => {
      const { systemNotificationService } = await import('./src/services/systemNotificationService');
      await systemNotificationService.initialize();
      
      // 初始化后台保活服务
      const { initBackgroundService } = await import('./src/services/backgroundService');
      await initBackgroundService();
      
      // 监听 App 状态变化
      const subscription = AppState.addEventListener('change', (nextAppState) => {
        if (
          appState.current.match(/inactive|background/) &&
          nextAppState === 'active'
        ) {
          systemNotificationService.clearBadge();
        }
        appState.current = nextAppState;
      });

      // 监听通知点击响应
      notificationResponseListener.current = Notifications.addNotificationResponseReceivedListener(
        (response) => {
          const data = response.notification.request.content.data;
          void data;
        }
      );
      
      // 监听通知到达（用于前台显示时额外处理）
      const notificationReceivedSubscription = Notifications.addNotificationReceivedListener(
        (notification) => {
          void notification;
        }
      );

      return () => {
        subscription.remove();
        notificationResponseListener.current?.remove();
        notificationReceivedSubscription.remove();
      };
    };

    initNotifications();
  }, []);

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <SafeAreaProvider>
        <PaperProvider theme={paperTheme}>
          <QueryClientProvider client={queryClient}>
            <StatusBar style="light" />
            <MainNavigator />
            <AppPromptBar />
            <AppDialogHost />
          </QueryClientProvider>
        </PaperProvider>
      </SafeAreaProvider>
    </GestureHandlerRootView>
  );
}
