All files / src/viewmodels/event useCreateEventViewModel.ts

82.59% Statements 446/540
73.78% Branches 259/351
86.84% Functions 66/76
87.76% Lines 409/466

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 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 10972x 2x 2x 2x 2x 2x                               2x                                             2x   2x         2x     2x   2x                                                                                                                                                           2x 10x 10x 10x 10x       16x       16x 16x           2x 7x   7x 11x 11x 4x     7x       5x       5x   5x 7x 7x         4x   3x       1x     2x                                                 2x   9x   9x   8x 3x     5x 4x         11x 11x 11x 9x 9x 5x 5x     2x 11x 11x 11x 3x   8x       2x 141x 141x 141x 141x 141x 141x 141x 141x 141x 141x   141x 141x 141x           4x   137x       2x 78x 78x 78x 78x 78x 78x 78x 78x 78x       299x       230x     2x 156x   156x 156x 156x   156x 155x 155x 8x       148x 145x 145x 4x       144x 141x     3x     2x 93x   93x 93x 93x   93x 92x 92x 8x       85x 82x 82x 4x       81x 78x     3x       85x 85x 85x 85x 85x 85x 85x     2x 2x 2x 2x 2x           143x             143x 6x   137x     143x 68x   75x       143x         143x 52x 52x   52x 6x       143x 143x 12x     12x     12x     12x       12x         12x 12x 12x       12x   12x 10x         143x       28x   28x 28x 4x 24x 1x 23x       28x 28x 4x 24x 1x 23x       28x 4x     28x 4x     28x   28x       2x       2x 2x 1x     1x       1x       1x 1x                         231x         21x                                                                                     21x     2x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x 277x   277x 318x       318x     277x 57x 57x         277x 75x 75x 41x 41x   75x     277x   309x   309x     309x 309x 309x   309x 309x 309x   309x 309x 309x         277x       277x 115x 115x 115x       115x   305x     70x     45x           45x 139x 1x     138x   45x   23x 23x 92x 91x       23x                   277x 1x 1x   1x       1x         1x 1x 1x 1x 1x       277x 2x             2x 2x     277x 1x             1x     277x 11x 11x 11x 9x       9x   11x     277x 1x   2x       277x 3x 3x 3x 3x 2x 2x           3x     277x 23x 23x 1x 1x     22x 22x 22x 23x 23x     22x         22x 22x   22x               6x 6x 6x 6x 6x 6x 2x 2x     4x 2x 2x         4x 2x 2x 2x 1x 1x   1x 2x 2x       3x 3x 3x     6x 6x 6x 6x 3x 3x   3x 3x 3x     10x 10x 10x 10x       16x 16x 16x               277x             277x 6x   6x 6x 6x 1x 1x 1x 1x     5x             5x   5x 5x         5x 5x 4x   1x 1x     4x           277x         277x   3x 3x   3x             3x             3x   3x 6x 3x         3x                     1x   3x           277x   28x 28x 63x 28x 19x 19x     9x 9x 9x 9x 9x   9x 9x   9x               9x   9x                                               9x   9x                                     9x 6x     6x 3x 3x 1x 1x 1x         2x       6x   3x 2x 1x 1x 2x 1x 1x 1x   1x         1x   2x   1x   3x   9x           277x                                                          
import { useState, useCallback, useRef, useMemo, useEffect } from 'react';
import { Alert } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
import * as ImageManipulator from 'expo-image-manipulator';
import { ApiError } from '@/services/api';
import {
  createEvent,
  searchLocation,
  getEventImageUploadUrl,
  uploadFileToPresignedUrl,
  confirmEventImageUpload,
} from '@/services/eventService';
import {
  PrivacyLevel,
  LocationSuggestion,
  CreateEventRequest,
  CreateEventResponse,
  EventConstraint,
  EventCategory,
} from '@/models/event';
 
export const CATEGORIES: EventCategory[] = [
  { id: 1, name: 'Sports' },
  { id: 2, name: 'Music' },
  { id: 3, name: 'Education' },
  { id: 4, name: 'Technology' },
  { id: 5, name: 'Art' },
  { id: 6, name: 'Food & Drink' },
  { id: 7, name: 'Outdoors' },
  { id: 8, name: 'Fitness' },
  { id: 9, name: 'Networking' },
  { id: 10, name: 'Gaming' },
  { id: 11, name: 'Charity' },
  { id: 12, name: 'Photography' },
  { id: 13, name: 'Travel' },
  { id: 14, name: 'Workshops' },
  { id: 15, name: 'Conferences' },
  { id: 16, name: 'Movies & Cinema' },
  { id: 17, name: 'Theatre' },
  { id: 18, name: 'Books & Literature' },
  { id: 19, name: 'Wellness' },
  { id: 20, name: 'Volunteering' },
];
 
export const CATEGORY_PREVIEW_COUNT = 6;
 
export const PRIVACY_OPTIONS: { label: string; value: PrivacyLevel }[] = [
  { label: 'Public', value: 'PUBLIC' },
  { label: 'Protected', value: 'PROTECTED' },
];
 
export const CONSTRAINT_TYPES = ['gender', 'age', 'capacity', 'other'] as const;
export type ConstraintType = (typeof CONSTRAINT_TYPES)[number];
 
export const MAX_CONSTRAINTS = 5;
 
export const CONSTRAINT_TYPE_LIMITS: Record<ConstraintType, number> = {
  gender: 1,
  age: 1,
  capacity: 1,
  other: MAX_CONSTRAINTS,
};
 
export interface CreateEventFormData {
  title: string;
  description: string;
  imageUrl: string;
  categoryId: number | null;
  locationQuery: string;
  address: string;
  lat: number | null;
  lon: number | null;
  startDate: string;
  startTime: string;
  endDate: string;
  endTime: string;
  privacyLevel: PrivacyLevel;
  tags: string[];
  tagInput: string;
  constraints: EventConstraint[];
  constraintType: ConstraintType;
  // Type-specific constraint inputs
  genderConstraintValue: 'MALE' | 'FEMALE' | null;
  ageMinInput: string;
  ageMaxInput: string;
  capacityInput: string;
  otherConstraintInput: string;
}
 
export interface CreateEventFormErrors {
  title?: string | null;
  description?: string | null;
  categoryId?: string | null;
  location?: string | null;
  startDate?: string | null;
  startTime?: string | null;
  endDate?: string | null;
  endTime?: string | null;
  tags?: string | null;
  constraints?: string | null;
}
 
export interface CreateEventViewModel {
  formData: CreateEventFormData;
  errors: CreateEventFormErrors;
  isLoading: boolean;
  isUploadingImage: boolean;
  apiError: string | null;
  imageError: string | null;
  successMessage: string | null;
  imageUploadSuccessMessage: string | null;
  selectedImageUri: string | null;
  locationSuggestions: LocationSuggestion[];
  isSearchingLocation: boolean;
  categoriesExpanded: boolean;
  constraintTypeCounts: Record<ConstraintType, number>;
  updateField: <K extends keyof CreateEventFormData>(
    field: K,
    value: CreateEventFormData[K],
  ) => void;
  handleLocationSearch: (query: string) => void;
  selectLocation: (suggestion: LocationSuggestion) => void;
  clearLocation: () => void;
  toggleCategoriesExpanded: () => void;
  addTag: () => void;
  removeTag: (index: number) => void;
  addGenderConstraint: (gender: 'MALE' | 'FEMALE') => void;
  addConstraint: () => void;
  removeConstraint: (index: number) => void;
  pickImage: () => Promise<void>;
  removeImage: () => void;
  handleSubmit: (token: string) => Promise<CreateEventResponse | null>;
}
 
export function formatDateForForm(date: Date): string {
  const day = String(date.getDate()).padStart(2, '0');
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const year = String(date.getFullYear());
  return `${day}.${month}.${year}`;
}
 
function decodeFileUriOnce(uri: string): string {
  Iif (!uri.startsWith('file://')) {
    return uri;
  }
 
  try {
    return `file://${decodeURIComponent(uri.slice('file://'.length))}`;
  } catch {
    return uri;
  }
}
 
export function normalizePickedImageUri(uri: string): string {
  let normalized = uri;
 
  for (let i = 0; i < 3; i += 1) {
    const next = decodeFileUriOnce(normalized);
    if (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');
}
 
export const INITIAL_FORM_DATA: CreateEventFormData = {
  title: '',
  description: '',
  imageUrl: '',
  categoryId: null,
  locationQuery: '',
  address: '',
  lat: null,
  lon: null,
  startDate: formatDateForForm(new Date()),
  startTime: '',
  endDate: '',
  endTime: '',
  privacyLevel: 'PUBLIC',
  tags: [],
  tagInput: '',
  constraints: [],
  constraintType: 'gender',
  genderConstraintValue: null,
  ageMinInput: '',
  ageMaxInput: '',
  capacityInput: '',
  otherConstraintInput: '',
};
 
export function formatTimeInput(current: string, previous: string): string {
  // Strip non-digit and non-colon characters
  const cleaned = current.replace(/[^\d:]/g, '');
  // If user is deleting, don't auto-format
  if (cleaned.length < previous.length) return cleaned;
  // After typing 2 digits, auto-insert ':'
  if (cleaned.length === 2 && !cleaned.includes(':')) {
    return cleaned + ':';
  }
  // Limit to HH:mm format (5 chars)
  if (cleaned.length > 5) return cleaned.slice(0, 5);
  return cleaned;
}
 
/** Formats typing into `dd.mm.yyyy` with auto-inserted dots (like `formatTimeInput` for times). */
function formatDigitsToDate(digits: string): string {
  Iif (digits.length === 0) return '';
  const day = digits.slice(0, 2);
  if (digits.length <= 2) return day;
  const month = digits.slice(2, 4);
  if (digits.length <= 4) return `${day}.${month}`;
  const year = digits.slice(4, 8);
  return `${day}.${month}.${year}`;
}
 
export function formatDateInput(current: string, previous: string): string {
  const digits = current.replace(/\D/g, '');
  const prevDigits = previous.replace(/\D/g, '');
  if (digits.length < prevDigits.length) {
    return formatDigitsToDate(digits);
  }
  return formatDigitsToDate(digits.slice(0, 8));
}
 
/** Returns an error message if the date string (dd.mm.yyyy) is invalid, or null if valid. */
export function validateDateFormat(date: string): string | null {
  const parts = date.split('.');
  Iif (parts.length !== 3) return 'Invalid date format';
  const [dayStr, monthStr, yearStr] = parts;
  Iif (yearStr.length < 4) return 'Invalid date format';
  const day = parseInt(dayStr, 10);
  const month = parseInt(monthStr, 10);
  const year = parseInt(yearStr, 10);
  Iif (isNaN(day) || isNaN(month) || isNaN(year)) return 'Invalid date';
  Iif (month < 1 || month > 12) return 'Invalid date: month must be 1–12';
  Iif (day < 1 || day > 31) return 'Invalid date: day must be 1–31';
  // Guard against JS Date silently normalizing overflow (e.g. 30.02.2030 → March)
  const iso = `${year}-${monthStr.padStart(2, '0')}-${dayStr.padStart(2, '0')}T00:00:00`;
  const parsed = new Date(iso);
  if (
    isNaN(parsed.getTime()) ||
    parsed.getFullYear() !== year ||
    parsed.getMonth() + 1 !== month ||
    parsed.getDate() !== day
  ) {
    return 'Invalid date';
  }
  return null;
}
 
/** Returns an error message if the time string (HH:mm) is invalid, or null if valid. */
export function validateTimeFormat(time: string): string | null {
  const parts = time.split(':');
  Iif (parts.length !== 2) return 'Invalid time format';
  const [hourStr, minuteStr] = parts;
  const hour = parseInt(hourStr, 10);
  const minute = parseInt(minuteStr, 10);
  Iif (isNaN(hour) || isNaN(minute)) return 'Invalid time';
  Iif (hour < 0 || hour > 23) return 'Invalid time: hour must be 0–23';
  Iif (minute < 0 || minute > 59) return 'Invalid time: minute must be 0–59';
  return null;
}
 
function isCompleteDateInput(date: string): boolean {
  return date.length === 10;
}
 
function isCompleteTimeInput(time: string): boolean {
  return time.length === 5;
}
 
export function validateLiveDateInput(date: string): string | null {
  Iif (!date) return null;
 
  const parts = date.split('.');
  const dayStr = parts[0] ?? '';
  const monthStr = parts[1] ?? '';
 
  if (dayStr.length === 2) {
    const day = parseInt(dayStr, 10);
    if (isNaN(day) || day < 1 || day > 31) {
      return 'Invalid date: day must be 1-31';
    }
  }
 
  if (monthStr.length === 2) {
    const month = parseInt(monthStr, 10);
    if (isNaN(month) || month < 1 || month > 12) {
      return 'Invalid date: month must be 1-12';
    }
  }
 
  if (isCompleteDateInput(date)) {
    return validateDateFormat(date);
  }
 
  return null;
}
 
export function validateLiveTimeInput(time: string): string | null {
  Iif (!time) return null;
 
  const parts = time.split(':');
  const hourStr = parts[0] ?? '';
  const minuteStr = parts[1] ?? '';
 
  if (hourStr.length === 2) {
    const hour = parseInt(hourStr, 10);
    if (isNaN(hour) || hour < 0 || hour > 23) {
      return 'Invalid time: hour must be 0-23';
    }
  }
 
  if (minuteStr.length === 2) {
    const minute = parseInt(minuteStr, 10);
    if (isNaN(minute) || minute < 0 || minute > 59) {
      return 'Invalid time: minute must be 0-59';
    }
  }
 
  if (isCompleteTimeInput(time)) {
    return validateTimeFormat(time);
  }
 
  return null;
}
 
function parseDateTime(date: string, time: string): string | null {
  Iif (!date || !time) return null;
  const [dayStr, monthStr, yearStr] = date.split('.');
  Iif (!dayStr || !monthStr || !yearStr) return null;
  const iso = `${yearStr}-${monthStr.padStart(2, '0')}-${dayStr.padStart(2, '0')}T${time}:00`;
  const parsed = new Date(iso);
  Iif (isNaN(parsed.getTime())) return null;
  return parsed.toISOString();
}
 
export const TITLE_MIN_LENGTH = 10;
export const TITLE_MAX_LENGTH = 60;
export const DESCRIPTION_MIN_LENGTH = 20;
export const DESCRIPTION_MAX_LENGTH = 600;
export const CAPACITY_MIN = 2;
 
function getDateTimeErrors(
  formData: CreateEventFormData,
  requireMissingFields: boolean,
): Pick<CreateEventFormErrors, 'startDate' | 'startTime' | 'endDate' | 'endTime'> {
  const errors: Pick<CreateEventFormErrors, 'startDate' | 'startTime' | 'endDate' | 'endTime'> = {
    startDate: null,
    startTime: null,
    endDate: null,
    endTime: null,
  };
 
  if (!formData.startDate) {
    if (requireMissingFields) errors.startDate = 'Start date is required';
  } else {
    errors.startDate = validateLiveDateInput(formData.startDate);
  }
 
  if (!formData.startTime) {
    if (requireMissingFields) errors.startTime = 'Start time is required';
  } else {
    errors.startTime = validateLiveTimeInput(formData.startTime);
  }
 
  const hasComparableStartDateTime =
    isCompleteDateInput(formData.startDate) &&
    isCompleteTimeInput(formData.startTime) &&
    !errors.startDate &&
    !errors.startTime;
 
  if (hasComparableStartDateTime) {
    const parsedStart = parseDateTime(formData.startDate, formData.startTime);
    Iif (!parsedStart) {
      errors.startDate = 'Invalid start date';
    } else if (new Date(parsedStart) <= new Date()) {
      errors.startDate = 'Start date must be in the future';
    }
  }
 
  const hasEndInput = Boolean(formData.endDate || formData.endTime);
  if (hasEndInput) {
    Iif (!formData.endDate) {
      if (requireMissingFields) errors.endDate = 'End date is required';
    } else {
      errors.endDate = validateLiveDateInput(formData.endDate);
    }
 
    Iif (!formData.endTime) {
      if (requireMissingFields) errors.endTime = 'End time is required';
    } else {
      errors.endTime = validateLiveTimeInput(formData.endTime);
    }
 
    const hasComparableEndDateTime =
      isCompleteDateInput(formData.endDate) &&
      isCompleteTimeInput(formData.endTime) &&
      !errors.endDate &&
      !errors.endTime;
 
    Eif (hasComparableEndDateTime) {
      const parsedEnd = parseDateTime(formData.endDate, formData.endTime);
      const parsedStart = hasComparableStartDateTime
        ? parseDateTime(formData.startDate, formData.startTime)
        : null;
 
      Iif (!parsedEnd) {
        errors.endDate = 'Invalid end date';
      } else if (parsedStart && new Date(parsedEnd) <= new Date(parsedStart)) {
        errors.endDate = 'End must be after start';
      }
    }
  }
 
  return errors;
}
 
function validateForm(formData: CreateEventFormData): CreateEventFormErrors {
  const errors: CreateEventFormErrors = {};
 
  const trimmedTitle = formData.title.trim();
  if (!trimmedTitle) {
    errors.title = 'Title is required';
  } else if (trimmedTitle.length < TITLE_MIN_LENGTH) {
    errors.title = `Title must be at least ${TITLE_MIN_LENGTH} characters`;
  } else Iif (trimmedTitle.length > TITLE_MAX_LENGTH) {
    errors.title = `Title must be at most ${TITLE_MAX_LENGTH} characters`;
  }
 
  const trimmedDescription = formData.description.trim();
  if (!trimmedDescription) {
    errors.description = 'Description is required';
  } else if (trimmedDescription.length < DESCRIPTION_MIN_LENGTH) {
    errors.description = `Description must be at least ${DESCRIPTION_MIN_LENGTH} characters`;
  } else Iif (trimmedDescription.length > DESCRIPTION_MAX_LENGTH) {
    errors.description = `Description must be at most ${DESCRIPTION_MAX_LENGTH} characters`;
  }
 
  if (formData.categoryId === null) {
    errors.categoryId = 'Please select a category';
  }
 
  if (formData.lat === null || formData.lon === null) {
    errors.location = 'Please select a location';
  }
 
  Object.assign(errors, getDateTimeErrors(formData, true));
 
  return errors;
}
 
function getImageUploadErrorMessage(error: unknown): string {
  Iif (error instanceof ApiError) {
    return error.message;
  }
 
  Eif (error instanceof Error) {
    if (error.message === 'Network request failed') {
      return 'The event was created, but uploading the image failed because the network request did not complete.';
    }
 
    Iif (error.message === 'Missing upload instructions from server') {
      return 'The server returned incomplete image upload instructions.';
    }
 
    Iif (error.message.startsWith('Unsupported upload method')) {
      return 'The server returned an unsupported image upload method.';
    }
 
    Eif (error.message.startsWith('Upload failed with status')) {
      return 'The event was created, but uploading the image to storage failed.';
    }
 
    return error.message;
  }
 
  return 'The event was created, but the image upload failed.';
}
 
function isLocalDateTimeError(
  field: 'startDate' | 'startTime' | 'endDate' | 'endTime',
  error: string | null | undefined,
): boolean {
  if (error == null) return true;
 
  const localErrorsByField: Record<
    'startDate' | 'startTime' | 'endDate' | 'endTime',
    Set<string>
  > = {
    startDate: new Set([
      'Start date is required',
      'Invalid date format',
      'Invalid date',
      'Invalid date: day must be 1–31',
      'Invalid date: month must be 1–12',
      'Invalid date: day must be 1-31',
      'Invalid date: month must be 1-12',
      'Start date must be in the future',
      'Invalid start date',
    ]),
    startTime: new Set([
      'Start time is required',
      'Invalid time format',
      'Invalid time',
      'Invalid time: hour must be 0–23',
      'Invalid time: minute must be 0–59',
      'Invalid time: hour must be 0-23',
      'Invalid time: minute must be 0-59',
    ]),
    endDate: new Set([
      'End date is required',
      'Invalid date format',
      'Invalid date',
      'Invalid date: day must be 1–31',
      'Invalid date: month must be 1–12',
      'Invalid date: day must be 1-31',
      'Invalid date: month must be 1-12',
      'End must be after start',
      'Invalid end date',
    ]),
    endTime: new Set([
      'End time is required',
      'Invalid time format',
      'Invalid time',
      'Invalid time: hour must be 0–23',
      'Invalid time: minute must be 0–59',
      'Invalid time: hour must be 0-23',
      'Invalid time: minute must be 0-59',
    ]),
  };
 
  return localErrorsByField[field].has(error);
}
 
export function useCreateEventViewModel(): CreateEventViewModel {
  const [formData, setFormData] = useState<CreateEventFormData>(INITIAL_FORM_DATA);
  const [errors, setErrors] = useState<CreateEventFormErrors>({});
  const [isLoading, setIsLoading] = useState(false);
  const [apiError, setApiError] = useState<string | null>(null);
  const [imageError, setImageError] = useState<string | null>(null);
  const [successMessage, setSuccessMessage] = useState<string | null>(null);
  const [imageUploadSuccessMessage, setImageUploadSuccessMessage] = useState<string | null>(null);
  const [locationSuggestions, setLocationSuggestions] = useState<LocationSuggestion[]>([]);
  const [isSearchingLocation, setIsSearchingLocation] = useState(false);
  const [categoriesExpanded, setCategoriesExpanded] = useState(false);
  const [selectedImageUri, setSelectedImageUri] = useState<string | null>(null);
  const [isUploadingImage, setIsUploadingImage] = useState(false);
  const [hasAttemptedSubmit, setHasAttemptedSubmit] = useState(false);
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const imageUploadSuccessTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
 
  const clearImageUploadSuccessMessage = useCallback(() => {
    Iif (imageUploadSuccessTimerRef.current) {
      clearTimeout(imageUploadSuccessTimerRef.current);
      imageUploadSuccessTimerRef.current = null;
    }
    setImageUploadSuccessMessage(null);
  }, []);
 
  useEffect(
    () => () => {
      if (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
    },
    [],
  );
 
  const constraintTypeCounts = useMemo(() => {
    const counts: Record<ConstraintType, number> = { gender: 0, age: 0, capacity: 0, other: 0 };
    formData.constraints.forEach((c) => {
      const t = c.type as ConstraintType;
      Eif (t in counts) counts[t]++;
    });
    return counts;
  }, [formData.constraints]);
 
  const updateField = useCallback(
    <K extends keyof CreateEventFormData>(field: K, value: CreateEventFormData[K]) => {
      setFormData((prev) => ({ ...prev, [field]: value }));
      // Map form fields to their corresponding error keys
      const errorKeyMap: Partial<Record<keyof CreateEventFormData, keyof CreateEventFormErrors>> = {
        locationQuery: 'location',
      };
      const errorKey = (errorKeyMap[field] ?? field) as keyof CreateEventFormErrors;
      setErrors((prev) => {
        const next = { ...prev, [errorKey]: null };
        // Time changes also clear the associated date error (cross-field "must be after" constraint)
        if (field === 'startTime') next.startDate = null;
        if (field === 'endTime') next.endDate = null;
        return next;
      });
      setApiError(null);
      setSuccessMessage(null);
      clearImageUploadSuccessMessage();
    },
    [clearImageUploadSuccessMessage],
  );
 
  const toggleCategoriesExpanded = useCallback(() => {
    setCategoriesExpanded((prev) => !prev);
  }, []);
 
  useEffect(() => {
    const nextDateTimeErrors = getDateTimeErrors(formData, hasAttemptedSubmit);
    setErrors((prev) => {
      const hasExistingDateTimeError = Boolean(
        prev.startDate || prev.startTime || prev.endDate || prev.endTime,
      );
 
      if (
        !hasAttemptedSubmit &&
        Object.values(nextDateTimeErrors).every((value) => value == null) &&
        !hasExistingDateTimeError
      ) {
        return prev;
      }
 
      const dateTimeKeys: Array<keyof typeof nextDateTimeErrors> = [
        'startDate',
        'startTime',
        'endDate',
        'endTime',
      ];
      const changed = dateTimeKeys.some((key) => {
        if (!isLocalDateTimeError(key, prev[key])) {
          return false;
        }
 
        return prev[key] !== nextDateTimeErrors[key];
      });
      if (!changed) return prev;
 
      const nextErrors = { ...prev };
      dateTimeKeys.forEach((key) => {
        if (isLocalDateTimeError(key, prev[key])) {
          nextErrors[key] = nextDateTimeErrors[key];
        }
      });
 
      return nextErrors;
    });
  }, [
    formData.startDate,
    formData.startTime,
    formData.endDate,
    formData.endTime,
    hasAttemptedSubmit,
  ]);
 
  const handleLocationSearch = useCallback((query: string) => {
    setFormData((prev) => ({ ...prev, locationQuery: query }));
    setErrors((prev) => ({ ...prev, location: null }));
 
    Iif (searchTimeoutRef.current) {
      clearTimeout(searchTimeoutRef.current);
    }
 
    Iif (query.trim().length < 2) {
      setLocationSuggestions([]);
      return;
    }
 
    searchTimeoutRef.current = setTimeout(async () => {
      setIsSearchingLocation(true);
      const results = await searchLocation(query);
      setLocationSuggestions(results);
      setIsSearchingLocation(false);
    }, 400);
  }, []);
 
  const selectLocation = useCallback((suggestion: LocationSuggestion) => {
    setFormData((prev) => ({
      ...prev,
      locationQuery: suggestion.display_name,
      address: suggestion.display_name,
      lat: parseFloat(suggestion.lat),
      lon: parseFloat(suggestion.lon),
    }));
    setLocationSuggestions([]);
    setErrors((prev) => ({ ...prev, location: null }));
  }, []);
 
  const clearLocation = useCallback(() => {
    setFormData((prev) => ({
      ...prev,
      locationQuery: '',
      address: '',
      lat: null,
      lon: null,
    }));
    setLocationSuggestions([]);
  }, []);
 
  const addTag = useCallback(() => {
    setFormData((prev) => {
      const tag = prev.tagInput.trim();
      if (!tag || prev.tags.length >= 5 || prev.tags.includes(tag)) return prev;
      Iif (tag.length > 20) {
        setErrors((e) => ({ ...e, tags: 'Each tag must be at most 20 characters' }));
        return prev;
      }
      return { ...prev, tags: [...prev.tags, tag], tagInput: '' };
    });
    setErrors((prev) => ({ ...prev, tags: null }));
  }, []);
 
  const removeTag = useCallback((index: number) => {
    setFormData((prev) => ({
      ...prev,
      tags: prev.tags.filter((_, i) => i !== index),
    }));
  }, []);
 
  const addGenderConstraint = useCallback((gender: 'MALE' | 'FEMALE') => {
    setFormData((prev) => {
      Iif (prev.constraints.length >= MAX_CONSTRAINTS) return prev;
      const genderCount = prev.constraints.filter((c) => c.type === 'gender').length;
      if (genderCount >= CONSTRAINT_TYPE_LIMITS.gender) return prev;
      const info = gender === 'MALE' ? 'Males only' : 'Females only';
      return {
        ...prev,
        constraints: [...prev.constraints, { type: 'gender', info }],
        genderConstraintValue: null,
      };
    });
    setErrors((prev) => ({ ...prev, constraints: null }));
  }, []);
 
  const addConstraint = useCallback(() => {
    setFormData((prev) => {
      if (prev.constraints.length >= MAX_CONSTRAINTS) {
        setErrors((e) => ({ ...e, constraints: `Maximum ${MAX_CONSTRAINTS} constraints allowed` }));
        return prev;
      }
 
      const type = prev.constraintType;
      const typeCounts: Record<ConstraintType, number> = { gender: 0, age: 0, capacity: 0, other: 0 };
      prev.constraints.forEach((c) => {
        const t = c.type as ConstraintType;
        Eif (t in typeCounts) typeCounts[t]++;
      });
 
      Iif (typeCounts[type] >= CONSTRAINT_TYPE_LIMITS[type]) {
        setErrors((e) => ({ ...e, constraints: `Only ${CONSTRAINT_TYPE_LIMITS[type]} ${type} constraint allowed` }));
        return prev;
      }
 
      let info = '';
      const updates: Partial<CreateEventFormData> = {};
 
      switch (type) {
        case 'gender': {
          if (!prev.genderConstraintValue) return prev;
          info = prev.genderConstraintValue === 'MALE' ? 'Males only' : 'Females only';
          updates.genderConstraintValue = null;
          break;
        }
        case 'age': {
          const min = prev.ageMinInput.trim();
          const max = prev.ageMaxInput.trim();
          Iif (!min && !max) return prev;
          Eif (min) {
            const minNum = parseInt(min, 10);
            if (isNaN(minNum) || minNum < 0 || minNum > 120) {
              setErrors((e) => ({ ...e, constraints: 'Age must be between 0 and 120' }));
              return prev;
            }
          }
          if (max) {
            const maxNum = parseInt(max, 10);
            Iif (isNaN(maxNum) || maxNum < 0 || maxNum > 120) {
              setErrors((e) => ({ ...e, constraints: 'Age must be between 0 and 120' }));
              return prev;
            }
          }
          if (min && max) {
            const minNum = parseInt(min, 10);
            const maxNum = parseInt(max, 10);
            if (minNum > maxNum) {
              setErrors((e) => ({ ...e, constraints: 'Minimum age cannot be greater than maximum age' }));
              return prev;
            }
            info = `Ages ${minNum}–${maxNum}`;
          } else if (min) {
            info = `${parseInt(min, 10)}+`;
          } else E{
            info = `Under ${parseInt(max, 10)}`;
          }
          updates.ageMinInput = '';
          updates.ageMaxInput = '';
          break;
        }
        case 'capacity': {
          const cap = prev.capacityInput.trim();
          Iif (!cap) return prev;
          const capNum = parseInt(cap, 10);
          if (isNaN(capNum) || capNum < CAPACITY_MIN) {
            setErrors((e) => ({ ...e, constraints: `Capacity must be at least ${CAPACITY_MIN}` }));
            return prev;
          }
          info = `${capNum} participants`;
          updates.capacityInput = '';
          break;
        }
        case 'other': {
          info = prev.otherConstraintInput.trim();
          Iif (!info) return prev;
          updates.otherConstraintInput = '';
          break;
        }
      }
 
      setErrors((e) => ({ ...e, constraints: null }));
      const constraint: EventConstraint = { type, info };
      return {
        ...prev,
        ...updates,
        constraints: [...prev.constraints, constraint],
      };
    });
  }, []);
 
  const removeConstraint = useCallback((index: number) => {
    setFormData((prev) => ({
      ...prev,
      constraints: prev.constraints.filter((_, i) => i !== index),
    }));
  }, []);
 
  const pickImage = useCallback(async () => {
    setImageError(null);
 
    try {
      const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
      if (status !== 'granted') {
        const message = 'Please allow access to your photo library to add an event image.';
        setImageError(message);
        Alert.alert('Permission required', message);
        return;
      }
 
      const result = await ImagePicker.launchImageLibraryAsync({
        mediaTypes: ['images'],
        allowsEditing: true,
        aspect: [16, 9],
        quality: 0.8,
      });
 
      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;
      }
 
      try {
        const preparedImageUri = await preparePickedImageUri(asset.uri);
        setSelectedImageUri(preparedImageUri);
      } catch {
        setImageError('We could not process the selected image. Please try a different one.');
        return;
      }
 
      setSuccessMessage(null);
    } catch {
      setImageError('We could not open your photo library. Please try again.');
    }
  }, []);
 
  const removeImage = useCallback(() => {
    setSelectedImageUri(null);
    setImageError(null);
  }, []);
 
  const uploadEventImage = useCallback(
    async (eventId: string, imageUri: string, token: string): Promise<void> => {
      setIsUploadingImage(true);
      try {
        // Resize to original (max 1200px wide) as JPEG
        const original = await ImageManipulator.manipulateAsync(
          imageUri,
          [{ resize: { width: 1200 } }],
          { compress: 0.8, format: ImageManipulator.SaveFormat.JPEG },
        );
 
        // Resize to small thumbnail (max 400px wide) as JPEG
        const small = await ImageManipulator.manipulateAsync(
          imageUri,
          [{ resize: { width: 400 } }],
          { compress: 0.7, format: ImageManipulator.SaveFormat.JPEG },
        );
 
        // 1. Get presigned upload URLs
        const uploadInit = await getEventImageUploadUrl(eventId, 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');
        }
 
        // 2. Upload both variants
        await Promise.all([
          uploadFileToPresignedUrl(
            originalUpload.method,
            originalUpload.url,
            originalUpload.headers,
            original.uri,
          ),
          uploadFileToPresignedUrl(smallUpload.method, smallUpload.url, smallUpload.headers, small.uri),
        ]);
 
        // 3. Confirm
        await confirmEventImageUpload(eventId, uploadInit.confirm_token, token);
      } finally {
        setIsUploadingImage(false);
      }
    },
    [],
  );
 
  const handleSubmit = useCallback(
    async (token: string): Promise<CreateEventResponse | null> => {
      setHasAttemptedSubmit(true);
      const validationErrors = validateForm(formData);
      const hasErrors = Object.values(validationErrors).some((e) => e != null);
      if (hasErrors) {
        setErrors(validationErrors);
        return null;
      }
 
      setIsLoading(true);
      setApiError(null);
      setImageError(null);
      setSuccessMessage(null);
      clearImageUploadSuccessMessage();
 
      try {
        const startTimeISO = parseDateTime(formData.startDate, formData.startTime)!;
        const endTimeISO =
          formData.endDate && formData.endTime
            ? parseDateTime(formData.endDate, formData.endTime) ?? undefined
            : undefined;
 
        // Map structured constraints to first-class API fields
        let preferredGender: 'MALE' | 'FEMALE' | undefined;
        let minimumAge: number | undefined;
        let capacity: number | undefined;
        const otherConstraints: EventConstraint[] = [];
 
        for (const c of formData.constraints) {
          switch (c.type) {
            case 'gender':
              preferredGender = c.info === 'Males only' ? 'MALE' : 'FEMALE';
              break;
            case 'age': {
              // Formats: "18+", "Ages 18–30", "Under 30"
              const plusMatch = c.info.match(/^(\d+)\+$/);
              const rangeMatch = c.info.match(/^Ages (\d+)/);
              if (plusMatch) minimumAge = parseInt(plusMatch[1], 10);
              else if (rangeMatch) minimumAge = parseInt(rangeMatch[1], 10);
              break;
            }
            case 'capacity': {
              const capMatch = c.info.match(/(\d+)/);
              if (capMatch) capacity = parseInt(capMatch[1], 10);
              break;
            }
            case 'other':
              otherConstraints.push(c);
              break;
          }
        }
 
        const address = formData.address || undefined;
 
        const request: CreateEventRequest = {
          title: formData.title.trim(),
          description: formData.description.trim(),
          image_url: formData.imageUrl.trim() || undefined,
          category_id: formData.categoryId!,
          address,
          lat: formData.lat ?? undefined,
          lon: formData.lon ?? undefined,
          location_type: 'POINT',
          start_time: startTimeISO,
          end_time: endTimeISO,
          privacy_level: formData.privacyLevel,
          tags: formData.tags.length > 0 ? formData.tags : undefined,
          constraints: otherConstraints.length > 0 ? otherConstraints : undefined,
          preferred_gender: preferredGender,
          minimum_age: minimumAge,
          capacity,
        };
 
        const result = await createEvent(request, token);
        setSuccessMessage('Event created successfully!');
 
        // Upload image if one was selected
        if (selectedImageUri) {
          try {
            await uploadEventImage(result.id, selectedImageUri, token);
            Iif (imageUploadSuccessTimerRef.current) clearTimeout(imageUploadSuccessTimerRef.current);
            setImageUploadSuccessMessage('Cover image uploaded successfully.');
            imageUploadSuccessTimerRef.current = setTimeout(() => {
              setImageUploadSuccessMessage(null);
              imageUploadSuccessTimerRef.current = null;
            }, 5000);
          } catch (error) {
            setImageError(getImageUploadErrorMessage(error));
          }
        }
 
        return result;
      } catch (err) {
        if (err instanceof ApiError) {
          if (err.details) {
            const fieldErrors: CreateEventFormErrors = {};
            for (const [key, msg] of Object.entries(err.details)) {
              if (key === 'title') fieldErrors.title = msg;
              else Iif (key === 'description') fieldErrors.description = msg;
              else Iif (key === 'category_id') fieldErrors.categoryId = msg;
              else Iif (key === 'lat' || key === 'lon' || key === 'address')
                fieldErrors.location = msg;
              else if (key === 'start_time') fieldErrors.startDate = msg;
              else Eif (key === 'end_time') fieldErrors.endDate = msg;
              else if (key === 'tags') fieldErrors.tags = msg;
              else if (key.startsWith('constraints')) fieldErrors.constraints = msg;
            }
            setErrors(fieldErrors);
          }
          setApiError(err.message);
        } else {
          setApiError('An unexpected error occurred. Please try again.');
        }
        return null;
      } finally {
        setIsLoading(false);
      }
    },
    [formData, selectedImageUri, uploadEventImage, clearImageUploadSuccessMessage],
  );
 
  return {
    formData,
    errors,
    isLoading,
    isUploadingImage,
    apiError,
    imageError,
    successMessage,
    imageUploadSuccessMessage,
    selectedImageUri,
    locationSuggestions,
    isSearchingLocation,
    categoriesExpanded,
    constraintTypeCounts,
    updateField,
    handleLocationSearch,
    selectLocation,
    clearLocation,
    toggleCategoriesExpanded,
    addTag,
    removeTag,
    addGenderConstraint,
    addConstraint,
    removeConstraint,
    pickImage,
    removeImage,
    handleSubmit,
  };
}