// Main App - Jiucun Wang Mobile Prototype

const { useState, useEffect, useCallback, useRef } = React;

// Module to nav type mapping
const MODULE_NAV_MAP = {
  home: 'default',
  feed: 'default',
  messages: 'default',
  'article-list': 'default',
  'article-detail': 'default',
  archive: 'default',
  apps: 'default',
  'my-archive': 'default',
  'my-articles': 'default',
  'admin-seo': 'default',
  'mall': 'default',
  'mall-product': 'default',
  'mall-cart': 'default',
  'mall-order-confirm': 'default',
  'mall-orders': 'default',
  'mall-pretty-numbers': 'default',
  space: 'default',
  credentials: 'default',
  profile: 'default',
  video: 'video',
  memorial: 'memorial',
  love: 'love',
  accounting: 'none',
  'accounting-personal': 'accounting',
  'accounting-enterprise': 'accounting-enterprise',
  im: 'im',
  member: 'member',
  yellowpages: 'yellowpages',
  distribution: 'distribution',
  'pipe-income': 'default',
  'pipe-team': 'default',
  'pipe-income-detail': 'default',
  'pipe-agent': 'default',
  'pipe-third': 'default',
  qrcode: 'none',
  qa: 'none',
  'qa-experts': 'none',
  'qa-question': 'none',
  'qa-consult': 'none',
  wiki: 'none',
  'wiki-entry': 'none',
  'wiki-edit': 'none',
  'admin-wiki': 'default',
  'space-square': 'default',
};

// Theme class mapping
const MODULE_THEME_MAP = {
  home: '',
  feed: '',
  messages: '',
  'article-list': '',
  'article-detail': '',
  archive: '',
  apps: '',
  'my-archive': '',
  'my-articles': '',
  'admin-seo': '',
  credentials: '',
  profile: '',
  video: 'theme-video',
  memorial: 'theme-memorial',
  love: 'theme-love',
  accounting: 'theme-accounting',
  'accounting-personal': 'theme-accounting',
  'accounting-enterprise': 'theme-accounting',
  im: 'theme-im',
  member: 'theme-member',
  yellowpages: 'theme-yellowpages',
  sitemap: 'theme-sitemap',
  orders: 'theme-orders',
  distribution: 'theme-distribution',
  typesetting: '',
  qrcode: '',
  qa: '',
  'qa-experts': '',
  'qa-question': '',
  'qa-consult': '',
  wiki: '',
  'wiki-entry': '',
  'wiki-edit': '',
  'admin-wiki': '',
};

function App() {
  const [currentPage, setCurrentPage] = useState('home');
  const [pageHistory, setPageHistory] = useState(['home']);
  const [pageParams, setPageParams] = useState({});
  const [showPublish, setShowPublish] = useState(false);
  const [showAccountingBill, setShowAccountingBill] = useState(false);
  const [showPublishFeed, setShowPublishFeed] = useState(false);
  const [showPublishArticle, setShowPublishArticle] = useState(false);
  const [showArticlePublish, setShowArticlePublish] = useState(false);
  const [showCSModal, setShowCSModal] = useState(false);
  const [showIMNew, setShowIMNew] = useState(false);
  const [showMemberRecharge, setShowMemberRecharge] = useState(false);
  const [showYPNew, setShowYPNew] = useState(false);
  const [showOrderNew, setShowOrderNew] = useState(false);
  const [showDistGenerate, setShowDistGenerate] = useState(false);
  const [showVideoUpload, setShowVideoUpload] = useState(false);
  const [toast, setToast] = useState({ show: false, msg: '' });
  const [currentUser, setCurrentUser] = useState(null);
  const [authModal, setAuthModal] = useState({ show: false, mode: 'choice', pendingAction: null });
  const toastTimerRef = useRef(null);

  // Initialize API + load current user + load SEO settings
  useEffect(() => {
    if (window.API) {
      window.API.init().then(() => {
        window.API.get('/user/current').then(res => {
          if (res.success && res.data) setCurrentUser(res.data);
          else setCurrentUser(null);
        });
        // Load SEO settings and apply initial
        if (window.SEO) {
          window.SEO.loadSettings();
        }
      });
    }
  }, []);

  // Apply page-specific SEO when currentPage changes
  useEffect(() => {
    if (window.SEO) {
      window.SEO.applyPageSEO(currentPage);
    }
  }, [currentPage]);

  // Module inner tab state - maps page -> activeTab
  const [innerTabs, setInnerTabs] = useState({
    memorial: 'altar',
    love: 'dynamic',
    accounting: 'bills',
    'accounting-personal': 'bills',
    im: 'chats',
    member: 'home',
    yellowpages: 'list',
    sitemap: 'home',
    orders: 'home',
    distribution: 'home',
    archive: 'all',
  });

  const navType = MODULE_NAV_MAP[currentPage] || 'default';
  const themeClass = MODULE_THEME_MAP[currentPage] || '';

  const showToast = useCallback((msg) => {
    setToast({ show: true, msg });
    if (toastTimerRef.current) clearTimeout(toastTimerRef.current);
    toastTimerRef.current = setTimeout(() => {
      setToast({ show: false, msg: '' });
    }, 1800);
  }, []);

  // 全局清理：路由切换前移除所有可能残留的全屏遮罩元素，防止卡死
  const cleanupOverlays = useCallback(() => {
    try {
      // 清理已知的管道模块弹窗
      const pipeModals = document.querySelectorAll('[data-pipe-modal="1"]');
      pipeModals.forEach(el => el.remove());

      // 清理所有 fixed 定位的全屏遮罩（zIndex > 100 且尺寸接近全屏）
      const all = document.querySelectorAll('div');
      for (let i = 0; i < all.length; i++) {
        const el = all[i];
        try {
          const style = window.getComputedStyle(el);
          if (style.position !== 'fixed') continue;
          const z = parseInt(style.zIndex || '0', 10);
          if (z < 100) continue;
          const rect = el.getBoundingClientRect();
          const vw = window.innerWidth;
          const vh = window.innerHeight;
          // 元素覆盖全屏且是半透明/透明背景（典型遮罩特征）
          if (rect.width >= vw * 0.9 && rect.height >= vh * 0.9) {
            const bg = style.backgroundColor || '';
            // 有透明背景的遮罩 或 无内容的空 overlay
            if (bg.includes('rgba') || bg === 'transparent' || el.children.length <= 1) {
              el.remove();
            }
          }
        } catch (e) {}
      }

      // 恢复 body 滚动
      document.body.style.overflow = '';
      document.body.style.position = '';
    } catch (e) {
      console.warn('[cleanupOverlays] failed:', e);
    }
  }, []);

  const navigate = useCallback((page, params) => {
    cleanupOverlays();
    if (params) setPageParams(prev => ({ ...prev, [page]: params }));
    setCurrentPage(page);
    setPageHistory(prev => [...prev, page]);
    setTimeout(() => {
      const containers = document.querySelectorAll('.page-container');
      containers.forEach(c => { c.scrollTop = 0; });
    }, 50);
  }, [cleanupOverlays]);

  const goBack = useCallback(() => {
    if (pageHistory.length > 1) {
      cleanupOverlays();
      const newHistory = pageHistory.slice(0, -1);
      setPageHistory(newHistory);
      setCurrentPage(newHistory[newHistory.length - 1]);
    }
  }, [pageHistory]);

  // 登录/注册相关
  const openAuthModal = useCallback((mode = 'choice', pendingAction = null) => {
    setAuthModal({ show: true, mode, pendingAction });
  }, []);

  const closeAuthModal = useCallback(() => {
    setAuthModal({ show: false, mode: 'choice', pendingAction: null });
  }, []);

  const handleAuthSuccess = useCallback(async (user) => {
    setCurrentUser(user);
    const pending = authModal.pendingAction;
    closeAuthModal();
    // 执行登录前被拦截的操作
    if (pending && typeof pending === 'function') {
      setTimeout(() => pending(), 200);
    }
  }, [authModal, closeAuthModal]);

  const handleLogout = useCallback(async () => {
    if (window.API) {
      await window.API.post('/user/logout');
    }
    setCurrentUser(null);
    showToast('已退出登录');
  }, [showToast]);

  // 权限拦截：未登录时弹出登录框，登录成功后执行原操作
  const requireLogin = useCallback((action, mode = 'choice') => {
    if (currentUser && currentUser.id) {
      if (typeof action === 'function') action();
      return true;
    }
    openAuthModal(mode, action);
    return false;
  }, [currentUser, openAuthModal]);

  const setInnerTab = useCallback((page, tabId) => {
    setInnerTabs(prev => ({ ...prev, [page]: tabId }));
  }, []);

  // Handle bottom nav clicks
  const handleNav = useCallback((navId) => {
    // Map navId -> action per module
    const navActions = {
      // Default nav
      'article-list': () => navigate('article-list'),
      archive: () => navigate('archive'),
      apps: () => navigate('apps'),
      feed: () => navigate('feed'),
      messages: () => requireLogin(() => navigate('messages'), 'login'),
      profile: () => requireLogin(() => navigate('profile'), 'login'),

      // Video
      'video-recommend': () => showToast('推荐'),
      'video-follow': () => showToast('关注'),
      'video-msg': () => showToast('消息'),
      'video-me': () => showToast('我的'),

      // Memorial
      'memorial-altar': () => setInnerTab('memorial', 'altar'),
      'memorial-msg': () => setInnerTab('memorial', 'msg'),
      'memorial-album': () => setInnerTab('memorial', 'album'),
      'memorial-me': () => setInnerTab('memorial', 'me'),

      // Love
      'love-dynamic': () => setInnerTab('love', 'dynamic'),
      'love-album': () => setInnerTab('love', 'album'),
      'love-anniversary': () => setInnerTab('love', 'anniversary'),
      'love-message': () => setInnerTab('love', 'message'),
      'love-goal': () => setInnerTab('love', 'goal'),

      // Accounting
      'accounting-bills': () => setInnerTab('accounting-personal', 'bills'),
      'accounting-receivables': () => setInnerTab('accounting-personal', 'receivables'),
      'accounting-stats': () => setInnerTab('accounting-personal', 'stats'),
      'accounting-accounts': () => setInnerTab('accounting-personal', 'accounts'),

      // IM
      'im-chats': () => setInnerTab('im', 'chats'),
      'im-groups': () => setInnerTab('im', 'groups'),
      'im-contacts': () => setInnerTab('im', 'contacts'),
      'im-me': () => setInnerTab('im', 'me'),

      // Member
      'member-home': () => setInnerTab('member', 'home'),
      'member-plan': () => setInnerTab('member', 'plan'),
      'member-rights': () => setInnerTab('member', 'rights'),
      'member-orders': () => setInnerTab('member', 'orders'),

      // Yellow Pages
      'yp-home': () => setInnerTab('yellowpages', 'home'),
      'yp-list': () => setInnerTab('yellowpages', 'list'),
      'yp-inquiry': () => navigate('im'),
      'yp-im': () => navigate('im'),
      'yp-me': () => setInnerTab('yellowpages', 'me'),

      // Site Map
      'sm-home': () => setInnerTab('sitemap', 'home'),
      'sm-index': () => setInnerTab('sitemap', 'index'),
      'sm-perm': () => setInnerTab('sitemap', 'perm'),
      'sm-me': () => setInnerTab('sitemap', 'me'),

      // Orders
      'order-home': () => setInnerTab('orders', 'home'),
      'order-all': () => setInnerTab('orders', 'all'),
      'order-refund': () => setInnerTab('orders', 'refund'),
      'order-bill': () => setInnerTab('orders', 'bill'),

      // Distribution
      'dist-home': () => setInnerTab('distribution', 'home'),
      'dist-material': () => setInnerTab('distribution', 'material'),
      'dist-team': () => setInnerTab('distribution', 'team'),
      'dist-commission': () => setInnerTab('distribution', 'commission'),
    };

    const action = navActions[navId];
    if (action) action();
  }, [navigate, showToast, setInnerTab]);

  const handleFab = useCallback(() => {
    // 发布类操作需要登录（记账页的记一笔也需要登录）
    const isAccountingPage = currentPage === 'accounting-personal';
    if (!currentUser?.id) {
      requireLogin(() => {
        if (isAccountingPage) {
          setShowAccountingBill(true);
        } else {
          setShowPublish(true);
        }
      });
      return;
    }
    // Different FAB behavior per module
    if (isAccountingPage) {
      setShowAccountingBill(true);
    } else {
      setShowPublish(true);
    }
  }, [currentPage, currentUser, requireLogin]);

  const getPublishType = () => {
    const typeMap = {
      home: 'default',
      feed: 'default',
      apps: 'default',
      archive: 'default',
      video: 'video',
      memorial: 'memorial',
      love: 'love',
      accounting: 'accounting',
      'accounting-personal': 'accounting',
      'accounting-enterprise': 'accounting',
      im: 'im',
      member: 'member',
      yellowpages: 'yellowpages',
      sitemap: 'sitemap',
      orders: 'orders',
      distribution: 'distribution',
      'pipe-income': 'default',
      'pipe-team': 'default',
      'pipe-income-detail': 'default',
      'pipe-agent': 'default',
      'pipe-third': 'default',
    };
    return typeMap[currentPage] || 'default';
  };

  const getActiveNavId = () => {
    // For default nav, active tab is the current page itself
    // Secondary pages map to their parent tab
    if (navType === 'default') {
      const tabMap = {
        'article-detail': 'article-list',
        'my-articles': 'article-list',
        'my-archive': 'archive',
        'home': '', // home page: no tab active
        'sitemap': '',
        'credentials': 'apps',
        'qrcode': 'apps',
        'typesetting': 'apps',
        'qa': 'apps',
        'qa-experts': 'apps',
        'qa-question': 'apps',
        'qa-consult': 'apps',
        'wiki': 'apps',
        'wiki-entry': 'apps',
        'wiki-edit': 'apps',
        'admin-wiki': 'apps',
        'admin-seo': 'apps',
        'admin': '',
        'member': 'profile',
        'orders': 'profile',
        'distribution': 'profile',
        'mall': 'apps',
        'mall-product': '',
        'mall-cart': '',
        'mall-order-confirm': '',
        'mall-orders': 'profile',
        'mall-pretty-numbers': '',
        'space': '',
      };
      return tabMap[currentPage] !== undefined ? tabMap[currentPage] : currentPage;
    }
    const prefixMap = {
      video: 'video-',
      memorial: 'memorial-',
      love: 'love-',
      accounting: 'accounting-',
      'accounting-personal': 'accounting-',
      'accounting-enterprise': 'accounting-enterprise-',
      im: 'im-',
      member: 'member-',
      yellowpages: 'yp-',
      sitemap: 'sm-',
      orders: 'order-',
      distribution: 'dist-',
    };
    const prefix = prefixMap[currentPage] || '';
    return prefix + (innerTabs[currentPage] || 'home');
  };

  const renderPage = () => {
    const props = { activeTab: innerTabs[currentPage], setActiveTab: (tab) => setInnerTab(currentPage, tab) };
    switch (currentPage) {
      case 'home': return <HomePage />;
      case 'feed': return <FeedPage showPublish={showPublishFeed} onClosePublish={() => setShowPublishFeed(false)} />;
      case 'messages': return <MessageCenterPage />;
      case 'apps': return <AppsPage />;
      case 'memorial': return <MemorialPage {...props} />;
      case 'love': return <LovePage activeTab={innerTabs.love} setActiveTab={(t) => setInnerTab('love', t)} />;
      case 'accounting': return <AccountingOnboardingPage />;
      case 'accounting-personal': return <AccountingPage {...props} showAddBill={showAccountingBill} onCloseAddBill={() => setShowAccountingBill(false)} />;
      case 'accounting-enterprise': return <AccountingEnterprisePage />;
      case 'im': return <IMPage {...props} pageParams={pageParams.im} showNew={showIMNew} onCloseNew={() => setShowIMNew(false)} />;
      case 'video': return <VideoPage showUpload={showVideoUpload} onCloseUpload={() => setShowVideoUpload(false)} />;
      case 'member': return <MemberPage {...props} showRecharge={showMemberRecharge} onCloseRecharge={() => setShowMemberRecharge(false)} />;
      case 'yellowpages': return <YellowPagesPage {...props} showNew={showYPNew} onCloseNew={() => setShowYPNew(false)} />;
      case 'sitemap': return <SitemapPage {...props} />;
      case 'orders': return <OrdersPage {...props} showNew={showOrderNew} onCloseNew={() => setShowOrderNew(false)} />;
      case 'distribution': return <DistributionPage {...props} showGenerate={showDistGenerate} onCloseGenerate={() => setShowDistGenerate(false)} />;
      case 'pipe-income': return <PipeIncomePage />;
      case 'pipe-team': return <PipeTeamPage />;
      case 'pipe-income-detail': return <PipeIncomeDetailPage initialTab={props?.tab || 'all'} />;
      case 'pipe-agent': return <PipeAgentPage />;
      case 'pipe-third': return <PipeThirdPage />;
      case 'pipe-academy': return <PipeAcademyPage />;
      case 'pipe-article-detail': return <PipeArticleDetailPage />;
      case 'archive': return <ArchivePage />;
      case 'my-archive': return <MyArchivePage />;
      case 'my-articles': return <MyArticlesPage />;
      case 'profile': return <ProfilePage />;
      case 'article-list': return <ArticlesPage />;
      case 'article-detail': return <ArticleDetailPage />;
      case 'admin-seo': return <AdminSEOSettings />;
      case 'mall': return <MallPage />;
      case 'mall-product': return <MallProductPage />;
      case 'mall-cart': return <MallCartPage />;
      case 'mall-order-confirm': return <MallOrderConfirmPage />;
      case 'mall-orders': return <MallOrdersPage />;
      case 'mall-pretty-numbers': return <MallPrettyNumbersPage />;
      case 'space': return <SpacePage />;
      case 'space-square': return <SpaceSquarePage />;
      case 'credentials': return <CredentialsPage />;
      case 'typesetting': return <TypesettingPage />;
      case 'qrcode': return <QrcodePage />;
      case 'qa': return <QaPage />;
      case 'qa-experts': return <QaExpertsPage />;
      case 'qa-question': return <QaQuestionPage />;
      case 'qa-consult': return <QaConsultPage />;
      case 'wiki': return <WikiPage />;
      case 'wiki-entry': return <WikiEntryPage />;
      case 'wiki-edit': return <WikiEditPage />;
      case 'admin-wiki': return <AdminWikiPage />;
      case 'admin': return <AdminPage />;
      case 'temple': return <TempleListPage />;
      case 'temple-detail': return <TempleDetailPage />;
      default: return <HomePage />;
    }
  };

  const handlePublishSelect = useCallback((option) => {
    setShowPublish(false);
    const key = option.key || option.label;
    if (key === 'feed' || option.label?.includes('心情') || option.label?.includes('动态')) {
      setShowPublishFeed(true);
    } else if (key === 'article' || option.label?.includes('文章')) {
      setShowArticlePublish(true);
    } else if (option.label?.includes('视频')) {
      setShowVideoUpload(true);
    } else if (option.label?.includes('爱情') || option.label?.includes('宣言')) {
      navigate('love');
      setInnerTab('love', 'dynamic');
    } else {
      showToast('功能开发中，敬请期待');
    }
  }, [showToast]);

  const openFeedPublish = useCallback(() => {
    if (!requireLogin(() => openFeedPublish())) return;
    setShowPublishFeed(true);
  }, [requireLogin]);

  const openArticlePublish = useCallback(() => {
    if (!requireLogin(() => openArticlePublish())) return;
    setShowArticlePublish(true);
  }, [requireLogin]);

  // 暴露全局方法供各页面调用
  useEffect(() => {
    window.openArticlePublish = openArticlePublish;
    window.openFeedPublish = openFeedPublish;
    window.showCustomerServiceModal = () => setShowCSModal(true);
    return () => {
      delete window.openArticlePublish;
      delete window.openFeedPublish;
      delete window.showCustomerServiceModal;
    };
  }, [openArticlePublish]);

  const handleArticlePublished = useCallback(() => {
    setShowArticlePublish(false);
    showToast('发布成功');
    navigate('article-list');
  }, [navigate, showToast]);

  const contextValue = {
    currentPage,
    pageParams,
    navigate,
    goBack,
    showToast,
    innerTabs,
    setInnerTab,
    showPublish,
    setShowPublish,
    currentUser,
    requireLogin,
    openAuthModal,
    closeAuthModal,
    handleLogout,
    api: window.API || {},
  };

  return (
    <AppContext.Provider value={contextValue}>
      <div className={`app-container ${themeClass}`}>
        {renderPage()}

        {/* Bottom Nav - video page has its own built-in nav */}
        {currentPage !== 'video' && currentPage !== 'accounting' && currentPage !== 'accounting-enterprise' && (
          <BottomNav
            navType={navType}
            activeId={getActiveNavId()}
            onNav={handleNav}
            onFab={handleFab}
          />
        )}

        {/* Publish Sheet */}
        <PublishSheet
          show={showPublish}
          onClose={() => setShowPublish(false)}
          type={getPublishType()}
          onSelect={handlePublishSelect}
        />

        {/* Article Publish Modal */}
        <ArticlePublishPage
          show={showArticlePublish}
          onClose={() => setShowArticlePublish(false)}
          onPublished={handleArticlePublished}
        />

        {/* 客服弹窗 */}
        {window.CustomerServiceModal && (
          <CustomerServiceModal show={showCSModal} onClose={() => setShowCSModal(false)} />
        )}

        {/* Global Toast */}
        <div className={`toast ${toast.show ? 'show' : ''}`}>{toast.msg}</div>

        {/* 全局登录/注册弹窗 */}
        <AuthModal
          show={authModal.show}
          mode={authModal.mode}
          onClose={closeAuthModal}
          onSuccess={handleAuthSuccess}
        />
      </div>
    </AppContext.Provider>
  );
}

const root = ReactDOM.createRoot(document.getElementById('root'));

// 根级错误边界：捕获任何未被页面级边界捕获的错误，防止整页卡死
class AppErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, error: null };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true, error };
  }
  componentDidCatch(error, info) {
    console.error('[AppErrorBoundary] Root error caught:', error, info);
    // 强制清理所有可能残留的全屏固定遮罩，避免拦截点击
    try {
      const selectors = [
        '[data-pipe-modal="1"]',
        '.modal-overlay',
        '.bottom-sheet',
      ];
      selectors.forEach(sel => {
        document.querySelectorAll(sel).forEach(el => {
          // 只清理 fixed / 全屏定位的元素
          const style = window.getComputedStyle(el);
          if (style.position === 'fixed') el.remove();
        });
      });
      // 兜底：移除所有 z-index > 100 且 position=fixed 的透明/半透明全屏元素
      document.querySelectorAll('*').forEach(el => {
        try {
          const s = window.getComputedStyle(el);
          if (s.position === 'fixed' && parseInt(s.zIndex || '0', 10) > 100) {
            const rect = el.getBoundingClientRect();
            if (rect.width >= window.innerWidth * 0.9 && rect.height >= window.innerHeight * 0.9) {
              el.remove();
            }
          }
        } catch(e) {}
      });
    } catch(e) { console.error('cleanup failed', e); }
  }
  handleReload = () => {
    window.location.reload();
  };
  handleBack = () => {
    if (window.history.length > 1) {
      window.history.back();
    } else {
      window.location.reload();
    }
  };
  render() {
    if (this.state.hasError) {
      return (
        <div className="app-container">
          <div className="page-container">
            <header className="app-header">
              <div className="flex items-center gap-8">
                <div style={{ fontSize: '20px', cursor: 'pointer', width: 28, height: 28, display: 'flex', alignItems: 'center', justifyContent: 'center' }} onClick={this.handleBack}>←</div>
                <div className="logo">
                  <div className="logo-icon">久</div>
                  <div><div style={{ fontSize: '15px', lineHeight: 1.2 }}>出错了</div></div>
                </div>
              </div>
            </header>
            <div style={{ padding: '80px 20px', textAlign: 'center', color: 'var(--text-secondary)' }}>
              <div style={{ fontSize: 56, marginBottom: 16 }}>⚠️</div>
              <div style={{ fontSize: 16, color: 'var(--text-primary)', marginBottom: 8 }}>页面出现异常</div>
              <div style={{ fontSize: 13, color: 'var(--text-tertiary)', marginBottom: 24, lineHeight: 1.6 }}>
                抱歉，应用遇到了一些问题<br/>请返回上一页或刷新重试
              </div>
              <div style={{ display: 'flex', gap: 10, justifyContent: 'center' }}>
                <div
                  onClick={this.handleBack}
                  style={{
                    padding: '10px 24px',
                    borderRadius: 20,
                    border: '1px solid var(--border)',
                    color: 'var(--text-secondary)',
                    fontSize: 14,
                    cursor: 'pointer',
                  }}
                >返回</div>
                <div
                  onClick={this.handleReload}
                  style={{
                    padding: '10px 24px',
                    borderRadius: 20,
                    background: 'linear-gradient(135deg, #FF6B3D, #FF8A3D)',
                    color: '#fff',
                    fontSize: 14,
                    fontWeight: 600,
                    cursor: 'pointer',
                  }}
                >刷新页面</div>
              </div>
            </div>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}

root.render(
  <AppErrorBoundary>
    <App />
  </AppErrorBoundary>
);
