All files / src/viewmodels/home useHomeViewModel.ts

86% Statements 387/450
78.7% Branches 207/263
90.76% Functions 59/65
88.03% Lines 368/418

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 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 10442x                   2x 2x 2x 2x 2x       2x 2x 2x   2x 2x   2x       2x 2x           2x                                     97x               41x         37x     4x               357x               43x 48x           48x 48x                                               222x 41x     181x 4x         177x             8x 8x   8x             104x   2x 2x   2x 2x 2x 2x   2x 2x   2x 2x   2x                   2x                 2x       30x   30x 30x   30x 30x 30x 30x   30x 30x   28x 28x   26x   26x                 26x 26x       11x   11x 11x   11x 5x 5x 2x   3x 1x       8x 3x 3x 1x   2x         7x 2x 2x   2x 1x       6x       14x   14x 14x   14x       25x   14x   14x 14x 14x         14x 14x 14x 2x       12x   12x 12x 1x     11x 1x     10x     14x 14x   11x 11x   10x 3x 3x   3x 1x       9x                                                                                                                               2x 222x 222x 222x   222x 222x 222x 222x 222x 222x 222x 222x         222x   222x 222x 222x 222x 222x   222x 222x 222x 222x 222x     222x   222x 222x   222x 222x   222x 222x 222x 222x 222x 222x   222x   44x   44x       2x 2x     42x 42x         222x         8x               222x 41x 41x             222x 44x   44x 1x 1x 1x 1x 1x 1x     43x 43x   43x 2x 2x 2x 2x           41x 41x 41x   41x 4x 4x 4x 4x           37x 37x 37x 37x     222x 44x 1x 1x 1x 1x     43x 43x   43x 43x 43x             43x       222x 41x 41x 40x   1x       222x         50x 1x 1x 1x 1x 1x 1x 1x 1x     49x   49x 49x 49x 49x   49x 46x 46x     49x     49x           49x                                           48x 48x   48x 48x 3x   45x     1x   49x 49x 49x           222x 41x     222x 41x   41x 41x   41x   41x 41x 41x     41x 41x       222x 41x     222x 100x   57x 46x     57x     222x 1x   1x       1x   1x         1x   1x 1x       222x             222x 2x     222x 11x 11x 11x 11x 11x     222x 1x         1x 1x 1x 1x 1x     222x                                                                 222x 5x         5x 5x 5x 5x     222x 5x         5x 5x 5x 5x     222x 8x       8x   8x   8x       8x 8x 8x 8x     222x 2x         2x 2x 2x 2x     222x 14x 14x 14x     222x 1x 1x 1x     222x 1x 1x     222x 11x   11x 5x 5x     6x 6x 6x     222x 2x 2x   2x                 222x 3x 3x   3x         3x 3x       222x 7x 7x         7x 7x       222x 4x 4x         4x 4x       222x 3x           222x     3x           222x 3x       3x                   222x 1x     222x       222x 3x   3x   3x 3x 3x   3x         3x           3x                                       3x 3x 3x       3x                       357x             222x                                                                                                                            
import { useCallback, useEffect, useRef, useState } from 'react';
import {
  DiscoverEventsSortBy,
  EventCategory,
  EventSummary,
  HomeFilterPrivacyLevel,
  HomeFiltersDraft,
  LocationSuggestion,
} from '@/models/event';
import { FavoriteLocation } from '@/models/favorite';
import { ApiError } from '@/services/api';
import { getCurrentLocationSuggestion } from '@/services/deviceLocationService';
import { listCategories, listEvents, searchLocation } from '@/services/eventService';
import { listFavoriteLocations } from '@/services/favoriteService';
import {
  getHomeLocationSelection,
  setHomeLocationSelection,
} from '@/services/homeLocationSelectionStore';
import { getMyProfile } from '@/services/profileService';
import { formatEventLocation } from '@/utils/eventLocation';
import { useAuth } from '@/contexts/AuthContext';
 
const PAGE_SIZE = 2;
const MAX_FAVORITE_LOCATION_OPTIONS = 3;
 
const DEFAULT_LOCATION = {
  lat: 41.0422,
  lon: 29.0083,
};
const DEFAULT_LOCATION_LABEL = 'Beşiktaş, Istanbul';
const FALLBACK_LOCATION: LocationSuggestion = {
  display_name: DEFAULT_LOCATION_LABEL,
  lat: String(DEFAULT_LOCATION.lat),
  lon: String(DEFAULT_LOCATION.lon),
};
 
const DEFAULT_FILTERS: HomeFiltersDraft = {
  categoryIds: [],
  privacyLevels: [],
  startDate: '',
  endDate: '',
  radiusKm: 10,
  sortBy: 'START_TIME',
};
 
type DefaultLocationSource = 'PROFILE' | 'LIVE' | 'FALLBACK';
 
interface HomeLocationOption {
  id: string;
  title: string;
  subtitle: string;
  suggestion: LocationSuggestion;
}
 
function excludeInProgressEvents(items: EventSummary[]): EventSummary[] {
  return items.filter((e) => e.status !== 'IN_PROGRESS');
}
 
function profileToSelectedLocation(profile: {
  default_location_address: string | null;
  default_location_lat: number | null;
  default_location_lon: number | null;
}): LocationSuggestion | null {
  if (
    !profile.default_location_address ||
    profile.default_location_lat == null ||
    profile.default_location_lon == null
  ) {
    return null;
  }
 
  return {
    display_name: profile.default_location_address,
    lat: String(profile.default_location_lat),
    lon: String(profile.default_location_lon),
  };
}
 
function favoriteLocationToSuggestion(location: FavoriteLocation): LocationSuggestion {
  return {
    display_name: location.address,
    lat: String(location.lat),
    lon: String(location.lon),
  };
}
 
function sortFavoriteLocations(locations: FavoriteLocation[]): FavoriteLocation[] {
  return [...locations].sort((left, right) => {
    const nameComparison = left.name.localeCompare(
      right.name,
      undefined,
      { sensitivity: 'base' },
    );
 
    Eif (nameComparison !== 0) {
      return nameComparison;
    }
 
    return left.id.localeCompare(right.id);
  });
}
 
function getFavoriteLocationsErrorMessage(error: unknown): string {
  if (error instanceof ApiError && error.status === 401) {
    return 'You must be logged in to view favorite locations.';
  }
 
  if (error instanceof ApiError) {
    return error.message;
  }
 
  return 'Failed to load favorite locations. Please try again.';
}
 
function getDefaultLocationSubtitle(
  source: DefaultLocationSource,
  location: LocationSuggestion | null,
  isResolving: boolean,
): string {
  if (!location) {
    return isResolving ? 'Resolving your location...' : 'Location unavailable.';
  }
 
  if (source === 'LIVE') {
    return location.display_name === 'Current location'
      ? 'Using your current live location.'
      : `Current location: ${location.display_name}`;
  }
 
  return location.display_name;
}
 
function locationsMatch(
  left: LocationSuggestion | null,
  right: LocationSuggestion | null,
): boolean {
  Iif (!left && !right) return true;
  Iif (!left || !right) return false;
 
  return left.lat === right.lat && left.lon === right.lon;
}
 
function parseStrictDateToIso(
  value: string,
  boundary: 'start' | 'end',
): string | undefined {
  if (!value) return undefined;
 
  const match = value.match(/^(\d{2})\.(\d{2})\.(\d{4})$/);
  Iif (!match) return undefined;
 
  const [, dayText, monthText, yearText] = match;
  const day = Number(dayText);
  const month = Number(monthText);
  const year = Number(yearText);
 
  Iif (!day || !month || !year) return undefined;
  Iif (month < 1 || month > 12) return undefined;
 
  const daysInMonth = new Date(year, month, 0).getDate();
  Iif (day < 1 || day > daysInMonth) return undefined;
 
  const date = new Date(
    year,
    month - 1,
    day,
    boundary === 'start' ? 0 : 23,
    boundary === 'start' ? 0 : 59,
    boundary === 'start' ? 0 : 59,
    boundary === 'start' ? 0 : 999,
  );
 
  Iif (
    Number.isNaN(date.getTime()) ||
    date.getFullYear() !== year ||
    date.getMonth() !== month - 1 ||
    date.getDate() !== day
  ) {
    return undefined;
  }
 
  return date.toISOString();
}
 
function parseStrictDate(value: string): Date | null {
  Iif (!value) return null;
 
  const match = value.match(/^(\d{2})\.(\d{2})\.(\d{4})$/);
  Iif (!match) return null;
 
  const [, dayText, monthText, yearText] = match;
  const day = Number(dayText);
  const month = Number(monthText);
  const year = Number(yearText);
 
  Iif (!day || !month || !year) return null;
  if (month < 1 || month > 12) return null;
 
  const daysInMonth = new Date(year, month, 0).getDate();
  if (day < 1 || day > daysInMonth) return null;
 
  const date = new Date(year, month - 1, day);
 
  Iif (
    Number.isNaN(date.getTime()) ||
    date.getFullYear() !== year ||
    date.getMonth() !== month - 1 ||
    date.getDate() !== day
  ) {
    return null;
  }
 
  date.setHours(0, 0, 0, 0);
  return date;
}
 
function validateFilterDates(filters: HomeFiltersDraft): string | null {
  const { startDate, endDate } = filters;
 
  const today = new Date();
  today.setHours(0, 0, 0, 0);
 
  if (startDate) {
    const parsedStart = parseStrictDate(startDate);
    if (!parsedStart) {
      return 'From date must be a valid date.';
    }
    if (parsedStart < today) {
      return 'From date must be today or later.';
    }
  }
 
  if (endDate) {
    const parsedEnd = parseStrictDate(endDate);
    if (!parsedEnd) {
      return 'To date must be a valid date.';
    }
    Iif (parsedEnd < today) {
      return 'To date must be today or later.';
    }
  }
 
  if (startDate && endDate) {
    const parsedStart = parseStrictDate(startDate);
    const parsedEnd = parseStrictDate(endDate);
 
    if (parsedStart && parsedEnd && parsedEnd < parsedStart) {
      return 'To date must be the same as or later than From date.';
    }
  }
 
  return null;
}
 
function validateFilterDatesLive(filters: HomeFiltersDraft): string | null {
  const { startDate, endDate } = filters;
 
  const today = new Date();
  today.setHours(0, 0, 0, 0);
 
  const validateSingle = (
    value: string,
    label: 'From' | 'To',
  ): string | null => {
    if (!value) return null;
 
    const digits = value.replace(/\D/g, '');
 
    Eif (digits.length >= 2) {
      const day = Number(digits.slice(0, 2));
      Iif (day < 1 || day > 31) {
        return `${label} date day must be between 01 and 31.`;
      }
    }
 
    Eif (digits.length >= 4) {
      const month = Number(digits.slice(2, 4));
      if (month < 1 || month > 12) {
        return `${label} date month must be between 01 and 12.`;
      }
    }
 
    Iif (value.length < 10) return null;
 
    const parsed = parseStrictDate(value);
    if (!parsed) {
      return `${label} date must be a valid date.`;
    }
 
    if (parsed < today) {
      return `${label} date must be today or later.`;
    }
 
    return null;
  };
 
  const startError = validateSingle(startDate, 'From');
  if (startError) return startError;
 
  const endError = validateSingle(endDate, 'To');
  if (endError) return endError;
 
  if (startDate.length === 10 && endDate.length === 10) {
    const parsedStart = parseStrictDate(startDate);
    const parsedEnd = parseStrictDate(endDate);
 
    if (parsedStart && parsedEnd && parsedEnd < parsedStart) {
      return 'To date must be the same as or later than From date.';
    }
  }
 
  return null;
}
 
export interface HomeViewModel {
  locationLabel: string;
  locationQuery: string;
  locationSuggestions: LocationSuggestion[];
  isSearchingLocation: boolean;
  isLocationModalOpen: boolean;
  pendingLocation: LocationSuggestion | null;
  defaultLocationOption: {
    title: string;
    subtitle: string;
    suggestion: LocationSuggestion | null;
    isLoading: boolean;
  };
  favoriteLocationOptions: Array<{
    id: string;
    title: string;
    subtitle: string;
    suggestion: LocationSuggestion;
  }>;
  isLoadingFavoriteLocations: boolean;
  favoriteLocationsError: string | null;
  categories: readonly EventCategory[];
  selectedCategoryId: number | null;
  searchText: string;
  events: EventSummary[];
  isLoading: boolean;
  isLoadingMore: boolean;
  isRefreshing: boolean;
  apiError: string | null;
  hasMore: boolean;
  isFilterModalOpen: boolean;
  filterDraft: HomeFiltersDraft;
  filterError: string | null;
  updateSearchText: (value: string) => void;
  submitSearch: () => void;
  selectCategory: (categoryId: number | null) => void;
  openFilterModal: () => void;
  closeFilterModal: () => void;
  resetFilterDraft: () => void;
  applyFilterDraft: () => void;
  toggleDraftCategory: (categoryId: number) => void;
  toggleDraftPrivacy: (privacy: HomeFilterPrivacyLevel) => void;
  updateDraftStartDate: (value: string) => void;
  updateDraftEndDate: (value: string) => void;
  updateDraftRadiusKm: (value: number) => void;
  updateDraftSortBy: (
    value: Extract<DiscoverEventsSortBy, 'START_TIME' | 'DISTANCE'>,
  ) => void;
  loadMoreEvents: () => Promise<void>;
  refreshEvents: () => Promise<void>;
  silentRefresh: () => Promise<void>;
  openLocationModal: () => void;
  closeLocationModal: () => void;
  updateLocationQuery: (value: string) => void;
  selectSavedLocationOption: (suggestion: LocationSuggestion) => void;
  selectLocationSuggestion: (suggestion: LocationSuggestion) => void;
  applySelectedLocation: () => void;
  resetLocationDraft: () => void;
  retryFavoriteLocations: () => Promise<void>;
}
 
export function useHomeViewModel(): HomeViewModel {
  const { token, user } = useAuth();
  const locationSelectionScope = user?.id ?? token ?? 'anonymous';
  const storedLocationSelection = getHomeLocationSelection(locationSelectionScope);
 
  const [categories, setCategories] = useState<EventCategory[]>([]);
  const [events, setEvents] = useState<EventSummary[]>([]);
  const [searchText, setSearchText] = useState('');
  const [locationQuery, setLocationQuery] = useState('');
  const [locationSuggestions, setLocationSuggestions] = useState<LocationSuggestion[]>([]);
  const [isSearchingLocation, setIsSearchingLocation] = useState(false);
  const [isLocationModalOpen, setIsLocationModalOpen] = useState(false);
  const [selectedLocation, setSelectedLocation] = useState<LocationSuggestion | null>(
    storedLocationSelection.mode === 'CUSTOM'
      ? storedLocationSelection.location
      : null,
  );
  const [defaultLocation, setDefaultLocation] = useState<LocationSuggestion | null>(null);
  const [defaultLocationSource, setDefaultLocationSource] =
    useState<DefaultLocationSource>('FALLBACK');
  const [pendingLocation, setPendingLocation] = useState<LocationSuggestion | null>(null);
  const [favoriteLocations, setFavoriteLocations] = useState<FavoriteLocation[]>([]);
  const [isLoadingFavoriteLocations, setIsLoadingFavoriteLocations] = useState(true);
  const [favoriteLocationsError, setFavoriteLocationsError] = useState<string | null>(null);
 
  const locationSearchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const [filterError, setFilterError] = useState<string | null>(null);
  const [appliedSearchText, setAppliedSearchText] = useState('');
  const [selectedCategoryId, setSelectedCategoryId] = useState<number | null>(null);
 
  const [appliedFilters, setAppliedFilters] =
    useState<HomeFiltersDraft>(DEFAULT_FILTERS);
  const [filterDraft, setFilterDraft] =
    useState<HomeFiltersDraft>(DEFAULT_FILTERS);
  const [isFilterModalOpen, setIsFilterModalOpen] = useState(false);
 
  const [nextCursor, setNextCursor] = useState<string | null>(null);
  const [hasMore, setHasMore] = useState(false);
 
  const [isLoading, setIsLoading] = useState(true);
  const [isLoadingMore, setIsLoadingMore] = useState(false);
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [isLocationContextReady, setIsLocationContextReady] = useState(false);
  const [isResolvingDefaultLocation, setIsResolvingDefaultLocation] = useState(true);
 
  const syncSelectedLocationWithDefault = useCallback(
    (resolvedDefaultLocation: LocationSuggestion) => {
      const persistedSelection = getHomeLocationSelection(locationSelectionScope);
 
      if (
        persistedSelection.mode === 'CUSTOM' &&
        persistedSelection.location
      ) {
        setSelectedLocation(persistedSelection.location);
        return persistedSelection.location;
      }
 
      setSelectedLocation(resolvedDefaultLocation);
      return resolvedDefaultLocation;
    },
    [locationSelectionScope],
  );
 
  const persistLocationSelection = useCallback(
    (
      mode: 'DEFAULT' | 'CUSTOM',
      location: LocationSuggestion | null,
    ) => {
      setHomeLocationSelection(locationSelectionScope, {
        mode,
        location: mode === 'CUSTOM' ? location : null,
      });
    },
    [locationSelectionScope],
  );
 
  useEffect(() => {
    const persistedSelection = getHomeLocationSelection(locationSelectionScope);
    setSelectedLocation(
      persistedSelection.mode === 'CUSTOM'
        ? persistedSelection.location
        : null,
    );
  }, [locationSelectionScope]);
 
  const resolveDefaultLocation = useCallback(async () => {
    setIsResolvingDefaultLocation(true);
 
    if (!token) {
      setDefaultLocation(FALLBACK_LOCATION);
      setDefaultLocationSource('FALLBACK');
      syncSelectedLocationWithDefault(FALLBACK_LOCATION);
      setIsLocationContextReady(true);
      setIsResolvingDefaultLocation(false);
      return FALLBACK_LOCATION;
    }
 
    try {
      const liveLocation = await getCurrentLocationSuggestion();
 
      if (liveLocation) {
        setDefaultLocation(liveLocation);
        setDefaultLocationSource('LIVE');
        syncSelectedLocationWithDefault(liveLocation);
        return liveLocation;
      }
    } catch {
      // Fall through to profile and fallback location resolution.
    }
 
    try {
      const profile = await getMyProfile(token);
      const profileLocation = profileToSelectedLocation(profile);
 
      if (profileLocation) {
        setDefaultLocation(profileLocation);
        setDefaultLocationSource('PROFILE');
        syncSelectedLocationWithDefault(profileLocation);
        return profileLocation;
      }
    } catch {
      // Fall through to the hardcoded fallback location.
    }
 
    setDefaultLocation(FALLBACK_LOCATION);
    setDefaultLocationSource('FALLBACK');
    syncSelectedLocationWithDefault(FALLBACK_LOCATION);
    return FALLBACK_LOCATION;
  }, [syncSelectedLocationWithDefault, token]);
 
  const fetchFavoriteLocations = useCallback(async () => {
    if (!token) {
      setFavoriteLocations([]);
      setFavoriteLocationsError(null);
      setIsLoadingFavoriteLocations(false);
      return;
    }
 
    setIsLoadingFavoriteLocations(true);
    setFavoriteLocationsError(null);
 
    try {
      const response = await listFavoriteLocations(token);
      setFavoriteLocations(
        sortFavoriteLocations(response.items).slice(0, MAX_FAVORITE_LOCATION_OPTIONS),
      );
    } catch (error) {
      setFavoriteLocations([]);
      setFavoriteLocationsError(getFavoriteLocationsErrorMessage(error));
    } finally {
      setIsLoadingFavoriteLocations(false);
    }
  }, [token]);
 
  const loadCategories = useCallback(async () => {
    try {
      const response = await listCategories();
      setCategories(response.items);
    } catch {
      setApiError('Failed to load categories. Please try again.');
    }
  }, []);
 
  const loadEvents = useCallback(
    async (
      mode: 'initial' | 'refresh' | 'loadMore',
      cursorOverride?: string | null,
    ) => {
      if (!token) {
        setEvents([]);
        setHasMore(false);
        setNextCursor(null);
        setApiError('You must be logged in to view events.');
        setIsLoading(false);
        setIsRefreshing(false);
        setIsLoadingMore(false);
        return;
      }
 
      const activeLocation = selectedLocation ?? defaultLocation ?? FALLBACK_LOCATION;
 
      try {
        if (mode === 'initial') setIsLoading(true);
        if (mode === 'refresh') setIsRefreshing(true);
        if (mode === 'loadMore') setIsLoadingMore(true);
 
        if (mode !== 'loadMore') {
          setNextCursor(null);
          setHasMore(false);
        }
 
        setApiError(null);
 
        const combinedCategoryIds =
          selectedCategoryId != null
            ? Array.from(
              new Set([selectedCategoryId, ...appliedFilters.categoryIds]),
            )
            : appliedFilters.categoryIds;
 
        const response = await listEvents(
          {
            lat: Number(activeLocation.lat),
            lon: Number(activeLocation.lon),
            radius_meters: appliedFilters.radiusKm * 1000,
            q: appliedSearchText || undefined,
            category_ids:
              combinedCategoryIds.length > 0 ? combinedCategoryIds : undefined,
            privacy_levels:
              appliedFilters.privacyLevels.length > 0
                ? appliedFilters.privacyLevels
                : undefined,
            start_from: parseStrictDateToIso(appliedFilters.startDate, 'start'),
            start_to: parseStrictDateToIso(appliedFilters.endDate, 'end'),
            sort_by: appliedFilters.sortBy,
            limit: PAGE_SIZE,
            cursor:
              mode === 'loadMore' ? cursorOverride ?? undefined : undefined,
          },
          token,
        );
 
        setHasMore(response.page_info.has_next);
        setNextCursor(response.page_info.next_cursor);
 
        const filtered = excludeInProgressEvents(response.items);
        if (mode === 'loadMore') {
          setEvents((prev) => [...prev, ...filtered]);
        } else {
          setEvents(filtered);
        }
      } catch {
        setApiError('Failed to load events. Please try again.');
      } finally {
        if (mode === 'initial') setIsLoading(false);
        if (mode === 'refresh') setIsRefreshing(false);
        if (mode === 'loadMore') setIsLoadingMore(false);
      }
    },
    [token, selectedLocation, defaultLocation, appliedSearchText, selectedCategoryId, appliedFilters],
  );
 
  useEffect(() => {
    void loadCategories();
  }, [loadCategories]);
 
  useEffect(() => {
    let isMounted = true;
 
    setIsLocationContextReady(false);
    setIsResolvingDefaultLocation(true);
 
    void resolveDefaultLocation()
      .finally(() => {
        Iif (!isMounted) return;
        setIsLocationContextReady(true);
        setIsResolvingDefaultLocation(false);
      });
 
    return () => {
      isMounted = false;
    };
  }, [resolveDefaultLocation]);
 
  useEffect(() => {
    void fetchFavoriteLocations();
  }, [fetchFavoriteLocations]);
 
  useEffect(() => {
    if (!isLocationContextReady) return;
 
    const timeout = setTimeout(() => {
      void loadEvents('initial');
    }, 300);
 
    return () => clearTimeout(timeout);
  }, [isLocationContextReady, loadEvents]);
 
  const updateSearchText = useCallback((value: string) => {
    setSearchText(value);
 
    Iif (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
 
    const trimmed = value.trim();
 
    Iif (trimmed.length === 0) {
      setAppliedSearchText('');
      return;
    }
 
    Iif (trimmed.length < 2) return;
 
    searchTimeoutRef.current = setTimeout(() => {
      setAppliedSearchText(trimmed);
    }, 300);
  }, []);
 
  const submitSearch = useCallback(() => {
    if (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
    setAppliedSearchText(searchText.trim());
  }, [searchText]);
 
  const selectCategory = useCallback((categoryId: number | null) => {
    setSelectedCategoryId(categoryId);
  }, []);
 
  const openLocationModal = useCallback(() => {
    setPendingLocation(null);
    setLocationQuery('');
    setLocationSuggestions([]);
    setIsSearchingLocation(false);
    setIsLocationModalOpen(true);
  }, []);
 
  const closeLocationModal = useCallback(() => {
    Iif (locationSearchTimeoutRef.current) {
      clearTimeout(locationSearchTimeoutRef.current);
      locationSearchTimeoutRef.current = null;
    }
 
    setPendingLocation(null);
    setLocationQuery('');
    setLocationSuggestions([]);
    setIsSearchingLocation(false);
    setIsLocationModalOpen(false);
  }, []);
 
  const updateLocationQuery = useCallback((value: string) => {
    setLocationQuery(value);
 
    if (locationSearchTimeoutRef.current) {
      clearTimeout(locationSearchTimeoutRef.current);
    }
 
    if (value.trim().length === 0) {
      setPendingLocation(null);
      setLocationSuggestions([]);
      setIsSearchingLocation(false);
      return;
    }
 
    if (value.trim().length < 2) {
      setPendingLocation(null);
      setLocationSuggestions([]);
      setIsSearchingLocation(false);
      return;
    }
 
    locationSearchTimeoutRef.current = setTimeout(async () => {
      setIsSearchingLocation(true);
      try {
        const results = await searchLocation(value);
        setLocationSuggestions(results);
      } finally {
        setIsSearchingLocation(false);
        locationSearchTimeoutRef.current = null;
      }
    }, 300);
  }, []);
 
  const selectSavedLocationOption = useCallback((suggestion: LocationSuggestion) => {
    Iif (locationSearchTimeoutRef.current) {
      clearTimeout(locationSearchTimeoutRef.current);
      locationSearchTimeoutRef.current = null;
    }
 
    setPendingLocation(suggestion);
    setLocationQuery('');
    setLocationSuggestions([]);
    setIsSearchingLocation(false);
  }, []);
 
  const selectLocationSuggestion = useCallback((suggestion: LocationSuggestion) => {
    Iif (locationSearchTimeoutRef.current) {
      clearTimeout(locationSearchTimeoutRef.current);
      locationSearchTimeoutRef.current = null;
    }
 
    setPendingLocation(suggestion);
    setLocationQuery(suggestion.display_name);
    setLocationSuggestions([]);
    setIsSearchingLocation(false);
  }, []);
 
  const applySelectedLocation = useCallback(() => {
    Iif (!pendingLocation) {
      return;
    }
 
    const nextLocation = pendingLocation ?? defaultLocation ?? FALLBACK_LOCATION;
    const followsDefault =
      defaultLocation != null && locationsMatch(nextLocation, defaultLocation);
 
    persistLocationSelection(
      followsDefault ? 'DEFAULT' : 'CUSTOM',
      followsDefault ? null : nextLocation,
    );
    setSelectedLocation(nextLocation);
    setLocationSuggestions([]);
    setLocationQuery('');
    setIsLocationModalOpen(false);
  }, [defaultLocation, pendingLocation, persistLocationSelection]);
 
  const resetLocationDraft = useCallback(() => {
    Iif (locationSearchTimeoutRef.current) {
      clearTimeout(locationSearchTimeoutRef.current);
      locationSearchTimeoutRef.current = null;
    }
 
    setPendingLocation(null);
    setLocationQuery('');
    setLocationSuggestions([]);
    setIsSearchingLocation(false);
  }, []);
 
  const openFilterModal = useCallback(() => {
    setFilterDraft(appliedFilters);
    setFilterError(null);
    setIsFilterModalOpen(true);
  }, [appliedFilters]);
 
  const closeFilterModal = useCallback(() => {
    setFilterDraft(appliedFilters);
    setFilterError(null);
    setIsFilterModalOpen(false);
  }, [appliedFilters]);
 
  const resetFilterDraft = useCallback(() => {
    setFilterDraft(DEFAULT_FILTERS);
    setFilterError(null);
  }, []);
 
  const applyFilterDraft = useCallback(() => {
    const validationError = validateFilterDates(filterDraft);
 
    if (validationError) {
      setFilterError(validationError);
      return;
    }
 
    setFilterError(null);
    setAppliedFilters(filterDraft);
    setIsFilterModalOpen(false);
  }, [filterDraft]);
 
  const toggleDraftCategory = useCallback((categoryId: number) => {
    setFilterDraft((prev) => {
      const exists = prev.categoryIds.includes(categoryId);
 
      return {
        ...prev,
        categoryIds: exists
          ? prev.categoryIds.filter((id) => id !== categoryId)
          : [...prev.categoryIds, categoryId],
      };
    });
  }, []);
 
  const toggleDraftPrivacy = useCallback((privacy: HomeFilterPrivacyLevel) => {
    setFilterDraft((prev) => {
      const exists = prev.privacyLevels.includes(privacy);
 
      const nextDraft = {
        ...prev,
        privacyLevels: exists ? [] : [privacy],
      };
 
      setFilterError(validateFilterDatesLive(nextDraft));
      return nextDraft;
    });
  }, []);
 
  const updateDraftStartDate = useCallback((value: string) => {
    setFilterDraft((prev) => {
      const nextDraft = {
        ...prev,
        startDate: value,
      };
 
      setFilterError(validateFilterDatesLive(nextDraft));
      return nextDraft;
    });
  }, []);
 
  const updateDraftEndDate = useCallback((value: string) => {
    setFilterDraft((prev) => {
      const nextDraft = {
        ...prev,
        endDate: value,
      };
 
      setFilterError(validateFilterDatesLive(nextDraft));
      return nextDraft;
    });
  }, []);
 
  const updateDraftRadiusKm = useCallback((value: number) => {
    setFilterDraft((prev) => ({
      ...prev,
      radiusKm: Math.round(value),
    }));
  }, []);
 
  const updateDraftSortBy = useCallback((
    value: Extract<DiscoverEventsSortBy, 'START_TIME' | 'DISTANCE'>,
  ) => {
    setFilterDraft((prev) => ({
      ...prev,
      sortBy: value,
    }));
  }, []);
 
  const loadMoreEvents = useCallback(async () => {
    Iif (isLoading || isLoadingMore || isRefreshing || !hasMore || !nextCursor) {
      return;
    }
 
    await loadEvents('loadMore', nextCursor);
  }, [
    hasMore,
    isLoading,
    isLoadingMore,
    isRefreshing,
    loadEvents,
    nextCursor,
  ]);
 
  const refreshEvents = useCallback(async () => {
    await loadEvents('refresh');
  }, [loadEvents]);
 
  const retryFavoriteLocations = useCallback(async () => {
    await fetchFavoriteLocations();
  }, [fetchFavoriteLocations]);
 
  const silentRefresh = useCallback(async () => {
    Iif (!token) return;
 
    await fetchFavoriteLocations();
 
    try {
      const refreshedDefaultLocation = await resolveDefaultLocation();
      const persistedSelection = getHomeLocationSelection(locationSelectionScope);
      const activeLocation =
        persistedSelection.mode === 'CUSTOM' && persistedSelection.location
          ? persistedSelection.location
          : refreshedDefaultLocation;
 
      const combinedCategoryIds =
        selectedCategoryId != null
          ? Array.from(
            new Set([selectedCategoryId, ...appliedFilters.categoryIds]),
          )
          : appliedFilters.categoryIds;
 
      const response = await listEvents(
        {
          lat: Number(activeLocation.lat),
          lon: Number(activeLocation.lon),
          radius_meters: appliedFilters.radiusKm * 1000,
          q: appliedSearchText || undefined,
          category_ids:
            combinedCategoryIds.length > 0 ? combinedCategoryIds : undefined,
          privacy_levels:
            appliedFilters.privacyLevels.length > 0
              ? appliedFilters.privacyLevels
              : undefined,
          start_from: parseStrictDateToIso(appliedFilters.startDate, 'start'),
          start_to: parseStrictDateToIso(appliedFilters.endDate, 'end'),
          sort_by: appliedFilters.sortBy,
          limit: PAGE_SIZE,
        },
        token,
      );
 
      setHasMore(response.page_info.has_next);
      setNextCursor(response.page_info.next_cursor);
      setEvents(excludeInProgressEvents(response.items));
    } catch {
      // Silent refresh should not overwrite existing content with an error state.
    } finally {
      setIsResolvingDefaultLocation(false);
    }
  }, [
    token,
    fetchFavoriteLocations,
    resolveDefaultLocation,
    locationSelectionScope,
    appliedSearchText,
    selectedCategoryId,
    appliedFilters,
  ]);
 
  const favoriteLocationOptions: HomeLocationOption[] = favoriteLocations.map((location) => ({
    id: location.id,
    title: location.name,
    subtitle: location.address,
    suggestion: favoriteLocationToSuggestion(location),
  }));
 
  return {
    locationLabel: selectedLocation
      ? formatEventLocation(selectedLocation.display_name)
      : isResolvingDefaultLocation
        ? 'Locating...'
        : DEFAULT_LOCATION_LABEL,
    locationQuery,
    categories,
    selectedCategoryId,
    searchText,
    events,
    isLoading,
    isLoadingMore,
    isRefreshing,
    apiError,
    hasMore,
    isFilterModalOpen,
    filterDraft,
    filterError,
    locationSuggestions,
    isSearchingLocation,
    isLocationModalOpen,
    pendingLocation,
    defaultLocationOption: {
      title: 'Use Default Location',
      subtitle: getDefaultLocationSubtitle(
        defaultLocationSource,
        defaultLocation,
        isResolvingDefaultLocation,
      ),
      suggestion: defaultLocation,
      isLoading: isResolvingDefaultLocation && !defaultLocation,
    },
    favoriteLocationOptions,
    isLoadingFavoriteLocations,
    favoriteLocationsError,
    updateSearchText,
    submitSearch,
    selectCategory,
    openFilterModal,
    closeFilterModal,
    resetFilterDraft,
    applyFilterDraft,
    toggleDraftCategory,
    toggleDraftPrivacy,
    updateDraftStartDate,
    updateDraftEndDate,
    updateDraftRadiusKm,
    updateDraftSortBy,
    openLocationModal,
    closeLocationModal,
    updateLocationQuery,
    selectSavedLocationOption,
    selectLocationSuggestion,
    applySelectedLocation,
    resetLocationDraft,
    retryFavoriteLocations,
    loadMoreEvents,
    refreshEvents,
    silentRefresh,
  };
}