All files / src/viewmodels/event useCreateEventViewModel.ts

78.62% Statements 537/683
68.92% Branches 224/325
79.09% Functions 87/110
83.05% Lines 490/590

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 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 14134x 4x 4x 4x 4x 4x               4x 4x 4x 4x                       4x   4x 4x                         4x 8x 7x 14x 14x 4x   7x 7x 7x 5x     4x                                             4x   4x           4x     4x   4x                                                                                                                                                                                                   4x 33x 33x 33x 33x       18x       18x 18x           4x 8x   8x 12x 12x 4x     8x       6x     4x 6x   6x 8x 8x         5x   3x       1x     4x                                                           4x   9x   9x   8x 3x     5x 4x         11x 11x 11x 9x 9x 5x 5x     4x 11x 11x 11x 3x   8x       4x 181x 181x 181x 181x 181x 181x 181x 181x 181x 181x   181x 181x 181x           4x   177x       4x 99x 99x 99x 99x 99x 99x 99x 99x 99x       373x       285x     4x 196x   196x 196x 196x   196x 195x 195x 8x       188x 185x 185x 4x       184x 181x     3x     4x 114x   114x 114x 114x   114x 113x 113x 8x       106x 103x 103x 4x       102x 99x     3x     4x 114x 114x 114x 114x 114x 114x 114x     4x 4x 4x 4x 4x           177x             177x 6x   171x     177x 87x   90x       177x         177x 67x 67x   67x 6x       177x 177x 12x     12x     12x     12x       12x         12x 12x 12x       12x   12x 10x         177x       33x   33x 33x 4x 29x 1x 28x       33x 33x 4x 29x 1x 28x       33x 4x     33x 4x 1x 3x     29x 4x     33x   33x       2x       2x 2x 1x     1x       1x       1x 1x                         263x         21x                                                                                     21x     4x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x 338x   338x 353x       353x     338x 76x 76x         338x 94x 94x 41x 41x   94x     338x   340x   340x     340x 340x 340x   340x 340x 340x   340x 340x 340x         338x       338x 144x 144x 144x       144x   401x     94x     50x           50x 155x 1x     154x   50x   27x 27x 108x 107x       27x                   338x 2x 2x   2x       2x         2x 1x 1x 1x 1x       338x 2x             2x 2x     338x 1x             1x     338x 16x 16x 16x                 16x 16x     338x   23x 23x 23x         23x         338x 2x 2x 2x 1x 1x 1x                 1x 1x     338x 1x 1x 1x 1x 1x       338x   2x             2x 2x         338x 3x 3x 1x 1x 1x       338x 4x 4x 4x           2x   2x 2x 2x       338x 11x 11x 11x 9x       9x   11x     338x 1x   2x       338x 3x 3x 3x 3x   2x     2x           3x     338x 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               338x             338x 6x   6x 6x 6x 1x 1x 1x 1x     5x             5x   5x 5x         5x 5x 4x   1x 1x     4x           338x         338x                               338x       338x                                                         338x                                                                                       338x   3x 3x   3x             3x             3x   3x 6x 3x         3x                     1x   3x           338x   33x 33x 80x 33x 20x 20x     13x 13x 13x 13x 13x   13x 13x   13x               13x   13x                                               13x 13x 13x       13x                 6x                                         13x 10x   10x                 10x 3x 3x 1x 1x 1x         2x       10x   3x 2x 1x 1x 2x 1x 1x 1x               1x         1x   2x   1x   3x   13x           338x                                                                                        
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,
  createEventInvitations,
  searchLocation,
  getEventImageUploadUrl,
  uploadFileToPresignedUrl,
  confirmEventImageUpload,
} from '@/services/eventService';
import { searchUsers } from '@/services/profileService';
import * as DocumentPicker from 'expo-document-picker';
import * as FileSystem from 'expo-file-system/legacy';
import { useAuth } from '@/contexts/AuthContext';
import { debounce } from 'lodash';
import {
  PrivacyLevel,
  LocationSuggestion,
  LocationType,
  RoutePointInput,
  CreateEventRequest,
  CreateEventResponse,
  EventConstraint,
  EventCategory,
} from '@/models/event';
import i18n from '@/i18n';
 
export const ROUTE_MIN_POINTS = 2;
export const ROUTE_MAX_POINTS = 50;
 
export interface RouteWaypoint {
  lat: number;
  lon: number;
  label?: string | null;
}
 
/**
 * Build a short display address from route waypoints. Uses each label's first
 * comma segment (e.g. "Galata Tower, Beyoglu, Istanbul" -> "Galata Tower"),
 * falling back to coordinates when no label is resolved yet.
 */
export function deriveRouteAddress(waypoints: RouteWaypoint[]): string {
  if (waypoints.length === 0) return '';
  const shortLabel = (w: RouteWaypoint): string => {
    const trimmed = (w.label ?? '').split(',')[0]?.trim();
    if (trimmed) return trimmed;
    return `${w.lat.toFixed(4)}, ${w.lon.toFixed(4)}`;
  };
  const first = shortLabel(waypoints[0]);
  const last = shortLabel(waypoints[waypoints.length - 1]);
  if (waypoints.length === 1 || first === last) return first;
  return `${first} → ${last}`;
}
 
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' },
  { label: 'PRIVATE', value: 'PRIVATE' },
];
 
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;
  locationType: LocationType;
  locationQuery: string;
  address: string;
  lat: number | null;
  lon: number | null;
  routePoints: RouteWaypoint[];
  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;
  invitationMessage: string;
  childFriendly: boolean;
  familyOriented: boolean;
}
 
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;
  setLocationType: (type: LocationType) => void;
  setPointFromCoordinate: (lat: number, lon: number, label?: string | null) => void;
  addRoutePointFromCoordinate: (lat: number, lon: number, label?: string | null) => void;
  addRoutePointFromSuggestion: (suggestion: LocationSuggestion) => void;
  removeRoutePoint: (index: number) => void;
  moveRoutePoint: (index: number, direction: -1 | 1) => void;
  updateRoutePointLabel: (index: number, label: string) => 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;
  invitedUsers: string[];
  userSearchQuery: string;
  userSuggestions: Array<{ id: string; username: string; display_name?: string | null }>;
  isSearchingUsers: boolean;
  addInvitedUser: (username: string) => void;
  removeInvitedUser: (username: string) => void;
  handleUserSearch: (query: string, token: string) => void;
  pickAndParseUserFile: () => Promise<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)])];
}
 
export 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,
  locationType: 'POINT',
  locationQuery: '',
  address: '',
  lat: null,
  lon: null,
  routePoints: [],
  startDate: formatDateForForm(new Date()),
  startTime: '',
  endDate: '',
  endTime: '',
  privacyLevel: 'PUBLIC',
  tags: [],
  tagInput: '',
  constraints: [],
  constraintType: 'gender',
  genderConstraintValue: null,
  ageMinInput: '',
  ageMaxInput: '',
  capacityInput: '',
  otherConstraintInput: '',
  invitationMessage: '',
  childFriendly: false,
  familyOriented: false,
};
 
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;
}
 
export 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) {
      Iif (requireMissingFields) errors.endDate = 'End date is required';
    } else {
      errors.endDate = validateLiveDateInput(formData.endDate);
    }
 
    Iif (!formData.endTime) {
      Iif (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;
 
    if (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.locationType === 'ROUTE') {
    if (formData.routePoints.length < ROUTE_MIN_POINTS) {
      errors.location = i18n.t('events.create.errors.routeMinPoints', { count: ROUTE_MIN_POINTS });
    } else Iif (formData.routePoints.length > ROUTE_MAX_POINTS) {
      errors.location = i18n.t('events.create.errors.routeMaxPoints', { count: ROUTE_MAX_POINTS });
    }
  } else 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;
  }
 
  if (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.';
    }
 
    if (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 [invitedUsers, setInvitedUsers] = useState<string[]>([]);
  const [userSearchQuery, setUserSearchQuery] = useState('');
  const [userSuggestions, setUserSuggestions] = useState<Array<{ id: string; username: string; display_name?: string | null }>>([]);
  const [isSearchingUsers, setIsSearchingUsers] = useState(false);
  const searchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const userSearchTimeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const imageUploadSuccessTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const { token, user } = useAuth();
 
  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;
      if (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 setLocationType = useCallback((type: LocationType) => {
    setFormData((prev) => {
      Iif (prev.locationType === type) return prev;
      return {
        ...prev,
        locationType: type,
        // Reset the inactive mode's data so we don't submit stale fields
        ...(type === 'ROUTE'
          ? { lat: null, lon: null, address: '', locationQuery: '' }
          : { routePoints: [] }),
      };
    });
    setLocationSuggestions([]);
    setErrors((prev) => ({ ...prev, location: null }));
  }, []);
 
  const addRoutePointFromCoordinate = useCallback(
    (lat: number, lon: number, label?: string | null) => {
      setFormData((prev) => {
        Iif (prev.routePoints.length >= ROUTE_MAX_POINTS) return prev;
        return {
          ...prev,
          routePoints: [...prev.routePoints, { lat, lon, label: label ?? null }],
        };
      });
      setErrors((prev) => ({ ...prev, location: null }));
    },
    [],
  );
 
  const addRoutePointFromSuggestion = useCallback((suggestion: LocationSuggestion) => {
    const lat = parseFloat(suggestion.lat);
    const lon = parseFloat(suggestion.lon);
    if (Number.isNaN(lat) || Number.isNaN(lon)) return;
    setFormData((prev) => {
      Iif (prev.routePoints.length >= ROUTE_MAX_POINTS) return prev;
      return {
        ...prev,
        locationQuery: '',
        routePoints: [
          ...prev.routePoints,
          { lat, lon, label: suggestion.display_name },
        ],
      };
    });
    setLocationSuggestions([]);
    setErrors((prev) => ({ ...prev, location: null }));
  }, []);
 
  const removeRoutePoint = useCallback((index: number) => {
    setFormData((prev) => {
      Iif (index < 0 || index >= prev.routePoints.length) return prev;
      const next = [...prev.routePoints];
      next.splice(index, 1);
      return { ...prev, routePoints: next };
    });
  }, []);
 
  const setPointFromCoordinate = useCallback(
    (lat: number, lon: number, label?: string | null) => {
      setFormData((prev) => ({
        ...prev,
        lat,
        lon,
        address: label ?? prev.address,
        locationQuery: label ?? prev.locationQuery,
      }));
      setLocationSuggestions([]);
      setErrors((prev) => ({ ...prev, location: null }));
    },
    [],
  );
 
  const updateRoutePointLabel = useCallback((index: number, label: string) => {
    setFormData((prev) => {
      if (index < 0 || index >= prev.routePoints.length) return prev;
      const next = [...prev.routePoints];
      next[index] = { ...next[index], label };
      return { ...prev, routePoints: next };
    });
  }, []);
 
  const moveRoutePoint = useCallback((index: number, direction: -1 | 1) => {
    setFormData((prev) => {
      const target = index + direction;
      if (
        index < 0 ||
        index >= prev.routePoints.length ||
        target < 0 ||
        target >= prev.routePoints.length
      ) {
        return prev;
      }
      const next = [...prev.routePoints];
      [next[index], next[target]] = [next[target], next[index]];
      return { ...prev, routePoints: next };
    });
  }, []);
 
  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'
          ? i18n.t('events.create.constraintActions.malesOnly')
          : i18n.t('events.create.constraintActions.femalesOnly');
      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;
        if (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': {
          Iif (!prev.genderConstraintValue) return prev;
          info =
            prev.genderConstraintValue === 'MALE'
              ? i18n.t('events.create.constraintActions.malesOnly')
              : i18n.t('events.create.constraintActions.femalesOnly');
          updates.genderConstraintValue = null;
          break;
        }
        case 'age': {
          const min = prev.ageMinInput.trim();
          const max = prev.ageMaxInput.trim();
          Iif (!min && !max) return prev;
          if (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 addInvitedUser = useCallback((username: string) => {
    Iif (user && username === user.username) {
      Alert.alert(
        i18n.t('events.create.invites.invalidTitle'),
        i18n.t('events.create.invites.invalidSelf'),
      );
      return;
    }
    setInvitedUsers((prev) => {
      Iif (prev.includes(username)) return prev;
      return [...prev, username];
    });
    setUserSearchQuery('');
    setUserSuggestions([]);
  }, [user]);
 
  const removeInvitedUser = useCallback((username: string) => {
    setInvitedUsers((prev) => prev.filter((u) => u !== username));
  }, []);
 
  const handleUserSearch = useCallback((query: string, token: string) => {
    setUserSearchQuery(query);
    Iif (userSearchTimeoutRef.current) clearTimeout(userSearchTimeoutRef.current);
 
    Iif (!query.trim()) {
      setUserSuggestions([]);
      setIsSearchingUsers(false);
      return;
    }
 
    setIsSearchingUsers(true);
    userSearchTimeoutRef.current = setTimeout(async () => {
      try {
        const results = await searchUsers(query, token);
        setUserSuggestions(
          results.items
            .filter((i) => i.username !== user?.username)
            .map((i) => ({ 
              id: i.id, 
              username: i.username,
              display_name: i.display_name 
            }))
        );
      } finally {
        setIsSearchingUsers(false);
      }
    }, 500);
  }, []);
 
  const pickAndParseUserFile = useCallback(async () => {
    try {
      const result = await DocumentPicker.getDocumentAsync({
        type: ['text/plain', 'text/csv'],
        copyToCacheDirectory: true,
      });
 
      Iif (result.canceled || !result.assets || result.assets.length === 0) return;
 
      const fileUri = result.assets[0].uri;
      const content = await FileSystem.readAsStringAsync(fileUri);
 
      // Split by comma, newline or space and clean up
      const usernames = content
        .split(/[\n,\s]+/)
        .map((u) => u.trim())
        .filter((u) => u.length > 0 && /^[a-zA-Z0-9._]+$/.test(u) && u !== user?.username);
 
      Iif (usernames.length === 0) {
        Alert.alert(
          i18n.t('events.create.importUsers.invalidFileTitle'),
          i18n.t('events.create.importUsers.noValidUsernames'),
        );
        return;
      }
 
      setInvitedUsers((prev) => {
        const combined = [...prev, ...usernames];
        return [...new Set(combined)];
      });
 
      Alert.alert(
        i18n.t('events.create.importUsers.successTitle'),
        i18n.t('events.create.importUsers.successBody', { count: usernames.length }),
      );
    } catch (error) {
      console.error('File read error:', error);
      Alert.alert(
        i18n.t('events.create.importUsers.errorTitle'),
        i18n.t('events.create.importUsers.readFailed'),
      );
    }
  }, []);
 
  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 Iif (rangeMatch) minimumAge = parseInt(rangeMatch[1], 10);
              break;
            }
            case 'capacity': {
              const capMatch = c.info.match(/(\d+)/);
              Iif (capMatch) capacity = parseInt(capMatch[1], 10);
              break;
            }
            case 'other':
              otherConstraints.push(c);
              break;
          }
        }
 
        const isRoute = formData.locationType === 'ROUTE';
        const explicitAddress = formData.address?.trim() || undefined;
        const address = isRoute
          ? explicitAddress ?? (deriveRouteAddress(formData.routePoints) || undefined)
          : explicitAddress;
 
        const request: CreateEventRequest = {
          title: formData.title.trim(),
          description: formData.description.trim(),
          image_url: formData.imageUrl.trim() || undefined,
          category_id: formData.categoryId!,
          address,
          location_type: formData.locationType,
          ...(isRoute
            ? {
                route_points: formData.routePoints.map<RoutePointInput>((p) => ({
                  lat: p.lat,
                  lon: p.lon,
                })),
              }
            : {
                lat: formData.lat ?? undefined,
                lon: formData.lon ?? undefined,
              }),
          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,
          child_friendly: formData.childFriendly || undefined,
          family_oriented: formData.familyOriented || undefined,
        };
 
        const result = await createEvent(request, token);
        setSuccessMessage('Event created successfully!');
 
        Iif (formData.privacyLevel === 'PRIVATE' && invitedUsers.length > 0) {
          try {
            await createEventInvitations(result.id, invitedUsers, token, formData.invitationMessage);
          } catch (error) {
            // We don't fail the whole creation for this, but could show a warning
          }
        }
 
        // 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' ||
                key === 'route_points' ||
                key.startsWith('route_points')
              )
                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 Iif (key.startsWith('constraints')) fieldErrors.constraints = msg;
            }
            setErrors(fieldErrors);
          }
          setApiError(err.message);
        } else {
          setApiError(i18n.t('events.create.errors.unexpected'));
        }
        return null;
      } finally {
        setIsLoading(false);
      }
    },
    [formData, selectedImageUri, invitedUsers, uploadEventImage, clearImageUploadSuccessMessage],
  );
 
  return {
    formData,
    errors,
    isLoading,
    isUploadingImage,
    apiError,
    imageError,
    successMessage,
    imageUploadSuccessMessage,
    selectedImageUri,
    locationSuggestions,
    isSearchingLocation,
    categoriesExpanded,
    constraintTypeCounts,
    updateField,
    handleLocationSearch,
    selectLocation,
    clearLocation,
    setLocationType,
    setPointFromCoordinate,
    addRoutePointFromCoordinate,
    addRoutePointFromSuggestion,
    removeRoutePoint,
    moveRoutePoint,
    updateRoutePointLabel,
    toggleCategoriesExpanded,
    addTag,
    removeTag,
    addGenderConstraint,
    addConstraint,
    removeConstraint,
    pickImage,
    removeImage,
    invitedUsers,
    userSearchQuery,
    userSuggestions,
    isSearchingUsers,
    addInvitedUser,
    removeInvitedUser,
    handleUserSearch,
    pickAndParseUserFile,
    handleSubmit,
  };
}