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

const LAST_USER_KEY = "matrix_client_pc.last_user_id";

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

  useEffect(() => {
    const last = localStorage.getItem(LAST_USER_KEY);
    if (!last) {
      setLoading(false);
      return;
    }
    GetSession(last)
      .then((s) => {
        if (s && s.has_token) setUserID(s.user_id);
      })
      .finally(() => setLoading(false));
  }, []);

  const handleLogin = (uid: string) => {
    localStorage.setItem(LAST_USER_KEY, uid);
    setUserID(uid);
  };

  const handleLogout = () => {
    localStorage.removeItem(LAST_USER_KEY);
    setUserID(null);
  };

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