import { useEffect, useState } from "react";
import { toast } from "sonner";
import Container from "../Container";
import NavBar from "../NavBar";
import MyAccount from "./MyAccount";
import Register from "./Register";

function Account() {
    const [isLoggedIn, setIsLoggedIn] = useState(null);

    useEffect(() => {
        fetch("/login/status", {
            method: "POST",
            credentials: "include",
        })
            .then((res) => res.json())
            .then((data) => {
                if (data.message === "True") {
                    setIsLoggedIn(true);
                } else {
                    setIsLoggedIn(false);
                }
            })
            .catch((err) => {
                toast.error(`Error checking login status. Reason: ${err.message}`);
                console.error("Error checking login status:", err);
                setIsLoggedIn(false);
            });
    }, []);

    if (isLoggedIn === null) {
        return <div>Loading...</div>;
    }

    return (
        <>
            <NavBar />
            <Container>
                <div id="accountpage" className="flex h-full w-full">
                    {isLoggedIn ? <MyAccount /> : <Register />}
                </div>
            </Container>
        </>
    );
}

export default Account;
