import { Tabs } from 'expo-router';
import React from 'react';
import { TabBarIcon } from '@/components/navigation/TabBarIcon';
import { Colors } from '@/constants/Colors';
import { useColorScheme } from '@/hooks/useColorScheme';
import { HapticTab } from '@/components/HapticTab';
import { webSocketManager, WebSocketStatus } from '@/lib/websocket-util';
import { useEffect, useState } from 'react';
import { Platform } from 'react-native';

// 只在iOS平台上导入TabBarBackground组件
const TabBarBackground = Platform.OS === 'ios' ? require('@/components/ui/TabBarBackground').default : null;

export default function MainLayout() {
  const colorScheme = useColorScheme();
  const [wsStatus, setWsStatus] = useState<WebSocketStatus>('disconnected');

  useEffect(() => {
    const handleStatusChange = (status: WebSocketStatus) => {
      setWsStatus(status);
    };
    webSocketManager.subscribeStatus(handleStatusChange);
    return () => {
      webSocketManager.unsubscribeStatus(handleStatusChange);
    };
  }, []);

  // 只在iOS平台上使用TabBarBackground
  const renderTabBarBackground = () => {
    if (Platform.OS === 'ios' && TabBarBackground) {
      return <TabBarBackground />;
    }
    return null;
  };

  return (
    <>
      <Tabs
        screenOptions={{
          tabBarActiveTintColor: Colors[colorScheme ?? 'light'].tint,
          headerShown: false,
          tabBarBackground: renderTabBarBackground, // 使用自定义背景
          tabBarButton: HapticTab, // 添加触觉反馈
        }}
      >
        <Tabs.Screen
          name="(tabs)"  // 这将渲染 (tabs) 目录下的 _layout.tsx
          options={{
            headerShown: false,
            title: 'Home',
            tabBarIcon: ({ color }) => <TabBarIcon name="home" color={color} />,
          }}
        />
      </Tabs>
    </>
  );
}
