import React, { useEffect } from 'react';
import { useStore } from './store/useStore';
import { getProjects } from './lib/api';
import { Sidebar } from './components/Sidebar';
import { Dashboard } from './components/Dashboard';
import { ProjectLibrary } from './components/ProjectLibrary';
import { VideoWorkspace } from './components/VideoWorkspace';
import { TemplateRegistry } from './components/TemplateRegistry';
import { AISegmentation } from './components/AISegmentation';
import { Login } from './components/Login';

export type ActiveModule = 'dashboard' | 'projects' | 'ai' | 'workspace' | 'templates';

export default function App() {
  const isAuthenticated = useStore((state) => state.isAuthenticated);
  const activeModule = useStore((state) => state.activeModule);
  const setActiveModule = useStore((state) => state.setActiveModule);
  const setProjects = useStore((state) => state.setProjects);
  const setError = useStore((state) => state.setError);

  useEffect(() => {
    if (isAuthenticated) {
      getProjects()
        .then((data) => setProjects(data))
        .catch((err) => {
          console.error('Failed to fetch projects:', err);
          setError('获取项目列表失败');
        });
    }
  }, [isAuthenticated, setProjects, setError]);

  if (!isAuthenticated) {
    return <Login />;
  }

  return (
    <div className="flex h-screen w-full bg-[#0a0a0a] text-gray-200 overflow-hidden font-sans">
      <Sidebar activeModule={activeModule as ActiveModule} setActiveModule={setActiveModule} />
      <main className="flex-1 flex flex-col min-w-0 h-full relative">
        {activeModule === 'dashboard' && <Dashboard />}
        {activeModule === 'projects' && <ProjectLibrary onProjectSelect={() => setActiveModule('workspace')} />}
        {activeModule === 'ai' && <AISegmentation onSendToWorkspace={() => setActiveModule('workspace')} />}
        {activeModule === 'workspace' && <VideoWorkspace onNavigateToAI={() => setActiveModule('ai')} />}
        {activeModule === 'templates' && <TemplateRegistry />}
      </main>
    </div>
  );
}
