'use client';

import { useCallback, useEffect, useState } from 'react';
import { useAuth } from '@/components/id/auth-provider';
import { apiFetch } from '@/lib/api';
import { AVATAR_UPDATED_EVENT } from '@/lib/avatar-events';

interface AvatarAccessResponse {
  accessUrl: string;
  expiresAt: string;
}

export function useAvatarUrl(userId: string | undefined, hasAvatar: boolean | undefined, token: string | null) {
  const { isPinLocked } = useAuth();
  const [avatarUrl, setAvatarUrl] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    if (!userId || !token || !hasAvatar || isPinLocked) {
      setAvatarUrl(null);
      return;
    }
    try {
      const response = await apiFetch<AvatarAccessResponse>(`/media/avatars/${userId}/url`, {}, token);
      setAvatarUrl(response.accessUrl);
    } catch {
      setAvatarUrl(null);
    }
  }, [hasAvatar, isPinLocked, token, userId]);

  useEffect(() => {
    void refresh();
    if (!hasAvatar) return;
    const timer = window.setInterval(() => {
      void refresh();
    }, 14 * 60 * 1000);
    return () => window.clearInterval(timer);
  }, [hasAvatar, refresh]);

  useEffect(() => {
    if (!userId || !hasAvatar) return;
    function handleAvatarUpdated(event: Event) {
      const detail = (event as CustomEvent<{ userId?: string }>).detail;
      if (detail?.userId === userId) {
        void refresh();
      }
    }
    window.addEventListener(AVATAR_UPDATED_EVENT, handleAvatarUpdated);
    return () => window.removeEventListener(AVATAR_UPDATED_EVENT, handleAvatarUpdated);
  }, [hasAvatar, refresh, userId]);

  return { avatarUrl, refreshAvatarUrl: refresh };
}
