import React, { useEffect, useState } from 'react';
import { BrowserRouter as Router, Routes, Route, Navigate } from 'react-router-dom';
import { ConfigProvider, App as AntdApp, Spin } from 'antd';
import zhCN from 'antd/locale/zh_CN';
import { OllamaProvider } from './contexts/OllamaContext';
import MainLayout from './components/MainLayout';
import NovelList from './pages/NovelList';
import NovelDetail from './pages/NovelDetail';
import NovelGenerate from './pages/NovelGenerate';
import ModelSettings from './pages/ModelSettings';
import UserManual from './pages/UserManual';
import SkillsPage from './pages/SkillsPage';
import InitPage from './pages/InitPage';
import ConversationsPage from './pages/ConversationsPage';
import { indexedDBStorage } from './utils/indexedDB';
import './App.css';

function App() {
  const [isDBReady, setIsDBReady] = useState(false);

  useEffect(() => {
    const initDB = async () => {
      try {
        await indexedDBStorage.init();
        setIsDBReady(true);
      } catch (error) {
        console.error('Failed to initialize IndexedDB:', error);
        // 即使初始化失败也继续运行，因为 IndexedDB 操作会自动重试
        setIsDBReady(true);
      }
    };
    initDB();
  }, []);

  if (!isDBReady) {
    return (
      <div style={{
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        height: '100vh',
        flexDirection: 'column'
      }}>
        <Spin size="large" />
        <div style={{ marginTop: '16px', color: '#666' }}>正在初始化数据库...</div>
      </div>
    );
  }

  return (
    <ConfigProvider locale={zhCN}>
      <AntdApp>
        <OllamaProvider>
          <Router>
            <Routes>
              <Route path="/" element={<MainLayout />}>
                <Route index element={<Navigate to="/novels" replace />} />
                <Route path="novels" element={<NovelList />} />
                <Route path="novels/:id" element={<NovelDetail />} />
                <Route path="novels/:id/generate" element={<NovelGenerate />} />
                <Route path="chat/conversations" element={<ConversationsPage />} />
                <Route path="agents/skills" element={<SkillsPage />} />
                <Route path="settings/model" element={<ModelSettings />} />
                <Route path="settings/init" element={<InitPage />} />
                <Route path="manual" element={<UserManual />} />
              </Route>
            </Routes>
          </Router>
        </OllamaProvider>
      </AntdApp>
    </ConfigProvider>
  );
}

export default App;
