import { useState, useEffect } from 'react';
import { checkUsernameAvailability } from '../services/authService';

export function useUsernameAvailability(username: string) {
  const [available, setAvailable] = useState<boolean | null>(null);
  const [checking, setChecking] = useState(false);

  useEffect(() => {
    if (!username || username.length < 3) {
      setAvailable(null);
      return;
    }

    const timer = setTimeout(async () => {
      setChecking(true);
      try {
        const isAvailable = await checkUsernameAvailability(username);
        setAvailable(isAvailable);
      } catch (error) {
        setAvailable(null);
      } finally {
        setChecking(false);
      }
    }, 500);

    return () => clearTimeout(timer);
  }, [username]);

  return { available, checking };
}

