import { useState, useEffect } from 'react';
import { authApi } from '@/services/api/auth';

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 response = await authApi.checkUsername({ username });
        setAvailable(response.available);
      } catch (error) {
        setAvailable(null);
      } finally {
        setChecking(false);
      }
    }, 500);

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

  return { available, checking };
}
