All files / src/viewmodels/profile useProfileViewModel.ts

58.9% Statements 172/292
43.61% Branches 41/94
68.88% Functions 31/45
62.16% Lines 161/259

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 6691x 1x 1x 1x       1x                                           1x 1x 1x 1x   1x 1x                                                                                                                                                                                                                                       99x   99x 99x     99x   98x       99x                         24x 24x   24x 72x 75x 74x 74x       24x             25x 74x                         24x 23x   1x     1x       1x         51x   51x   51x                               1x 51x   51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x 51x   51x   28x 1x 1x 1x 1x 1x 1x 1x 1x     27x 27x 27x   27x 27x                     27x                   1x 1x     24x 24x 24x 24x       24x 24x 24x             24x 24x 24x           24x 24x 24x 25x   24x             73x 24x 24x   2x 2x 2x 2x 2x 1x   1x     26x           51x 22x     51x 22x 22x         51x 6x     51x 1x 1x 1x 1x 1x 1x 1x       1x       51x 1x 1x 1x 1x 1x 1x       1x       51x                                                                                                                                                                                             51x 1x 1x 1x 1x 1x 1x       1x       51x 1x 1x 1x 1x 1x 1x       1x       51x 1x 1x 1x 1x 1x 1x       1x       51x                                                                                                                             51x 1x 1x 1x 1x 1x 1x       1x       51x 51x 51x         51x   51x                                                                            
import { useState, useCallback, useEffect, useRef } from 'react';
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import { UserProfile } from '@/models/profile';
import type { ProfileEventSummary } from '@/models/profile';
import type { PrivacyLevel } from '@/models/event';
import {
  confirmProfileAvatarUpload,
  getMyCanceledEvents,
  getMyCompletedEvents,
  getMyHostedEvents,
  getMyProfile,
  getProfileAvatarUploadUrl,
  getMyUpcomingEvents,
  getMyEquipment,
  getMyBadges,
  createEquipment,
  updateEquipment,
  deleteEquipment,
  getShowcaseImageUploadUrl,
  confirmShowcaseImageUpload,
  deleteShowcaseImage,
  updateMyProfile,
  getBadgeCatalog,
  getPublicProfile,
  getUserBadges,
} from '@/services/profileService';
import { BadgeItem, EquipmentItem, ShowcaseImageItem } from '@/models/profile';
import { ApiError } from '@/services/api';
import { useAuth } from '@/contexts/AuthContext';
import { uploadFileToPresignedUrl } from '@/services/eventService';
import { acceptInvitation, declineInvitation, listMyInvitations } from '@/services/invitationService';
import type { ReceivedInvitation } from '@/models/invitation';
import { shouldShowProfileEvent } from '@/utils/eventStatus';
import i18n from '@/i18n';
 
export interface ProfileEventItem {
  id: string;
  title: string;
  start_time: string;
  end_time?: string | null;
  image_url?: string | null;
  category_label: string;
  status: string;
  privacy_level: PrivacyLevel | null;
}
 
export interface ProfileViewModel {
  profile: UserProfile | null;
  isLoading: boolean;
  isUploadingAvatar: boolean;
  apiError: string | null;
  imageError: string | null;
  imageUploadSuccessMessage: string | null;
  primaryName: string;
  secondaryName: string | null;
  avatarInitial: string;
  overallRatingLabel: string;
  hostRatingLabel: string;
  participantRatingLabel: string;
  hostedEvents: ProfileEventItem[];
  attendedEvents: ProfileEventItem[];
  hostedCount: number;
  attendedCount: number;
  equipment: EquipmentItem[];
  invitations: ReceivedInvitation[];
  invitationCount: number;
  badges: BadgeItem[];
  showcaseImages: ShowcaseImageItem[];
  isActionLoading: boolean;
  isInvitationActionLoading: string | null;
  invitationError: string | null;
  catalogVisible: boolean;
  setCatalogVisible: (visible: boolean) => void;
  pickAvatar: () => Promise<void>;
  refresh: () => Promise<void>;
  handleAcceptInvitation: (invitationId: string) => Promise<void>;
  handleDeclineInvitation: (invitationId: string) => Promise<void>;
  addEquipment: (name: string, description?: string) => Promise<void>;
  editEquipment: (id: string, name: string, description?: string) => Promise<void>;
  removeEquipment: (id: string) => Promise<void>;
  uploadShowcaseImage: () => Promise<void>;
  removeShowcaseImage: (id: string) => Promise<void>;
}
 
function decodeFileUriOnce(uri: string): string {
  Iif (!uri.startsWith('file://')) {
    return uri;
  }
 
  try {
    return `file://${decodeURIComponent(uri.slice('file://'.length))}`;
  } catch {
    return uri;
  }
}
 
function normalizePickedImageUri(uri: string): string {
  let normalized = uri;
 
  for (let i = 0; i < 3; i += 1) {
    const next = decodeFileUriOnce(normalized);
    Iif (next === normalized) break;
    normalized = next;
  }
 
  return normalized;
}
 
function getPickedImageUriCandidates(uri: string): string[] {
  return [...new Set([uri, decodeFileUriOnce(uri), normalizePickedImageUri(uri)])];
}
 
async function preparePickedImageUri(uri: string): Promise<string> {
  let lastError: unknown = null;
 
  for (const candidateUri of getPickedImageUriCandidates(uri)) {
    try {
      const preparedImage = await ImageManipulator.manipulateAsync(
        candidateUri,
        [],
        { compress: 0.9, format: ImageManipulator.SaveFormat.JPEG },
      );
      return preparedImage.uri;
    } catch (error) {
      lastError = error;
    }
  }
 
  throw lastError ?? new Error('Could not prepare the selected image');
}
 
async function selectAvatarImage(): Promise<ImagePicker.ImagePickerResult> {
  return ImagePicker.launchImageLibraryAsync({
    mediaTypes: ['images'],
    allowsEditing: true,
    aspect: [1, 1],
    quality: 0.8,
  });
}
 
async function selectGeneralImage(): Promise<ImagePicker.ImagePickerResult> {
  return ImagePicker.launchImageLibraryAsync({
    mediaTypes: ['images'],
    allowsEditing: true,
    quality: 0.8,
  });
}
 
function normalizeEndTime(value?: string | null): string | null {
  Iif (!value) return null;
 
  const trimmed = value.trim();
  Iif (!trimmed) return null;
 
  // Some profile-event endpoints serialize missing end times as Go's zero time.
  if (trimmed.startsWith('0001-01-01')) return null;
 
  return trimmed;
}
 
function mapProfileEvent(event: ProfileEventSummary): ProfileEventItem {
  return {
    id: event.id,
    title: event.title,
    start_time: event.start_time,
    end_time: normalizeEndTime(event.end_time),
    image_url: event.image_url ?? null,
    category_label: event.category ?? 'Event',
    status: event.status,
    privacy_level: event.privacy_level ?? null,
  };
}
 
function mergeEventsById(...groups: ProfileEventSummary[][]): ProfileEventItem[] {
  const seen = new Set<string>();
  const merged: ProfileEventItem[] = [];
 
  for (const group of groups) {
    for (const event of group) {
      if (seen.has(event.id)) continue;
      seen.add(event.id);
      merged.push(mapProfileEvent(event));
    }
  }
 
  return merged;
}
 
function excludeHostedEvents(
  events: ProfileEventItem[],
  hosted: ProfileEventItem[],
): ProfileEventItem[] {
  const hostedIds = new Set(hosted.map((event) => event.id));
  return events.filter((event) => !hostedIds.has(event.id));
}
 
function normalizeInvitationsResponse(
  response:
    | {
        pending?: ReceivedInvitation[];
        past?: { items?: ReceivedInvitation[] };
        items?: ReceivedInvitation[];
      }
    | null
    | undefined,
): ReceivedInvitation[] {
  if (Array.isArray(response?.pending)) {
    return response.pending.filter((invitation) => invitation.status === 'PENDING');
  }
  Iif (Array.isArray(response?.items)) {
    return response.items.filter((invitation) => invitation.status === 'PENDING');
  }
  return [];
}
 
function getInvitationErrorMessage(error: unknown): string {
  return error instanceof ApiError ? error.message : i18n.t('profile.invitations.loadFailed');
}
 
function getProfileRatingLabels(profile: UserProfile | null) {
  const totalCount =
    (profile?.host_score?.rating_count || 0) +
    (profile?.participant_score?.rating_count || 0);
  const newLabel = i18n.t('profile.new');
 
  return {
    overallRatingLabel:
      profile?.final_score != null && totalCount > 0
        ? `${profile.final_score.toFixed(1)} (${totalCount})`
        : newLabel,
    hostRatingLabel:
      profile?.host_score?.score != null && profile.host_score.rating_count > 0
        ? `${profile.host_score.score.toFixed(1)} (${profile.host_score.rating_count})`
        : newLabel,
    participantRatingLabel:
      profile?.participant_score?.score != null && profile.participant_score.rating_count > 0
        ? `${profile.participant_score.score.toFixed(1)} (${profile.participant_score.rating_count})`
        : newLabel,
  };
}
 
export function useProfileViewModel(): ProfileViewModel {
  const { token } = useAuth();
 
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [hostedEvents, setHostedEvents] = useState<ProfileEventItem[]>([]);
  const [attendedEvents, setAttendedEvents] = useState<ProfileEventItem[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [isUploadingAvatar, setIsUploadingAvatar] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [imageError, setImageError] = useState<string | null>(null);
  const [imageUploadSuccessMessage, setImageUploadSuccessMessage] = useState<string | null>(null);
  const imageUploadSuccessTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [equipment, setEquipment] = useState<EquipmentItem[]>([]);
  const [invitations, setInvitations] = useState<ReceivedInvitation[]>([]);
  const [badges, setBadges] = useState<BadgeItem[]>([]);
  const [showcaseImages, setShowcaseImages] = useState<ShowcaseImageItem[]>([]);
  const [isActionLoading, setIsActionLoading] = useState(false);
  const [isInvitationActionLoading, setIsInvitationActionLoading] = useState<string | null>(null);
  const [invitationError, setInvitationError] = useState<string | null>(null);
  const [catalogVisible, setCatalogVisible] = useState(false);
 
  const fetchProfile = useCallback(
    async (mode: 'initial' | 'refresh') => {
      if (!token) {
        setProfile(null);
        setHostedEvents([]);
        setAttendedEvents([]);
        setInvitations([]);
        setInvitationError(null);
        setApiError(i18n.t('profile.errors.loginRequired'));
        setIsLoading(false);
        return;
      }
 
      if (mode === 'initial') setIsLoading(true);
      setApiError(null);
      setInvitationError(null);
 
      try {
        let nextInvitationError: string | null = null;
        const [
          profileResult,
          hostedResult,
          upcomingResult,
          completedResult,
          canceledResult,
          equipmentResult,
          earnedBadgesResult,
          catalogResult,
          invitationsResult,
        ] = await Promise.all([
          getMyProfile(token),
          getMyHostedEvents(token),
          getMyUpcomingEvents(token),
          getMyCompletedEvents(token),
          getMyCanceledEvents(token),
          getMyEquipment(token),
          getMyBadges(token),
          getBadgeCatalog(token),
          listMyInvitations(token).catch((err) => {
            nextInvitationError = getInvitationErrorMessage(err);
            return null;
          }),
        ]);
        setProfile(profileResult);
        setEquipment(equipmentResult.items);
        setInvitations(normalizeInvitationsResponse(invitationsResult));
        setInvitationError(nextInvitationError);
 
        // Workaround: Showcase images are currently only returned by the public profile endpoint.
        // We fetch our own public profile to get the showcase images.
        try {
          const publicData = await getPublicProfile(profileResult.id, token);
          setShowcaseImages(publicData?.showcase_images || []);
        } catch (err) {
          console.error('Failed to fetch self public profile for showcase images:', err);
          setShowcaseImages([]);
        }
        
        // Merge earned status
        const mergedBadges = (catalogResult.items || []).map((b: BadgeItem) => {
          const earned = (earnedBadgesResult.items || []).find((eb: BadgeItem) => eb.slug === b.slug);
          return {
            ...b,
            earned: !!earned,
            earned_at: earned?.earned_at || null,
          };
        });
        setBadges(mergedBadges);
        const allHostedEvents = (hostedResult.events || []).map(mapProfileEvent);
        const visibleHostedEvents = allHostedEvents.filter((event: any) =>
          ['IN_PROGRESS', 'COMPLETED', 'CANCELED'].includes(event.status),
        );
        const mergedAttendedEvents = excludeHostedEvents(
          mergeEventsById(
            upcomingResult.events,
            completedResult.events,
            canceledResult.events,
          ),
          allHostedEvents,
        ).filter((event) => shouldShowProfileEvent(event.status));
        setHostedEvents(visibleHostedEvents);
        setAttendedEvents(mergedAttendedEvents);
      } catch (err) {
        setHostedEvents([]);
        setAttendedEvents([]);
        setInvitations([]);
        setInvitationError(null);
        if (err instanceof ApiError) {
          setApiError(err.message);
        } else {
          setApiError(i18n.t('profile.errors.loadFailed'));
        }
      } finally {
        setIsLoading(false);
      }
    },
    [token],
  );
 
  useEffect(() => {
    void fetchProfile('initial');
  }, [token]);
 
  useEffect(
    () => () => {
      Iif (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
    },
    [],
  );
 
  const refresh = useCallback(async () => {
    await fetchProfile('refresh');
  }, [fetchProfile]);
 
  const handleAcceptInvitation = useCallback(async (invitationId: string) => {
    Iif (!token) return;
    setIsInvitationActionLoading(invitationId);
    setInvitationError(null);
    try {
      await acceptInvitation(invitationId, token);
      setInvitations((prev) => prev.filter((invitation) => invitation.invitation_id !== invitationId));
      await refresh();
    } catch (err) {
      setInvitationError(err instanceof ApiError ? err.message : i18n.t('profile.invitations.acceptFailed'));
    } finally {
      setIsInvitationActionLoading(null);
    }
  }, [refresh, token]);
 
  const handleDeclineInvitation = useCallback(async (invitationId: string) => {
    Iif (!token) return;
    setIsInvitationActionLoading(invitationId);
    setInvitationError(null);
    try {
      await declineInvitation(invitationId, token);
      setInvitations((prev) => prev.filter((invitation) => invitation.invitation_id !== invitationId));
    } catch (err) {
      setInvitationError(err instanceof ApiError ? err.message : i18n.t('profile.invitations.declineFailed'));
    } finally {
      setIsInvitationActionLoading(null);
    }
  }, [token]);
 
  const pickAvatar = useCallback(async () => {
    Iif (!token) {
      setImageError('You must be logged in to update your profile photo.');
      return;
    }
 
    setImageError(null);
    Iif (imageUploadSuccessTimerRef.current) {
      clearTimeout(imageUploadSuccessTimerRef.current);
      imageUploadSuccessTimerRef.current = null;
    }
    setImageUploadSuccessMessage(null);
    try {
      const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
 
      Iif (permission.status !== 'granted') {
        const message = 'Please allow access to your photo library to add a profile photo.';
        setImageError(message);
        Alert.alert('Permission required', message);
        return;
      }
 
      const result = await selectAvatarImage();
      Iif (result.canceled) return;
 
      const asset = result.assets[0];
      Iif (!asset?.uri) {
        setImageError('We could not read the selected image. Please try a different one.');
        return;
      }
 
      let preparedImageUri: string;
      try {
        preparedImageUri = await preparePickedImageUri(asset.uri);
      } catch {
        setImageError('We could not process the selected image. Please try a different one.');
        return;
      }
 
      setIsUploadingAvatar(true);
 
      const original = await ImageManipulator.manipulateAsync(
        preparedImageUri,
        [{ resize: { width: 1200 } }],
        { compress: 0.8, format: ImageManipulator.SaveFormat.JPEG },
      );
 
      const small = await ImageManipulator.manipulateAsync(
        preparedImageUri,
        [{ resize: { width: 400 } }],
        { compress: 0.7, format: ImageManipulator.SaveFormat.JPEG },
      );
 
      const uploadInit = await getProfileAvatarUploadUrl(token);
      const originalUpload = uploadInit.uploads.find((u) => u.variant === 'ORIGINAL');
      const smallUpload = uploadInit.uploads.find((u) => u.variant === 'SMALL');
 
      Iif (!originalUpload || !smallUpload) {
        throw new Error('Missing upload instructions from server');
      }
 
      await Promise.all([
        uploadFileToPresignedUrl(
          originalUpload.method,
          originalUpload.url,
          originalUpload.headers,
          original.uri,
        ),
        uploadFileToPresignedUrl(
          smallUpload.method,
          smallUpload.url,
          smallUpload.headers,
          small.uri,
        ),
      ]);
 
      await confirmProfileAvatarUpload(uploadInit.confirm_token, token);
      await refresh();
      Iif (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
      setImageUploadSuccessMessage('Profile photo updated successfully.');
      imageUploadSuccessTimerRef.current = setTimeout(() => {
        setImageUploadSuccessMessage(null);
        imageUploadSuccessTimerRef.current = null;
      }, 5000);
    } catch (error) {
      if (error instanceof ApiError) {
        setImageError(error.message);
      } else {
        setImageError('We could not upload the selected image. Please try again.');
      }
    } finally {
      setIsUploadingAvatar(false);
    }
  }, [refresh, token]);
 
  const addEquipment = useCallback(async (name: string, description?: string) => {
    Iif (!token) return;
    setIsActionLoading(true);
    setApiError(null);
    try {
      await createEquipment({ name, description }, token);
      await refresh();
    } catch (err) {
      setApiError(err instanceof ApiError ? err.message : 'Failed to add equipment.');
    } finally {
      setIsActionLoading(false);
    }
  }, [token, refresh]);
 
  const editEquipment = useCallback(async (id: string, name: string, description?: string) => {
    Iif (!token) return;
    setIsActionLoading(true);
    setApiError(null);
    try {
      await updateEquipment(id, { name, description }, token);
      await refresh();
    } catch (err) {
      setApiError(err instanceof ApiError ? err.message : 'Failed to update equipment.');
    } finally {
      setIsActionLoading(false);
    }
  }, [token, refresh]);
 
  const removeEquipment = useCallback(async (id: string) => {
    Iif (!token) return;
    setIsActionLoading(true);
    setApiError(null);
    try {
      await deleteEquipment(id, token);
      await refresh();
    } catch (err) {
      setApiError(err instanceof ApiError ? err.message : 'Failed to delete equipment.');
    } finally {
      setIsActionLoading(false);
    }
  }, [token, refresh]);
 
  const uploadShowcaseImage = useCallback(async () => {
    Iif (!token) return;
    setIsActionLoading(true);
    setImageError(null);
    try {
      const permission = await ImagePicker.requestMediaLibraryPermissionsAsync();
      Iif (permission.status !== 'granted') {
        Alert.alert('Permission required', 'Please allow access to your photo library.');
        return;
      }
 
      const result = await selectGeneralImage(); // Allow flexible cropping for showcase
      Iif (result.canceled) return;
 
      const asset = result.assets[0];
      Iif (!asset?.uri) return;
 
      const preparedImageUri = await preparePickedImageUri(asset.uri);
      
      // Showcase images also require both variants (similar to avatar)
      const [original, small] = await Promise.all([
        ImageManipulator.manipulateAsync(
          preparedImageUri,
          [{ resize: { width: 1600 } }], // High quality for showcase
          { compress: 0.8, format: ImageManipulator.SaveFormat.JPEG },
        ),
        ImageManipulator.manipulateAsync(
          preparedImageUri,
          [{ resize: { width: 400 } }],
          { compress: 0.7, format: ImageManipulator.SaveFormat.JPEG },
        ),
      ]);
 
      const uploadInit = await getShowcaseImageUploadUrl(token);
      const originalUpload = uploadInit.uploads.find((u) => u.variant === 'ORIGINAL');
      const smallUpload = uploadInit.uploads.find((u) => u.variant === 'SMALL');
      
      Iif (!originalUpload || !smallUpload) throw new Error('Server error');
 
      await Promise.all([
        uploadFileToPresignedUrl(
          originalUpload.method,
          originalUpload.url,
          originalUpload.headers,
          original.uri,
        ),
        uploadFileToPresignedUrl(
          smallUpload.method,
          smallUpload.url,
          smallUpload.headers,
          small.uri,
        ),
      ]);
 
      await confirmShowcaseImageUpload(uploadInit.confirm_token, token);
      await refresh();
    } catch (err) {
      setImageError(err instanceof ApiError ? err.message : 'Failed to upload image.');
    } finally {
      setIsActionLoading(false);
    }
  }, [token, refresh]);
 
  const removeShowcaseImage = useCallback(async (id: string) => {
    Iif (!token) return;
    setIsActionLoading(true);
    setApiError(null);
    try {
      await deleteShowcaseImage(id, token);
      await refresh();
    } catch (err) {
      setApiError(err instanceof ApiError ? err.message : 'Failed to delete image.');
    } finally {
      setIsActionLoading(false);
    }
  }, [token, refresh]);
 
  const primaryName = profile?.display_name ?? profile?.username ?? '';
  const secondaryName = profile?.display_name ? profile.username : null;
  const avatarInitial = primaryName.trim().charAt(0).toUpperCase() || '?';
  const {
    overallRatingLabel,
    hostRatingLabel,
    participantRatingLabel,
  } = getProfileRatingLabels(profile);
 
  return {
    profile,
    isLoading,
    isUploadingAvatar,
    apiError,
    imageError,
    imageUploadSuccessMessage,
    primaryName,
    secondaryName,
    avatarInitial,
    overallRatingLabel,
    hostRatingLabel,
    participantRatingLabel,
    hostedEvents,
    attendedEvents,
    hostedCount: hostedEvents.length,
    attendedCount: attendedEvents.length,
    equipment,
    invitations,
    invitationCount: invitations.length,
    badges,
    showcaseImages,
    isActionLoading,
    isInvitationActionLoading,
    invitationError,
    catalogVisible,
    setCatalogVisible,
    pickAvatar,
    refresh,
    handleAcceptInvitation,
    handleDeclineInvitation,
    addEquipment,
    editEquipment,
    removeEquipment,
    uploadShowcaseImage,
    removeShowcaseImage,
  };
}