import { useState, useEffect } from 'react';
import { login as loginService, logout as logoutService, getStoredUser, isAuthenticated } from '../services/auth';

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

  useEffect(() => {
    const storedUser = getStoredUser();
    if (isAuthenticated() && storedUser) {
      setUser(storedUser);
    }
    setLoading(false);

    // Handle 401/403 from API interceptor – clear user state without hard navigation
    const handleUnauthorized = () => setUser(null);
    window.addEventListener('auth:unauthorized', handleUnauthorized);
    return () => window.removeEventListener('auth:unauthorized', handleUnauthorized);
  }, []);

  const login = async (username, password) => {
    setLoading(true);
    try {
      const result = await loginService(username, password);
      if (result.success) {
        setUser(result.user);
      }
      setLoading(false);
      return result;
    } catch (error) {
      setLoading(false);
      return {
        success: false,
        message: error.message || 'Login fehlgeschlagen'
      };
    }
  };

  const logout = async () => {
    await logoutService();
    setUser(null);
  };

  return {
    user,
    isAuthenticated: !!user,
    loading,
    login,
    logout
  };
};
