/**
 * Unified avatar URL composable
 * Provides consistent avatar handling across all components
 */

/**
 * Get avatar URL with fallback to initials
 * @param avatarUrl - The avatar URL from backend (can be full URL, relative path, or null/undefined)
 * @param firstName - User's first name for fallback
 * @param lastName - User's last name for fallback
 * @returns Full avatar URL or initials fallback URL
 */
export function useAvatarUrl() {
  const getAvatarUrl = (
    avatarUrl: string | null | undefined,
    firstName?: string,
    lastName?: string
  ): string => {
    // Handle null/undefined avatar URL
    if (!avatarUrl) {
      // Return initials fallback with name
      const name = [firstName, lastName].filter(Boolean).join(' ') || 'default'
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=random&color=fff`
    }

    // If it's already a full URL (http/https), return as-is
    if (avatarUrl.startsWith('http://') || avatarUrl.startsWith('https://')) {
      return avatarUrl
    }

    // Handle relative paths (e.g., "backend/avatars/..." or "avatars/...")
    const cleanUrl = avatarUrl.replace(/^backend[\/\\]/, '').replace(/\\/g, '/')
    return `/${cleanUrl}`
  }

  /**
   * Get initials avatar URL for fallback display
   * @param firstName - User's first name
   * @param lastName - User's last name
   * @returns Initials avatar URL
   */
  const getInitialsAvatarUrl = (
    firstName?: string,
    lastName?: string
  ): string => {
    // Use name combination
    const name = [firstName, lastName].filter(Boolean).join(' ').trim()
    if (name) {
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(name)}&background=random&color=fff`
    }
    // Ultimate fallback
    return 'https://ui-avatars.com/api/?name=User&background=random&color=fff'
  }

  return {
    getAvatarUrl,
    getInitialsAvatarUrl
  }
}
