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

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

  useEffect(() => {
    const checkAuthStatus = async () => {
      try {
        console.log('Checking authentication status...');
        const response = await authService.getCurrentUser();
        console.log('Auth check response:', response);
        setUser(response.user);
      } catch (error) {
        console.log('User not authenticated:', error);
        setUser(null);
      } finally {
        setLoading(false);
      }
    };

    checkAuthStatus();

    // Check for auth success parameter
    const urlParams = new URLSearchParams(window.location.search);
    if (urlParams.get('auth') === 'success') {
      console.log('Auth success detected, rechecking user status...');
      // Remove the auth parameter from URL
      window.history.replaceState({}, document.title, window.location.pathname);
      // Recheck auth status
      setTimeout(checkAuthStatus, 1000);
    }
  }, []);

  const handleLogin = () => {
    console.log('Initiating login...');
    window.location.href = `${import.meta.env.PROD ? 'https://s22.ethanf.gg' : 'http://localhost:3001'}/auth/steam`;
  };

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

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