import React from 'react';
import { View, StyleSheet, Platform } from 'react-native';
import { BlurView } from 'expo-blur';

// 通用 TabBar 组件：
// - 通过 renderItem 自定义每个 tab 的渲染样式
// - 内置毛玻璃背景与可选覆盖层
export default function TabBar({
  items = [],
  activeKey,
  onTabPress,
  renderItem,
  tintColor,
  badgeCounts = {},
  blurTint = 'light',
  blurIntensity = 80,
  overlayColor = 'rgba(255,255,255,0.78)',
  borderTopColor = 'rgba(60,60,67,0.29)',
  borderTopWidth = 0.3,
  safeBottomInset = 0,
  onLayout,
  containerStyle,
}) {
  return (
    <View
      onLayout={onLayout}
      style={[
        styles.root,
        // 在 Android 上启用硬件加速以降低重绘成本
        Platform.OS === 'android' ? { renderToHardwareTextureAndroid: true } : null,
        // 安卓上不再使用覆盖层，直接以背景色减少一次合成
        Platform.OS === 'android' && overlayColor ? { backgroundColor: overlayColor } : null,
        containerStyle,
      ]}
    >
      {Platform.OS === 'ios' ? (
        <BlurView intensity={blurIntensity} tint={blurTint} style={StyleSheet.absoluteFill} />
      ) : null}
      {overlayColor && Platform.OS === 'ios' ? (
        <View pointerEvents="none" style={[StyleSheet.absoluteFill, { backgroundColor: overlayColor }]} />
      ) : null}
      <View
        style={{
          flexDirection: 'row',
          borderTopWidth: borderTopWidth,
          borderTopColor: borderTopColor,
          paddingBottom: safeBottomInset,
        }}
      >
        {items.map((item) => {
          const focused = activeKey === item.key;
          const badgeCount = badgeCounts[item.key] ?? 0;
          const onPress = () => onTabPress && onTabPress(item.key, item);
          const node = renderItem ? renderItem({ item, focused, onPress, tintColor, badgeCount }) : null;
          return <React.Fragment key={item.key}>{node}</React.Fragment>;
        })}
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  root: {
    position: 'absolute',
    left: 0,
    right: 0,
    bottom: 0,
    zIndex: 1000,
    elevation: 0,
  },
});