// 引入全局字体缩放配置（必须在组件渲染前执行）
import '@/utils/ui/fontScaling';
// 引入全局路由防抖 Patch
import '@/utils/core/routerPolyfill';
import {
  DarkTheme,
  DefaultTheme,
  ThemeProvider,
} from "@react-navigation/native";
import { Stack } from "expo-router";
import { StatusBar } from "expo-status-bar";
import "react-native-reanimated";
import { TamaguiProvider } from "tamagui";
import config from "@/tamagui.config";
import { useColorScheme } from "@/hooks/useColorScheme";
import { ToastProvider, ToastViewport, useToastController } from "@tamagui/toast";
import { PortalProvider } from "@tamagui/portal";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { CustomToast } from "@/components/common/CustomToast";
import { setGlobalToastController } from "@/utils/ui/toast";
import React, { useEffect, useRef, useMemo } from "react";
import dialogService, { DialogProvider } from "@/utils/ui/dialogService.js";
import { useAuthStore } from '@/stores/auth';
import useAuthRedirectGuard from '@/hooks/router/useAuthRedirectGuard';
// 新增：引入用户隐私同意状态 Store
import { useConsentStore } from '@/stores/consent';
import { useBrand } from '@/utils/core/brand/context'
import { useAppStore } from '@/stores'
import ErrorBoundary from "@/components/debug/ErrorBoundary";
import FloatingDebugger from "@/components/debug/FloatingDebugger";
import { GestureHandlerRootView } from 'react-native-gesture-handler';
import { CustomImagePreviewHost } from '@/components/common/CustomImagePreview';
import { JPushManager } from '@/hooks/push/useJPush.js';
import ConsentGate from '@/components/agreement/ConsentGate';
import ExpoWeChat from 'expo-wechat';
import { RootSiblingParent } from 'react-native-root-siblings';
// 引入国际化资源
import '@/i18n'
import selectService, { SelectProvider } from "@/utils/ui/selectService.js";
import { getLanguagePreference } from '@/i18n'
// 配置日历组件中文语言包
import * as Localization from 'expo-localization';
import { LocaleConfig } from 'react-native-calendars';
import loadingService, { LoadingProvider } from '@/utils/ui/loadingService.js';

import { OTAUpdateManager } from '@/hooks/system/useOTAUpdates.js';
import { Linking } from 'react-native'
import * as LinkingParser from 'expo-linking'
// 引入 JCore，用于国内网络下进行 FCM 通道测试 (不要删掉)
import JCore from 'jcore-react-native';
import { Platform } from 'react-native';
import useAppFonts from '@/hooks/system/useAppFonts.js';
// WeChat 握手 URL 过滤器（仅忽略 SDK 握手 URL，不影响业务深链）
(function installWeChatHandshakeFilter() {
  try {
    if (globalThis.__WX_HANDSHAKE_FILTER_INSTALLED__) return;
    globalThis.__WX_HANDSHAKE_FILTER_INSTALLED__ = true;

    const WX_APPID = process.env.EXPO_PUBLIC_WECHAT_APPID;

    const isHandshake = (url) => {
      if (!url || !WX_APPID) return false;
      try {
        const schemePrefix = `${String(WX_APPID).toLowerCase()}://`;
        if (!String(url).toLowerCase().startsWith(schemePrefix)) return false;

        const parsed = LinkingParser.parse(url);
        const host = parsed?.hostname || '';
        const qp = parsed?.queryParams || {};
        // 识别两类典型握手：resendContextReqByScheme / platformId=wechat + 特征参数
        if (host === 'resendContextReqByScheme') return true;
        if (host?.startsWith?.('platformId=wechat')) return true;
        if (qp?._wechat_sdk_biz_data || qp?.wechat_auth_context_id) return true;
      } catch (_) { }
      return false;
    };

    // patch getInitialURL：过滤冷启动握手 URL
    const originalGetInitialURL = Linking.getInitialURL?.bind(Linking);
    if (typeof originalGetInitialURL === 'function') {
      Linking.getInitialURL = async () => {
        const url = await originalGetInitialURL();
        if (isHandshake(url)) {
          try { console.log('[DeepLink][ignore_initial]', url); } catch (_) { }
          return null;
        }
        return url;
      };
    }

    // patch addEventListener：过滤运行期握手 URL 事件
    const originalAddEventListener = Linking.addEventListener?.bind(Linking);
    if (typeof originalAddEventListener === 'function') {
      Linking.addEventListener = (type, handler) => {
        if (type !== 'url') return originalAddEventListener(type, handler);
        const wrapped = (event) => {
          const url = event?.url;
          if (isHandshake(url)) {
            try { console.log('[DeepLink][ignore]', url); } catch (_) { }
            return; // 忽略，不下发给后续监听者（如导航）
          }
          try { handler?.(event); } catch (_) { }
        };
        return originalAddEventListener('url', wrapped);
      };
    }
  } catch (e) {
    try { console.warn('WeChat handshake filter install failed:', e); } catch (_) { }
  }
})();

LocaleConfig.locales['zh-CN'] = {
  monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  monthNamesShort: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
  dayNames: ['周日', '周一', '周二', '周三', '周四', '周五', '周六'],
  dayNamesShort: ['日', '一', '二', '三', '四', '五', '六'],
  today: '今天'
};
LocaleConfig.locales['en'] = {
  monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  today: 'Today'
};
const deviceLocale = Localization.getLocales()?.[0]?.languageTag || 'zh-CN';
const mapLang = (tag) => (tag?.startsWith('zh') ? 'zh-CN' : 'en');
// 优先使用用户偏好（非 system），否则跟随系统
const savedLangPref = getLanguagePreference?.();
const initialCalendarLocale = savedLangPref && savedLangPref !== 'system'
  ? (savedLangPref.startsWith('zh') ? 'zh-CN' : 'en')
  : mapLang(deviceLocale);
LocaleConfig.defaultLocale = initialCalendarLocale;

// Toast初始化组件
function ToastInitializer() {
  const toastController = useToastController();

  useEffect(() => {
    // 初始化全局toast控制器
    setGlobalToastController(toastController);
  }, [toastController]);

  return null;
}
function DialogInitializer() {
  const dialogRef = useRef(null);

  useEffect(() => {
    // 初始化全局dialog服务
    if (dialogRef.current && dialogRef.current.setDialogState) {
      dialogService.setStateUpdater(dialogRef.current.setDialogState);
    }
  }, []);

  return <DialogProvider ref={dialogRef} />;
}
function SelectInitializer() {
  const selectRef = useRef(null);

  useEffect(() => {
    if (selectRef.current && selectRef.current.setSelectState) {
      selectService.setStateUpdater(selectRef.current.setSelectState);
    }
  }, []);

  return <SelectProvider ref={selectRef} />;
}
// 新增：Loading 初始化组件，将 Provider 的 setState 绑定到服务
function LoadingInitializer() {
  const loadingRef = useRef(null);

  useEffect(() => {
    if (loadingRef.current && loadingRef.current.setLoadingState) {
      loadingService.setStateUpdater(loadingRef.current.setLoadingState);
    }
  }, []);

  return <LoadingProvider ref={loadingRef} />;
}

// OTA 更新检查逻辑已封装为 Hook + Manager 组件，参见 hooks/useOTAUpdates.js

// WeChat 初始化器
function WechatInitializer() {
  useEffect(() => {
    const WECHAT_APPID = process.env.EXPO_PUBLIC_WECHAT_APPID;
    const WECHAT_UNIVERSAL_LINK = process.env.EXPO_PUBLIC_WECHAT_UNIVERSAL_LINK;

    try {
      if (WECHAT_UNIVERSAL_LINK && WECHAT_UNIVERSAL_LINK !== 'YOUR_UNIVERSAL_LINK_OPTIONAL') {
        ExpoWeChat.registerApp(WECHAT_APPID, WECHAT_UNIVERSAL_LINK);
      } else {
        ExpoWeChat.registerApp(WECHAT_APPID);
      }
    } catch (e) {
      console.warn('WeChat registerApp failed:', e);
    }
  }, []);

  return null;
}

// JCore 国家码初始化器（用于国内网络下进行 FCM 通道测试）
function JCoreCountryCodeInitializer() {
  useEffect(() => {
    try {
      const env = process.env.EXPO_PUBLIC_ENV;
      // 仅在 Android 且非生产环境时设置国家码为 US，以便进行 FCM 通道联调测试
      const isProd = env === 'prod' || env?.startsWith?.('prod:')
      if (Platform.OS === 'android' && !isProd) {
        // 这个国家码设置后会强行走FCM通道，绕开国内厂商通道
        // 因此不光要限制在非正式环境的安卓设备，且仅可以在需要时手动打开，以防影响测试国内厂商推送通道
        // JCore?.setCountryCode?.({ code: 'us' });
        // try { console.log('[JCore] setCountryCode("us") for FCM testing'); } catch (_) {}
      }
    } catch (e) {
      try { console.warn('JCore setCountryCode failed:', e); } catch (_) { }
    }
  }, []);
  return null;
}


function useConsentMountControl() {
  // 平台与隐私同意状态
  const isIOS = Platform.OS === 'ios';
  const hasAccepted = useConsentStore((s) => s.accepted);
  // 同意后延迟挂载状态（统一控制 OTA 与推送）
  const [postConsentReady, setPostConsentReady] = React.useState(false);

  // iOS：首次挂载直接就绪（不受同意状态影响，不做延迟）
  React.useEffect(() => {
    if (isIOS) {
      setPostConsentReady(true);
    }
  }, [isIOS]);

  // Android：根据同意状态控制延迟挂载
  React.useEffect(() => {
    if (isIOS) return;
    let timer;
    if (hasAccepted) {
      setPostConsentReady(false);
      timer = setTimeout(() => setPostConsentReady(true), 1000);
    } else {
      setPostConsentReady(false);
    }
    return () => { if (timer) clearTimeout(timer); };
  }, [isIOS, hasAccepted]);

  // 统一渲染条件
  const sensitiveReady = isIOS ? postConsentReady : (hasAccepted && postConsentReady);
  const shouldShowConsentGate = !isIOS;

  return { sensitiveReady, shouldShowConsentGate };
}

export default function RootLayout() {
  const insets = useSafeAreaInsets();
  const colorScheme = useColorScheme();
  const brand = useBrand()
  const brandPrimary = brand?.features?.theme?.primary
  const setPrimary = useAppStore((s) => s.setPrimary)
  // 品牌主色初始化入口：
  // - 不使用 Tamagui Theme 来承载“业务主色”，统一写入 appStore.primary
  // - brandPrimary 由品牌模块注入（brands/<brand>/brand-modules），跟随路由根品牌变化而变化
  // 根据环境切换错误边界：生产环境不启用调试用 ErrorBoundary
  const MaybeBoundary = ErrorBoundary;
  const TelNum = useAuthStore(state => state.user?.TelNum);
  const allowedTelNums = [
    '17630920520',
    '16651298129',
    '18001543293',
    '18100571176'
  ];
  const showDebugger = allowedTelNums.includes(String(TelNum || '').trim());
  const { sensitiveReady, shouldShowConsentGate } = useConsentMountControl();
  // 加载并设置全局字体（默认使用 Regular）
  const fontsLoaded = useAppFonts();
  const [hydrated, setHydrated] = React.useState(useAuthStore.persist.hasHydrated());
  React.useEffect(() => {
    const unsub = useAuthStore.persist.onFinishHydration(() => {
      setHydrated(true);
    });
    return unsub;
  }, []);
  React.useEffect(() => {
    if (brandPrimary) setPrimary(brandPrimary)
  }, [brandPrimary, setPrimary])
  const { isChecking } = useAuthRedirectGuard({ hydrated });

  if (!hydrated || isChecking) {
    return null;
  }

  return (
    <GestureHandlerRootView style={{ flex: 1 }}>
      <RootSiblingParent>
        <MaybeBoundary>
          <TamaguiProvider config={config}>
            <PortalProvider>
              {/* swipeDirection 设置为 up 时，向上滑动手势可以关闭Toast */}
              <ToastProvider swipeDirection="up">
                <ThemeProvider
                  value={colorScheme === "dark" ? DarkTheme : DefaultTheme}
                >
                  {/* 字体可能异步加载，不需要拦截渲染；加载完成后会自动应用 */}
                  <Stack
                    screenOptions={{
                      animation: 'slide_from_right',
                      gestureEnabled: true,
                      gestureDirection: 'horizontal',
                      animationDuration: 250,
                    }}
                  >
                    <Stack.Screen
                      name="login/index"
                      options={{
                        headerShown: false,
                        animation: 'fade',
                      }}
                    />
                    <Stack.Screen
                      name="(tabs)"
                      options={{
                        headerShown: false,
                        animation: 'fade',
                      }}
                    />
                    <Stack.Screen name="+not-found" />
                  </Stack>
                  <StatusBar style="auto" />
                </ThemeProvider>
                {/* 默认 Toast 视口 */}
                <ToastViewport
                  flexDirection="column"
                  top={insets.top}
                  left={insets.left}
                  right={insets.right}
                />
                {/* Toast初始化器 */}
                <ToastInitializer />
                {/* 自定义Toast */}
                <CustomToast />
                {/* Dialog初始化器 */}
                <DialogInitializer />
                {/* Select初始化器 */}
                <SelectInitializer />
                {/* 新增：Loading初始化器 */}
                <LoadingInitializer />
                {/* WeChat 初始化器 */}
                <WechatInitializer />
                {/* JCore 国家码初始化器（FCM 测试用） */}
                <JCoreCountryCodeInitializer />
                {sensitiveReady && <JPushManager />}
                {/* OTA 更新检查器（Hook 封装版）：iOS 直接挂载；Android 同意后且延迟 */}
                {sensitiveReady && <OTAUpdateManager />}
                {/* 悬浮调试工具 */}
                {/* FloatingDebugger 已由 Xenon 接管，取消渲染 */}
                <CustomImagePreviewHost />
                {showDebugger && <FloatingDebugger />}
                {/* JPush Hook 已在顶层调用，根据 sensitiveReady 控制启用 */}
                {/* 首次启动协议 Gate */}
                {shouldShowConsentGate && <ConsentGate />}
              </ToastProvider>
            </PortalProvider>
          </TamaguiProvider>
        </MaybeBoundary>
      </RootSiblingParent>

    </GestureHandlerRootView>
  );
}
