import { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { useAuth } from "../contexts/AuthContext.tsx";

export default function AuthCallback() {
  const navigate = useNavigate();
  const { checkAuth } = useAuth();

  useEffect(() => {
    const processAuth = async () => {
      const hash = window.location.hash.substring(1);
      const params = new URLSearchParams(hash);
      const token = params.get("token");

      if (token) {
        localStorage.setItem("auth_token", token);
        console.log("Token saved, loading user...");

        await checkAuth();

        window.location.href = "/";
      } else {
        console.error("No token in URL");
        navigate("/login?error=no_token");
      }
    };

    processAuth();
  }, [navigate, checkAuth]);

  return (
    <div className="fixed inset-0 bg-black flex items-center justify-center">
      <div className="w-12 h-12 border-2 border-gray-800 border-t-[hsl(270,73%,63%)] rounded-full animate-spin"></div>
    </div>
  );
}
