import { useState, useEffect } from "react";
import type { SteamUser } from "../types";
import { authService } from "../services/api";

export function useAuth() {
  const [user, setUser] = useState<SteamUser | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    checkAuthStatus();

    // Check for auth success in URL (after Steam redirect)
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get("auth") === "success") {
      // Remove the auth parameter from URL
      window.history.replaceState({}, document.title, window.location.pathname);
      checkAuthStatus();
    }
  }, []);

  const checkAuthStatus = async () => {
    try {
      const data = await authService.checkUser();
      if (data) {
        setUser(data.user);
      }
    } catch (error) {
      console.error("Auth check failed:", error);
    } finally {
      setLoading(false);
    }
  };

  const handleLogin = () => {
    window.location.href = authService.getSteamLoginUrl();
  };

  const handleLogout = async () => {
    try {
      await authService.logout();
      setUser(null);
    } catch (error) {
      console.error("Logout failed:", error);
    }
  };

  return {
    user,
    loading,
    handleLogin,
    handleLogout,
  };
}
