'use client';

import { refresh } from "@/api/auth";
import { userState } from "@/state/auth";
import { Skeleton } from "@mantine/core";
import { useEffect, useState } from "react";
import { useRecoilState } from "recoil";

export default function Loading({ children }: { children: React.ReactNode }) {
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useRecoilState(userState);
  
  useEffect(() => {
    checkUser();
  }, []);

  async function checkUser() {
    setLoading(true);
    if (!user) {
      const response = await refresh();
      if (response) {
        setUser(response.user);
      }
    }
    setLoading(false);
  }

  if (loading) {
    return <Skeleton height={'100%'} />;
  } else {
    return <>{children}</>;
  }
}