import { useEffect } from 'react';
import useLabStore from './store/labStore';
import { getRoomStatus } from './services/labApi';
import { detectOllama, setOllamaModel } from './services/localLLM';

import SetupScreen from './screens/SetupScreen';
import WaitingScreen from './screens/WaitingScreen';
import StudentLoginScreen from './screens/StudentLoginScreen';
import DashboardScreen from './screens/DashboardScreen';
import CourseChatScreen from './screens/CourseChatScreen';
import GeneralChatScreen from './screens/GeneralChatScreen';
import ExerciseScreen from './screens/ExerciseScreen';
import SettingsScreen from './screens/SettingsScreen';

const screens = {
  'setup': SetupScreen,
  'waiting': WaitingScreen,
  'student-login': StudentLoginScreen,
  'dashboard': DashboardScreen,
  'course-chat': CourseChatScreen,
  'general-chat': GeneralChatScreen,
  'exercise': ExerciseScreen,
  'settings': SettingsScreen,
};

export default function App() {
  const { screen, theme, setConfig, setRoomStatus, setTheme, navigate } = useLabStore();

  // Apply theme to document
  useEffect(() => {
    document.documentElement.setAttribute('data-theme', theme);
  }, [theme]);

  // On startup: load saved config
  useEffect(() => {
    async function bootstrap() {
      if (!window.electronAPI) return;

      const savedUrl = await window.electronAPI.config.get('serverUrl');
      const savedRoomToken = await window.electronAPI.config.get('roomToken');
      const savedTheme = await window.electronAPI.config.get('theme');

      if (savedTheme) setTheme(savedTheme);

      if (savedUrl && savedRoomToken) {
        try {
          const roomStatus = await getRoomStatus(savedUrl, savedRoomToken);
          setConfig(savedUrl, savedRoomToken);
          setRoomStatus(roomStatus);
        } catch {
          await window.electronAPI.config.delete('serverUrl');
          await window.electronAPI.config.delete('roomToken');
          navigate('setup');
        }
      }

      detectOllama();

      const savedModel = await window.electronAPI.config.get('ollamaModel');
      if (savedModel) setOllamaModel(savedModel);
    }

    // Set default theme if not in electron
    if (!window.electronAPI) {
      document.documentElement.setAttribute('data-theme', theme);
    }

    bootstrap();
  }, []);

  const Screen = screens[screen] || SetupScreen;

  return (
    <div className="font-sans antialiased">
      <div key={screen} className="animate-fade-in">
        <Screen />
      </div>
    </div>
  );
}
