import { useEffect, useState } from "react";
import { Box, LoadingOverlay } from "@mantine/core";
import LoginScreen from "./LoginScreen";
import HomeScreen from "./HomeScreen";
import { GetLastUserID, GetSession } from "../wailsjs/go/main/MatrixService";

export default function App() {
  const [userID, setUserID] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const last = await GetLastUserID();
        if (!last) return;
        const s = await GetSession(last);
        if (s && s.has_token) setUserID(s.user_id);
      } finally {
        setLoading(false);
      }
    })();
  }, []);

  const handleLogin = (uid: string) => setUserID(uid);
  const handleLogout = () => setUserID(null);

  return (
    <Box pos="relative" mih="100vh">
      <LoadingOverlay visible={loading} />
      {userID ? (
        <HomeScreen userID={userID} onLogout={handleLogout} />
      ) : (
        <LoginScreen onLogin={handleLogin} />
      )}
    </Box>
  );
}
