import { useCallback, useEffect, useState } from 'react';
import {
  AVATAR_CHANGED_EVENT,
  clearUserAvatar,
  loadUserAvatar,
  notifyAvatarChanged,
  processAvatarFile,
  saveUserAvatar,
} from '../utils/userAvatar';

export function useUserAvatar() {
  const [avatarUrl, setAvatarUrl] = useState<string | null>(() => loadUserAvatar());

  useEffect(() => {
    const sync = () => setAvatarUrl(loadUserAvatar());
    window.addEventListener(AVATAR_CHANGED_EVENT, sync);
    window.addEventListener('storage', sync);
    return () => {
      window.removeEventListener(AVATAR_CHANGED_EVENT, sync);
      window.removeEventListener('storage', sync);
    };
  }, []);

  const updateAvatar = useCallback(async (file: File) => {
    const dataUrl = await processAvatarFile(file);
    saveUserAvatar(dataUrl);
    setAvatarUrl(dataUrl);
    notifyAvatarChanged();
  }, []);

  const resetAvatar = useCallback(() => {
    clearUserAvatar();
    setAvatarUrl(null);
    notifyAvatarChanged();
  }, []);

  return { avatarUrl, updateAvatar, resetAvatar };
}
