import React, { useMemo } from 'react';
import { Text as RNText, StyleSheet } from 'react-native';
import { MAX_FONT_SCALE } from '@/utils/ui/fontScaling';

function normalizeWeight(weight) {
  if (weight == null) return 400;
  if (typeof weight === 'number') return weight;
  const w = String(weight).toLowerCase();
  if (w === 'normal') return 400;
  if (w === 'bold') return 700;
  const n = parseInt(w, 10);
  return Number.isNaN(n) ? 400 : n;
}

function mapFamilyToWeight(family) {
  const f = String(family);
  if (f === 'Regular') return '400';
  if (f === 'Medium') return '500';
  if (f === 'SemiBold') return '600';
  if (f === 'Bold') return '700';
  return undefined;
}

const CUSTOM_FAMILIES = new Set(['Regular', 'Medium', 'SemiBold', 'Bold']);

function pickFontFamilyByWeight(numWeight) {
  const w = Math.max(100, Math.min(900, numWeight));
  if (w <= 450) return 'Regular'; 
  if (w <= 575) return 'Medium'; 
  if (w <= 675) return 'SemiBold';
  return 'Bold'; 
}

export default function CustomText({ style, children, ...rest }) {
  const finalStyle = useMemo(() => {
    const flat = StyleSheet.flatten(style) || {};
    // 全局降级：在部分设备上禁用自定义字体，使用系统默认字体
    const useSystemFont = globalThis.__USE_SYSTEM_FONT__ === true;
    if (useSystemFont) {
      // 若明确设置了我们自定义家族名，移除以回退到系统字体；其他情况保持原样
      const family = flat.fontFamily;
      if (family && CUSTOM_FAMILIES.has(String(family))) {
        const { fontFamily, ...styleWithoutFamily } = flat;
        // 映射自定义 family 到对应的 fontWeight；若已存在 fontWeight，则保留不动
        const mapped = mapFamilyToWeight(family);
        if (styleWithoutFamily.fontWeight == null && mapped) {
          return { ...styleWithoutFamily, fontWeight: mapped };
        }
        return styleWithoutFamily;
      }
      return flat;
    }

    // 没有 fontWeight：在非系统字体情况下，若未显式设置 family，默认使用 Regular；
    // 若外部显式设置了 family（不论是否为自定义家族），一律尊重外部设置。
    if (flat.fontWeight == null) {
      const explicitFamily = flat.fontFamily;
      if (explicitFamily == null) {
        return { ...flat, fontFamily: 'Regular' };
      }
      return flat;
    }

    // 慢速路径（兜底）：存在 fontWeight 时才处理
    const explicitFamily = flat.fontFamily;

    // 若已显式指定字体家族，则不覆写（仅移除 fontWeight）
    const shouldOverride = !explicitFamily;

    if (!shouldOverride) {
      // 只需移除 fontWeight
      const { fontWeight, ...styleWithoutWeight } = flat;
      return styleWithoutWeight;
    }

    // 需要替换 fontFamily
    const weightNum = normalizeWeight(flat.fontWeight);
    const family = pickFontFamilyByWeight(weightNum);
    const { fontWeight, ...styleWithoutWeight } = flat;
    return { ...styleWithoutWeight, fontFamily: family };
  }, [style]);
  return (
    <RNText maxFontSizeMultiplier={MAX_FONT_SCALE} style={finalStyle} {...rest}>
      {children}
    </RNText>
  );
}