/**
 * App 入口
 * ========
 */

import { useState, useEffect } from 'react';
import Sidebar from './components/Layout/Sidebar';
import Login from './pages/Login/Login';
import VideoCreation from './pages/VideoCreation';
import MyWorks from './pages/ContentManagement/MyWorks';
import VoiceMaterialLibrary from './pages/ContentManagement/VoiceMaterialLibrary';
import CoverAvatarLibrary from './pages/ContentManagement/CoverAvatarLibrary';
import Settings from './pages/Settings/Settings';
import Profile from './pages/Profile/Profile';
import UsageDetail from './pages/Profile/UsageDetail';
import ToastContainer from './components/Toast/ToastContainer';
import ProgressModal from './components/ProgressModal/ProgressModal';
import UpdateDialog from './components/UpdateDialog/UpdateDialog';
import { ErrorBoundary } from './components/ErrorBoundary';
import ConfirmModal from './components/Modal/ConfirmModal';
import { useAuthStore, usePointStore } from './store';
import { initProjectStore } from './store/projectStore';
import { loadAppConfig } from './api/modules/config';
import { setApiBaseUrl } from './api/client';
import { NavigationContext } from './contexts/NavigationContext';

import './App.css';

// 页面类型
type PageType =
  | 'video-creation'
  | 'voice-material'
  | 'cover-avatar'
  | 'my-works'
  | 'settings'
  | 'profile'
  | 'usage-detail';

// 页面组件映射表（模块级别，避免每次渲染重建组件实例）
const pages: Record<PageType, React.ComponentType> = {
  'video-creation': VideoCreation,
  'voice-material': VoiceMaterialLibrary,
  'cover-avatar': CoverAvatarLibrary,
  'my-works': MyWorks,
  settings: Settings,
  profile: Profile,
  'usage-detail': UsageDetail,
};

/**
 * 渲染页面组件
 */
function renderPage(page: PageType): React.ReactNode {
  const Page = pages[page] || VideoCreation;
  return (
    <ErrorBoundary key={page}>
      <Page />
    </ErrorBoundary>
  );
}

/**
 * 主应用组件
 */
function App() {
  const { isAuthenticated, logout, loadFromStorage, showKickModal, kickMessage, closeKickModal } = useAuthStore();
  const [currentPage, setCurrentPage] = useState<PageType>('video-creation');
  const [showLogoutConfirm, setShowLogoutConfirm] = useState(false);
  const [appEnvironment, setAppEnvironment] = useState<string>('production');
  const [isReady, setIsReady] = useState(false);

  // 应用启动时加载配置和认证状态
  useEffect(() => {
    Promise.all([
      loadAppConfig()
        .then(config => {
          setApiBaseUrl(config.apiBaseUrl);
          setAppEnvironment(config.environment);
        })
        .catch(console.error),
      loadFromStorage().catch(console.error),
    ]).finally(() => {
      // 确保至少显示 300ms 加载态，避免闪屏
      setTimeout(() => setIsReady(true), 300);
    });
  }, [loadFromStorage]);

  // 固定浅色模式
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', 'light');
  }, []);

  // 初始化项目存储（登录后加载本地项目）
  useEffect(() => {
    if (isAuthenticated) {
      initProjectStore().catch(console.error);
      usePointStore.getState().fetchBalance().catch(console.error);
    }
  }, [isAuthenticated]);



  const handleLogout = async () => {
    await logout();
    setCurrentPage('video-creation');
    setShowLogoutConfirm(false);
  };

  const handleNavigate = (page: string) => {
    if (page === 'logout') {
      setShowLogoutConfirm(true);
      return;
    }
    setCurrentPage(page as PageType);
  };

  if (!isReady) {
    return (
      <div className="app-loading">
        <div className="app-loading-spinner" />
        <div className="app-loading-text">美家卡智影</div>
      </div>
    );
  }

  return (
    <>
      {/* Toast 全局挂载 - 不受登录状态影响 */}
      <ToastContainer />

      {/* 自动更新检查对话框 - 全局挂载 */}
      <UpdateDialog />

      {/* 登录层 - 未登录时覆盖全屏 */}
      {!isAuthenticated && <Login />}

      {/* 被踢下线提示弹窗 - 独立于登录状态，必须放在条件 div 外面 */}
      <ConfirmModal
        open={showKickModal}
        type="warning"
        hideCancel
        title={kickMessage || '当前账号在其他设备登录，即将退出'}
        confirmText="确认"
        confirmButtonType="primary"
        onConfirm={closeKickModal}
        onCancel={closeKickModal}
      />

      {/* 主应用层 - 始终渲染但可能被覆盖 */}
      <div style={{ display: isAuthenticated ? 'block' : 'none' }}>
        <NavigationContext.Provider value={{ currentPage, navigate: handleNavigate, appEnvironment }}>
          <ProgressModal />
          <div className="app-layout">
            <Sidebar currentPath={currentPage} onNavigate={handleNavigate} />
            <main className="app-main">
              <div className="app-content">{renderPage(currentPage)}</div>
            </main>
          </div>

          {/* 退出登录确认弹窗 */}
          <ConfirmModal
            open={showLogoutConfirm}
            type="info"
            icon={
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4" />
                <polyline points="16 17 21 12 16 7" />
                <line x1="21" y1="12" x2="9" y2="12" />
              </svg>
            }
            title="确定要退出登录吗？"
            confirmText="确认退出"
            cancelText="取消"
            confirmButtonType="primary"
            onConfirm={handleLogout}
            onCancel={() => setShowLogoutConfirm(false)}
          />
        </NavigationContext.Provider>
      </div>
    </>
  );
}

export default App;
