import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.tsx";
import { AppWrapper } from "./components/common/PageMeta.tsx";
import { AuthProvider } from "@/contexts/AuthContext.tsx";
import { SiteSettingsProvider } from "@/contexts/SiteSettingsContext.tsx";
import { initPerformanceMonitoring } from "@/utils/performance";
import ErrorBoundary from "@/components/common/ErrorBoundary.tsx";

// 初始化性能监控
initPerformanceMonitoring();

// 全局错误处理器：忽略 ResizeObserver 的良性错误
if (typeof window !== 'undefined') {
  // 忽略 ResizeObserver 循环错误（这是一个良性的浏览器警告，不影响功能）
  window.addEventListener('error', (e) => {
    if (e.message === 'ResizeObserver loop completed with undelivered notifications.' ||
        e.message === 'ResizeObserver loop limit exceeded') {
      e.stopImmediatePropagation();
      e.preventDefault();
      return;
    }
  });
  
  console.log('[全局错误捕获器] 已初始化');
}

// 补救措施：确保在某些特定移动端浏览器（如百度APP、微信浏览器）中，页面加载后 body 的 pointer-events 始终为 auto
// 防止某些第三方组件库（如 Radix UI）意外锁定 body 的点击权限
if (typeof window !== 'undefined') {
  // 检测浏览器类型
  const isBaiduBrowser = /baiduboxapp|baidubrowser/i.test(navigator.userAgent);
  const isWeChatBrowser = /micromessenger/i.test(navigator.userAgent);
  
  // 输出环境信息用于调试
  console.log('[环境检测] User Agent:', navigator.userAgent);
  console.log('[环境检测] 是否为百度浏览器:', isBaiduBrowser);
  console.log('[环境检测] 是否为微信浏览器:', isWeChatBrowser);
  console.log('[环境检测] 视口宽度:', window.innerWidth);
  console.log('[环境检测] 视口高度:', window.innerHeight);
  
  // 百度浏览器特殊处理：修复 History API 可能的兼容性问题
  if (isBaiduBrowser) {
    const originalPushState = window.history.pushState;
    const originalReplaceState = window.history.replaceState;
    
    window.history.pushState = function(...args) {
      console.log('[百度浏览器兼容] pushState 被调用:', args);
      try {
        originalPushState.apply(window.history, args);
        console.log('[百度浏览器兼容] pushState 成功');
      } catch (e) {
        console.error('[百度浏览器兼容] pushState 失败:', e);
      }
    };
    
    window.history.replaceState = function(...args) {
      console.log('[百度浏览器兼容] replaceState 被调用:', args);
      try {
        originalReplaceState.apply(window.history, args);
        console.log('[百度浏览器兼容] replaceState 成功');
      } catch (e) {
        console.error('[百度浏览器兼容] replaceState 失败:', e);
      }
    };
    
    console.log('[百度浏览器兼容模式] History API 补丁已加载');

    // 注入全局 CSS 补丁，确保关键交互元素在百度 APP 等环境中的层级最高且可点击
    const style = document.createElement('style');
    style.id = 'baidu-compat-patch';
    style.textContent = `
      * { -webkit-tap-highlight-color: transparent !important; }
      body, html { -webkit-overflow-scrolling: touch !important; touch-action: manipulation !important; }
      header, nav, .fixed, .sticky, #mobile-nav, #header-container { 
        pointer-events: auto !important; 
        z-index: 2147483647 !important; 
      }
      #app-root, #root { pointer-events: auto !important; }
    `;
    document.head.appendChild(style);
    console.log('[百度浏览器兼容模式] 全局 CSS 补丁已注入');
  }
  
  // 微信浏览器特殊处理
  if (isWeChatBrowser) {
    console.log('[微信浏览器兼容模式] 已启用');
    
    // 禁用微信浏览器的字体缩放功能
    const disableWeChatFontResize = () => {
      if (typeof WeixinJSBridge !== 'undefined') {
        // 禁用微信字体缩放
        WeixinJSBridge.invoke('setFontSizeCallback', { fontSize: 0 });
        // 重写字体大小设置
        WeixinJSBridge.on('menu:setfont', () => {
          WeixinJSBridge?.invoke('setFontSizeCallback', { fontSize: 0 });
        });
        // 注意：不要调用 hideOptionMenu，这会隐藏所有菜单包括分享功能
        console.log('[微信浏览器兼容模式] 已禁用字体缩放');
      } else {
        // 如果 WeixinJSBridge 还未加载，等待加载完成
        document.addEventListener('WeixinJSBridgeReady', () => {
          if (typeof WeixinJSBridge !== 'undefined') {
            WeixinJSBridge.invoke('setFontSizeCallback', { fontSize: 0 });
            WeixinJSBridge.on('menu:setfont', () => {
              WeixinJSBridge?.invoke('setFontSizeCallback', { fontSize: 0 });
            });
            console.log('[微信浏览器兼容模式] 已禁用字体缩放（延迟加载）');
          }
        });
      }
    };
    
    // 立即执行
    disableWeChatFontResize();
    
    // 页面加载完成后再次执行
    window.addEventListener('load', disableWeChatFontResize);
    
    // DOMContentLoaded 时也执行一次
    document.addEventListener('DOMContentLoaded', disableWeChatFontResize);
  }
  
  window.addEventListener('load', () => {
    setTimeout(() => {
      document.body.style.pointerEvents = 'auto';
      console.log('[兼容性修复] body pointer-events 已设置为 auto');
      
      // 额外补救：确保所有交互元素都可以响应点击
      const interactiveElements = document.querySelectorAll('a, button, [role="button"]');
      interactiveElements.forEach(el => {
        (el as HTMLElement).style.pointerEvents = 'auto';
      });
      console.log('[兼容性修复] 已修复', interactiveElements.length, '个交互元素');
      
      // 百度浏览器特殊处理：强制启用触摸事件
      if (isBaiduBrowser) {
        document.body.style.touchAction = 'manipulation';
        console.log('[百度浏览器兼容模式] 已启用触摸事件优化');
      }
    }, 500);
  });
  
  // 监听 DOM 变化，确保新添加的元素也能正常交互
  const observer = new MutationObserver(() => {
    const interactiveElements = document.querySelectorAll('a, button, [role="button"]');
    interactiveElements.forEach(el => {
      const htmlEl = el as HTMLElement;
      if (htmlEl.style.pointerEvents === 'none') {
        htmlEl.style.pointerEvents = 'auto';
      }
    });
  });
  
  window.addEventListener('DOMContentLoaded', () => {
    observer.observe(document.body, {
      childList: true,
      subtree: true,
      attributes: true,
      attributeFilter: ['style']
    });
    console.log('[兼容性修复] DOM 监听器已启动');
  });
}

// 添加加载失败的fallback处理
const rootElement = document.getElementById("root");
if (!rootElement) {
  console.error('[致命错误] 找不到 root 元素');
  document.body.innerHTML = `
    <div style="display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; background: #f5f5f5;">
      <div style="max-width: 400px; padding: 24px; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        <h1 style="color: #e11d48; margin: 0 0 16px 0; font-size: 20px;">页面加载失败</h1>
        <p style="color: #666; margin: 0 0 16px 0; font-size: 14px;">抱歉，页面加载时遇到了问题。请尝试刷新页面。</p>
        <button onclick="window.location.reload()" style="width: 100%; padding: 10px; background: #e11d48; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;">刷新页面</button>
      </div>
    </div>
  `;
} else {
  try {
    createRoot(rootElement).render(
      <StrictMode>
        <ErrorBoundary>
          <SiteSettingsProvider>
            <AuthProvider>
              <AppWrapper>
                <App />
              </AppWrapper>
            </AuthProvider>
          </SiteSettingsProvider>
        </ErrorBoundary>
      </StrictMode>
    );
    console.log('[应用启动] React 应用已成功挂载');
  } catch (error) {
    console.error('[致命错误] React 应用挂载失败:', error);
    document.body.innerHTML = `
      <div style="display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 20px; background: #f5f5f5;">
        <div style="max-width: 400px; padding: 24px; background: white; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
          <h1 style="color: #e11d48; margin: 0 0 16px 0; font-size: 20px;">应用启动失败</h1>
          <p style="color: #666; margin: 0 0 16px 0; font-size: 14px;">抱歉，应用启动时遇到了问题。请尝试刷新页面或联系技术支持。</p>
          <button onclick="window.location.reload()" style="width: 100%; padding: 10px; background: #e11d48; color: white; border: none; border-radius: 4px; cursor: pointer; font-size: 14px;">刷新页面</button>
        </div>
      </div>
    `;
  }
}

