File size: 53,102 Bytes
a406193
351d460
1dc6a03
351d460
1686de5
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
 
 
d9619a1
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
65933cd
c8ed728
1686de5
 
 
 
 
351d460
 
1686de5
 
186c8e8
1686de5
 
 
362f973
82ff6c1
 
 
 
 
 
 
 
 
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
 
 
 
 
 
351d460
1686de5
 
230c4ad
 
 
351d460
1686de5
351d460
1686de5
351d460
ae86947
 
 
 
 
186c8e8
 
 
 
 
 
84aedaf
 
 
 
 
 
 
 
 
 
 
 
 
902bb5e
 
 
 
 
351d460
 
 
 
 
 
d9619a1
 
 
 
 
 
 
 
 
351d460
d9619a1
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84aedaf
65933cd
1686de5
351d460
 
 
 
 
 
 
 
902bb5e
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84aedaf
d9619a1
 
 
 
 
 
 
351d460
 
84aedaf
 
351d460
84aedaf
 
 
 
 
 
 
 
 
 
 
 
 
 
902bb5e
 
351d460
 
 
 
 
 
 
902bb5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351d460
 
 
84aedaf
351d460
 
 
 
 
84aedaf
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84aedaf
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
351d460
1686de5
351d460
21ef00c
1686de5
 
 
 
 
 
 
 
21ef00c
 
1686de5
 
 
 
351d460
1686de5
 
a41ced5
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
351d460
 
 
 
 
 
 
 
 
 
 
82ff6c1
 
 
 
 
 
 
 
 
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
 
ba5edb0
1686de5
 
351d460
1686de5
2bffd24
351d460
 
 
 
 
 
2bffd24
1686de5
84aedaf
 
 
 
 
 
 
 
2bffd24
1686de5
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
99eb145
 
 
 
 
 
 
 
186c8e8
99eb145
 
 
186c8e8
 
 
 
c69ce84
65933cd
2bffd24
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9619a1
 
 
 
351d460
d9619a1
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9619a1
 
 
 
351d460
d9619a1
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9619a1
 
 
 
351d460
d9619a1
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
82ff6c1
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2bffd24
99eb145
 
230c4ad
 
 
186c8e8
230c4ad
 
 
 
 
 
 
 
 
 
186c8e8
65933cd
 
 
1686de5
65933cd
 
1686de5
ae86947
 
 
 
 
c8ed728
 
1686de5
351d460
 
 
 
 
 
 
 
 
 
 
 
82ff6c1
351d460
 
 
 
 
 
 
1686de5
351d460
1686de5
351d460
 
 
1686de5
 
 
 
 
351d460
 
1686de5
230c4ad
 
1686de5
 
230c4ad
1686de5
 
 
 
65933cd
 
1686de5
 
 
 
 
2bffd24
1686de5
 
351d460
1686de5
 
 
c8ed728
 
1686de5
 
 
 
65933cd
1686de5
65933cd
1686de5
 
 
ae86947
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae86947
 
1686de5
ae86947
 
 
 
 
 
 
 
 
1686de5
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
ab3b988
ae86947
ab3b988
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
351d460
1686de5
 
 
d2a86e9
1686de5
 
 
65933cd
 
 
 
 
 
 
351d460
 
1686de5
65933cd
 
 
351d460
65933cd
 
 
 
 
 
351d460
65933cd
 
 
 
 
1686de5
 
 
351d460
1686de5
 
 
351d460
 
 
 
 
 
 
 
 
1686de5
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
 
 
 
 
 
 
 
 
 
 
 
351d460
1686de5
65933cd
1686de5
 
 
 
 
 
 
351d460
1686de5
e2f9373
3cf9fa0
 
 
 
 
 
 
 
351d460
e2f9373
351d460
 
 
 
 
 
 
e2f9373
351d460
 
 
 
 
e2f9373
ae86947
 
351d460
 
 
 
 
 
 
 
 
902bb5e
351d460
902bb5e
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
c8ed728
351d460
902bb5e
 
 
ae86947
65933cd
ab3b988
 
362f973
ab3b988
 
 
29b7d98
351d460
29b7d98
 
 
 
ab3b988
 
351d460
29b7d98
 
 
ab3b988
351d460
ab3b988
 
 
 
351d460
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1686de5
 
 
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
1413
import { useState, useEffect, useRef, useCallback } from 'react';
import { PageContainer, Heading, Button, Spinner, IconButton } from '@ifrc-go/ui';
import { DeleteBinLineIcon} from '@ifrc-go/icons';
import { useSearchParams, useNavigate } from 'react-router-dom';
import styles from './UploadPage.module.css';
import {
  FileUploadSection,
  ImagePreviewSection,
  MetadataFormSection,
  RatingSection,
  GeneratedTextSection,
  FullSizeImageModal,
  RatingWarningModal,
  DeleteConfirmModal,
  NavigationConfirmModal,
  FallbackNotificationModal,
  PreprocessingNotificationModal,
  PreprocessingModal,
  UnsupportedFormatModal,
  FileSizeWarningModal,

} from '../../components';

const SELECTED_MODEL_KEY = 'selectedVlmModel';

export default function UploadPage() {
  // Safely get search params with fallback
  let searchParams: URLSearchParams;
  let navigate: any;
  
  try {
    [searchParams] = useSearchParams();
    navigate = useNavigate();
  } catch (error) {
    console.warn('Router context not available, using fallback:', error);
    searchParams = new URLSearchParams();
    navigate = () => {};
  }
  
  const [step, setStep] = useState<1 | '2a' | '2b' | 3>(1);
  const [isLoading, setIsLoading] = useState(false);
  const [isLoadingContribution, setIsLoadingContribution] = useState(false);
  const [isSubmitting, setIsSubmitting] = useState(false);
  const stepRef = useRef(step);
  const uploadedImageIdRef = useRef<string | null>(null);
  const [preview, setPreview] = useState<string | null>(null);

  const [file, setFile] = useState<File | null>(null);
  const [files, setFiles] = useState<File[]>([]);
  const [source, setSource] = useState('');
  const [eventType, setEventType] = useState('');
  const [epsg, setEpsg] = useState('');
  const [imageType, setImageType] = useState('crisis_map');
  const [countries, setCountries] = useState<string[]>([]);
  const [title, setTitle] = useState('');

  // Drone metadata fields
  const [centerLon, setCenterLon] = useState<string>('');
  const [centerLat, setCenterLat] = useState<string>('');
  const [amslM, setAmslM] = useState<string>('');
  const [aglM, setAglM] = useState<string>('');
  const [headingDeg, setHeadingDeg] = useState<string>('');
  const [yawDeg, setYawDeg] = useState<string>('');
  const [pitchDeg, setPitchDeg] = useState<string>('');
  const [rollDeg, setRollDeg] = useState<string>('');
  const [rtkFix, setRtkFix] = useState<boolean>(false);
  const [stdHM, setStdHM] = useState<string>('');
  const [stdVM, setStdVM] = useState<string>('');

  // Multi-image metadata arrays
  const [metadataArray, setMetadataArray] = useState<Array<{
    source: string;
    eventType: string;
    epsg: string;
    countries: string[];
    centerLon: string;
    centerLat: string;
    amslM: string;
    aglM: string;
    headingDeg: string;
    yawDeg: string;
    pitchDeg: string;
    rollDeg: string;
    rtkFix: boolean;
    stdHM: string;
    stdVM: string;
  }>>([]);

  const [sources, setSources] = useState<{s_code: string, label: string}[]>([]);
  const [types, setTypes] = useState<{t_code: string, label: string}[]>([]);
  const [spatialReferences, setSpatialReferences] = useState<{epsg: string, srid: string, proj4: string, wkt: string}[]>([]);
  const [imageTypes, setImageTypes] = useState<{image_type: string, label: string}[]>([]);
  const [countriesOptions, setCountriesOptions] = useState<{c_code: string, label: string, r_code: string}[]>([]);

  const [uploadedImageId, setUploadedImageId] = useState<string | null>(null);
   const [uploadedImageIds, setUploadedImageIds] = useState<string[]>([]);
  const [imageUrl, setImageUrl] = useState<string|null>(null);
  const [draft, setDraft] = useState('');
  const [description, setDescription] = useState('');
  const [analysis, setAnalysis] = useState('');
  const [recommendedActions, setRecommendedActions] = useState('');
  const [scores, setScores] = useState({ accuracy: 50, context: 50, usability: 50 });

  // Modal states
  const [isFullSizeModalOpen, setIsFullSizeModalOpen] = useState(false);
  const [selectedImageData, setSelectedImageData] = useState<{ file: File; index: number } | null>(null);
  const [isPerformanceConfirmed, setIsPerformanceConfirmed] = useState(false);
  const [showRatingWarning, setShowRatingWarning] = useState(false);
  const [showDeleteConfirm, setShowDeleteConfirm] = useState(false);
  const [showNavigationConfirm, setShowNavigationConfirm] = useState(false);
  const [pendingNavigation, setPendingNavigation] = useState<string | null>(null);
  const [showFallbackNotification, setShowFallbackNotification] = useState(false);
  const [fallbackInfo, setFallbackInfo] = useState<{
    originalModel: string;
    fallbackModel: string;
    reason: string;
  } | null>(null);
  const [showPreprocessingNotification, setShowPreprocessingNotification] = useState(false);
  const [preprocessingInfo, setPreprocessingInfo] = useState<{
    original_filename: string;
    processed_filename: string;
    original_mime_type: string;
    processed_mime_type: string;
    was_preprocessed: boolean;
    error?: string;
  } | null>(null);
  const [showPreprocessingModal, setShowPreprocessingModal] = useState(false);
  const [preprocessingFile, setPreprocessingFile] = useState<File | null>(null);
  const [isPreprocessing, setIsPreprocessing] = useState(false);
  const [preprocessingProgress, setPreprocessingProgress] = useState<string>('');
  const [showUnsupportedFormatModal, setShowUnsupportedFormatModal] = useState(false);
  const [unsupportedFile, setUnsupportedFile] = useState<File | null>(null);
  const [showFileSizeWarningModal, setShowFileSizeWarningModal] = useState(false);
  const [oversizedFile, setOversizedFile] = useState<File | null>(null);

  // Carousel state for multi-upload in step 2b
  const [currentImageIndex, setCurrentImageIndex] = useState(0);

  stepRef.current = step;
  uploadedImageIdRef.current = uploadedImageId;

  // Helper function to convert source label to code
  const convertSourceToCode = (sourceValue: string): string => {
    if (!sourceValue || sources.length === 0) return sourceValue;
    
    // Find matching source by code or label
    const sourceObj = sources.find(s => s.s_code === sourceValue || s.label === sourceValue);
    return sourceObj?.s_code || sourceValue;
  };

  // Event handlers
  const handleSourceChange = (value: string | undefined) => {
    setSource(convertSourceToCode(value || ''));
  };
  const handleEventTypeChange = (value: string | undefined) => setEventType(value || '');
  const handleEpsgChange = (value: string | undefined) => setEpsg(value || '');
  const handleImageTypeChange = (value: string | undefined) => setImageType(value || '');
  const handleCountriesChange = (value: string[] | undefined) => setCountries(Array.isArray(value) ? value : []);
  const handleCenterLonChange = (value: string | undefined) => setCenterLon(value || '');
  const handleCenterLatChange = (value: string | undefined) => setCenterLat(value || '');
  const handleAmslMChange = (value: string | undefined) => setAmslM(value || '');
  const handleAglMChange = (value: string | undefined) => setAglM(value || '');
  const handleHeadingDegChange = (value: string | undefined) => setHeadingDeg(value || '');
  const handleYawDegChange = (value: string | undefined) => setYawDeg(value || '');
  const handlePitchDegChange = (value: string | undefined) => setPitchDeg(value || '');
  const handleRollDegChange = (value: string | undefined) => setRollDeg(value || '');
  const handleRtkFixChange = (value: boolean | undefined) => setRtkFix(value || false);
  const handleStdHMChange = (value: string | undefined) => setStdHM(value || '');
  const handleStdVMChange = (value: string | undefined) => setStdVM(value || '');
  const handleStepChange = (newStep: 1 | '2a' | '2b' | 3) => setStep(newStep);

  // Carousel navigation functions for step 2b
  const goToPrevious = useCallback(() => {
    if (files.length > 1) {
      setCurrentImageIndex((prev: number) => (prev > 0 ? prev - 1 : files.length - 1));
    }
  }, [files.length]);

  const goToNext = useCallback(() => {
    if (files.length > 1) {
      setCurrentImageIndex((prev: number) => (prev < files.length - 1 ? prev + 1 : 0));
    }
  }, [files.length]);

  const goToImage = useCallback((index: number) => {
    if (index >= 0 && index < files.length) {
      setCurrentImageIndex(index);
    }
  }, [files.length]);

  // Multi-image functions
  const addImage = () => {
    if (files.length < 5) {
      const input = document.createElement('input');
      input.type = 'file';
      input.accept = '.jpg,.jpeg,.png,.tiff,.tif,.heic,.heif,.webp,.gif,.pdf';
      input.onchange = (e) => {
        const target = e.target as HTMLInputElement;
        if (target.files && target.files[0]) {
          const newFile = target.files[0];
          onFileChange(newFile);
        }
      };
      input.click();
    }
  };

  const removeImage = (index: number) => {
    setFiles(prev => {
      const newFiles = prev.filter((_, i) => i !== index);
      // If we're back to single file, update the single file state
      if (newFiles.length === 1) {
        setFile(newFiles[0]);
      } else if (newFiles.length === 0) {
        setFile(null);
      }
      return newFiles;
    });
    setMetadataArray(prev => prev.filter((_, i) => i !== index));
  };

  const updateMetadataForImage = (index: number, field: string, value: any) => {
    setMetadataArray(prev => {
      const newArray = [...prev];
      if (!newArray[index]) {
        newArray[index] = {
          source: '', eventType: '', epsg: '', countries: [],
          centerLon: '', centerLat: '', amslM: '', aglM: '',
          headingDeg: '', yawDeg: '', pitchDeg: '', rollDeg: '',
          rtkFix: false, stdHM: '', stdVM: ''
        };
      }
      
      if (field === 'source') {
        newArray[index] = { ...newArray[index], [field]: convertSourceToCode(value) };
      } else {
        newArray[index] = { ...newArray[index], [field]: value };
      }
      
      return newArray;
    });
  };

  // File handling functions
  const needsPreprocessing = (file: File): boolean => {
    const supportedTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    const supportedExtensions = ['.jpg', '.jpeg', '.png'];
    
    let needsPreprocess = !supportedTypes.includes(file.type);
    
    if (!needsPreprocess && file.name) {
      const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
      needsPreprocess = !supportedExtensions.includes(fileExtension);
    }
    
    return needsPreprocess;
  };

  const isCompletelyUnsupported = (file: File): boolean => {
    const completelyUnsupportedTypes = [
      'text/html', 'text/css', 'application/javascript', 'application/json',
      'text/plain', 'application/xml', 'text/xml', 'application/zip',
      'application/x-zip-compressed', 'application/x-rar-compressed',
      'application/x-7z-compressed', 'audio/', 'video/', 'text/csv',
      'application/vnd.ms-excel', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      'application/vnd.ms-powerpoint', 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
      'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    ];
    
    for (const unsupportedType of completelyUnsupportedTypes) {
      if (file.type.startsWith(unsupportedType)) {
        return true;
      }
    }
    
    if (file.name) {
      const fileExtension = file.name.toLowerCase().substring(file.name.lastIndexOf('.'));
      const unsupportedExtensions = [
        '.html', '.htm', '.css', '.js', '.json', '.txt', '.xml',
        '.zip', '.rar', '.7z', '.csv', '.xlsx', '.xls', '.pptx',
        '.ppt', '.docx', '.doc', '.mp3', '.mp4', '.avi', '.mov'
      ];
      
      if (unsupportedExtensions.includes(fileExtension)) {
        return true;
      }
    }
    
    return false;
  };

  const onFileChange = (file: File | undefined) => {
    if (file) {
      console.log('File selected:', file.name, 'Type:', file.type, 'Size:', file.size);
      
      const fileSizeMB = file.size / (1024 * 1024);
      if (fileSizeMB > 5) {
        console.log('File too large, showing size warning modal');
        setOversizedFile(file);
        setShowFileSizeWarningModal(true);
      }
      
      if (isCompletelyUnsupported(file)) {
        console.log('File format not supported at all, showing unsupported format modal');
        setUnsupportedFile(file);
        setShowUnsupportedFormatModal(true);
            return;
          }

      if (needsPreprocessing(file)) {
        console.log('File needs preprocessing, showing modal');
        setPreprocessingFile(file);
        setShowPreprocessingModal(true);
            } else {
        console.log('File does not need preprocessing, setting directly');
        // If this is the first file, set it as the single file
        if (files.length === 0) {
          setFile(file);
          setFiles([file]);
        } else {
          // If files already exist, add to the array (multi-upload mode)
          setFiles(prev => [...prev, file]);
        }
      }
    }
  };

  const onChangeFile = (file: File | undefined) => {
    if (file) {
      console.log('File changed:', file.name, 'Type:', file.type, 'Size:', file.size);
      
      const fileSizeMB = file.size / (1024 * 1024);
      if (fileSizeMB > 5) {
        console.log('File too large, showing size warning modal');
        setOversizedFile(file);
        setShowFileSizeWarningModal(true);
      }
      
      if (isCompletelyUnsupported(file)) {
        console.log('File format not supported at all, showing unsupported format modal');
        setUnsupportedFile(file);
        setShowUnsupportedFormatModal(true);
            return;
          }

      if (needsPreprocessing(file)) {
        console.log('File needs preprocessing, showing modal');
        setPreprocessingFile(file);
        setShowPreprocessingModal(true);
            } else {
        console.log('File does not need preprocessing, replacing last file');
        // Replace only the last file in the array
        if (files.length > 1) {
          setFiles(prev => {
            const newFiles = [...prev];
            newFiles[newFiles.length - 1] = file;
            return newFiles;
          });
          // Update single file state if it's a single upload
          if (files.length === 1) {
            setFile(file);
          }
        } else {
          // If only one file, replace it normally
          setFile(file);
          setFiles([file]);
        }
      }
    }
  };

  // API functions
  async function readJsonSafely(res: Response): Promise<Record<string, unknown>> {
    const text = await res.text();
    try {
      return text ? JSON.parse(text) : {};
    } catch {
      return { error: text };
    }
  }

  function handleApiError(err: unknown, operation: string) {
    const message = err instanceof Error ? err.message : `Failed to ${operation.toLowerCase()}`;
    alert(message);
  }

  async function handleGenerate() {
     if (files.length === 0) return;

    setIsLoading(true);
    
     try {
       if (files.length === 1) {
         await handleSingleUpload();
       } else {
         await handleMultiUpload();
       }
     } catch (err) {
       handleApiError(err, 'Upload');
     } finally {
       setIsLoading(false);
     }
   }

   async function handleSingleUpload() {
     console.log('DEBUG: Starting single image upload');

    const fd = new FormData();
     fd.append('file', files[0]);
     fd.append('title', title);
     fd.append('image_type', imageType);
     
     // Add metadata for single image
     if (source) fd.append('source', source);
     if (eventType) fd.append('event_type', eventType);
     if (epsg) fd.append('epsg', epsg);
     if (countries.length > 0) {
       countries.forEach(c => fd.append('countries', c));
     }
    if (imageType === 'drone_image') {
      if (centerLon) fd.append('center_lon', centerLon);
      if (centerLat) fd.append('center_lat', centerLat);
      if (amslM) fd.append('amsl_m', amslM);
      if (aglM) fd.append('agl_m', aglM);
      if (headingDeg) fd.append('heading_deg', headingDeg);
      if (yawDeg) fd.append('yaw_deg', yawDeg);
      if (pitchDeg) fd.append('pitch_deg', pitchDeg);
      if (rollDeg) fd.append('roll_deg', rollDeg);
      if (rtkFix) fd.append('rtk_fix', rtkFix.toString());
      if (stdHM) fd.append('std_h_m', stdHM);
      if (stdVM) fd.append('std_v_m', stdVM);
     }

     const modelName = localStorage.getItem(SELECTED_MODEL_KEY);
     if (modelName) {
       fd.append('model_name', modelName);
     }

     const mapRes = await fetch('/api/images/', { method: 'POST', body: fd });
     const mapJson = await readJsonSafely(mapRes);
     if (!mapRes.ok) throw new Error((mapJson.error as string) || 'Upload failed');
     console.log('DEBUG: Single upload response:', mapJson);

     await processUploadResponse(mapJson, false);
   }

   async function handleMultiUpload() {
     console.log('DEBUG: Starting multi-image upload');
     
     const fd = new FormData();
     files.forEach(file => fd.append('files', file));
     fd.append('title', title);
    fd.append('image_type', imageType);
     
     // Add metadata for each image
     metadataArray.forEach((metadata, index) => {
       if (metadata.source) fd.append(`source_${index}`, metadata.source);
       if (metadata.eventType) fd.append(`event_type_${index}`, metadata.eventType);
       if (metadata.epsg) fd.append(`epsg_${index}`, metadata.epsg);
       if (metadata.countries.length > 0) {
         metadata.countries.forEach(c => fd.append(`countries_${index}`, c));
       }
       if (imageType === 'drone_image') {
         if (metadata.centerLon) fd.append(`center_lon_${index}`, metadata.centerLon);
         if (metadata.centerLat) fd.append(`center_lat_${index}`, metadata.centerLat);
         if (metadata.amslM) fd.append(`amsl_m_${index}`, metadata.amslM);
         if (metadata.aglM) fd.append(`agl_m_${index}`, metadata.aglM);
         if (metadata.headingDeg) fd.append(`heading_deg_${index}`, metadata.headingDeg);
         if (metadata.yawDeg) fd.append(`yaw_deg_${index}`, metadata.yawDeg);
         if (metadata.pitchDeg) fd.append(`pitch_deg_${index}`, metadata.pitchDeg);
         if (metadata.rollDeg) fd.append(`roll_deg_${index}`, metadata.rollDeg);
         if (metadata.rtkFix) fd.append(`rtk_fix_${index}`, metadata.rtkFix.toString());
         if (metadata.stdHM) fd.append(`std_h_m_${index}`, metadata.stdHM);
         if (metadata.stdVM) fd.append(`std_v_m_${index}`, metadata.stdVM);
       }
     });

    const modelName = localStorage.getItem(SELECTED_MODEL_KEY);
    if (modelName) {
      fd.append('model_name', modelName);
    }

     const mapRes = await fetch('/api/images/multi', { method: 'POST', body: fd });
      const mapJson = await readJsonSafely(mapRes);
      if (!mapRes.ok) throw new Error((mapJson.error as string) || 'Upload failed');
     console.log('DEBUG: Multi upload response:', mapJson);

     await processUploadResponse(mapJson, true);
   }

   async function processUploadResponse(mapJson: Record<string, unknown>, isMultiUpload: boolean) {
      setImageUrl(mapJson.image_url as string);

      if (mapJson.preprocessing_info && 
          typeof mapJson.preprocessing_info === 'object' && 
          'was_preprocessed' in mapJson.preprocessing_info && 
          mapJson.preprocessing_info.was_preprocessed === true) {
        setPreprocessingInfo(mapJson.preprocessing_info as any);
        setShowPreprocessingNotification(true);
      }

      const mapIdVal = mapJson.image_id as string;
      if (!mapIdVal) throw new Error('Upload failed: image_id not found');
      setUploadedImageId(mapIdVal);
    
     // Store image IDs
     if (isMultiUpload) {
       if (mapJson.image_ids && Array.isArray(mapJson.image_ids)) {
         const imageIds = mapJson.image_ids as string[];
         console.log('DEBUG: Storing image IDs for multi-upload:', imageIds);
         setUploadedImageIds(imageIds);
       } else {
         console.log('DEBUG: Multi-upload but no image_ids found, using single ID');
         setUploadedImageIds([mapIdVal]);
       }
     } else {
       console.log('DEBUG: Storing single image ID:', mapIdVal);
       setUploadedImageIds([mapIdVal]);
     }
     
     const capJson = mapJson;

      // Check for fallback information in the response
      const rawJson = capJson.raw_json as Record<string, unknown>;
      const fallbackUsed = rawJson?.fallback_used;
      const originalModel = rawJson?.original_model as string;
      const fallbackReason = rawJson?.fallback_reason as string;
      const currentModel = capJson.model as string;
      
      if (fallbackUsed && originalModel && fallbackReason) {
        setFallbackInfo({
          originalModel: originalModel,
          fallbackModel: currentModel,
          reason: fallbackReason
        });
        setShowFallbackNotification(true);
      }

      const extractedMetadata = (capJson.raw_json as Record<string, unknown>)?.metadata;
      if (extractedMetadata) {
        const metadata = (extractedMetadata as Record<string, unknown>).metadata || extractedMetadata;
       
       if (metadata && typeof metadata === 'object') {
         const newMetadataArray = [];
         
         if (isMultiUpload) {
           // Try to get individual image metadata first
           const metadataImages = (metadata as Record<string, unknown>).metadata_images;
           if (metadataImages && typeof metadataImages === 'object') {
             // Parse individual image metadata
             for (let i = 1; i <= files.length; i++) {
               const imageKey = `image${i}`;
               const imageMetadata = (metadataImages as Record<string, unknown>)[imageKey];
               
               if (imageMetadata && typeof imageMetadata === 'object') {
                 const imgMeta = imageMetadata as Record<string, unknown>;
                 // Convert source label to code if needed
                 const sourceValue = imgMeta.source as string || '';
                 const sourceCode = convertSourceToCode(sourceValue);
                 
                 newMetadataArray.push({
                   source: sourceCode,
                   eventType: imgMeta.type as string || '',
                   epsg: imgMeta.epsg as string || '',
                   countries: Array.isArray(imgMeta.countries) ? imgMeta.countries as string[] : [],
                   centerLon: '', centerLat: '', amslM: '', aglM: '',
                   headingDeg: '', yawDeg: '', pitchDeg: '', rollDeg: '',
                   rtkFix: false, stdHM: '', stdVM: ''
                 });
               } else {
                 // Fallback to empty metadata for this image
                 newMetadataArray.push({
                   source: '', eventType: '', epsg: '', countries: [],
                   centerLon: '', centerLat: '', amslM: '', aglM: '',
                   headingDeg: '', yawDeg: '', pitchDeg: '', rollDeg: '',
                   rtkFix: false, stdHM: '', stdVM: ''
                 });
               }
             }
           } else {
             // Fallback to shared metadata if no individual metadata found
             // Convert source label to code if needed
             const sourceValue = (metadata as Record<string, unknown>).source as string || '';
             const sourceCode = convertSourceToCode(sourceValue);
             
             const sharedMetadata = {
               source: sourceCode,
               eventType: (metadata as Record<string, unknown>).type as string || '',
               epsg: (metadata as Record<string, unknown>).epsg as string || '',
               countries: Array.isArray((metadata as Record<string, unknown>).countries) 
                 ? (metadata as Record<string, unknown>).countries as string[] 
                 : [],
               centerLon: '', centerLat: '', amslM: '', aglM: '',
               headingDeg: '', yawDeg: '', pitchDeg: '', rollDeg: '',
               rtkFix: false, stdHM: '', stdVM: ''
             };
             
             // Create metadata array with shared data for all images
             for (let i = 0; i < files.length; i++) {
               newMetadataArray.push({ ...sharedMetadata });
             }
           }
         } else {
           // Single upload: use shared metadata
           // Convert source label to code if needed
           const sourceValue = (metadata as Record<string, unknown>).source as string || '';
           const sourceCode = convertSourceToCode(sourceValue);
           
           const sharedMetadata = {
             source: sourceCode,
             eventType: (metadata as Record<string, unknown>).type as string || '',
             epsg: (metadata as Record<string, unknown>).epsg as string || '',
             countries: Array.isArray((metadata as Record<string, unknown>).countries) 
               ? (metadata as Record<string, unknown>).countries as string[] 
               : [],
             centerLon: '', centerLat: '', amslM: '', aglM: '',
             headingDeg: '', yawDeg: '', pitchDeg: '', rollDeg: '',
             rtkFix: false, stdHM: '', stdVM: ''
           };
           newMetadataArray.push(sharedMetadata);
         }
         
         setMetadataArray(newMetadataArray);
         
         if (newMetadataArray.length > 0) {
           const firstMeta = newMetadataArray[0];
           // Set shared title from metadata
           if (metadata && typeof metadata === 'object') {
             const sharedTitle = (metadata as Record<string, unknown>).title;
             if (sharedTitle) {
               setTitle(sharedTitle as string || '');
             }
           }
           setSource(firstMeta.source || '');
           setEventType(firstMeta.eventType || '');
           setEpsg(firstMeta.epsg || '');
           setCountries(firstMeta.countries || []);
        if (imageType === 'drone_image') {
             setCenterLon(firstMeta.centerLon || '');
             setCenterLat(firstMeta.centerLat || '');
             setAmslM(firstMeta.amslM || '');
             setAglM(firstMeta.aglM || '');
             setHeadingDeg(firstMeta.headingDeg || '');
             setYawDeg(firstMeta.yawDeg || '');
             setPitchDeg(firstMeta.pitchDeg || '');
             setRollDeg(firstMeta.rollDeg || '');
             setRtkFix(firstMeta.rtkFix || false);
             setStdHM(firstMeta.stdHM || '');
             setStdVM(firstMeta.stdVM || '');
           }
         }
       }
     }

      // Extract the three parts from the metadata
      const extractedMetadataForParts = (capJson.raw_json as Record<string, unknown>)?.metadata;
      if (extractedMetadataForParts) {
        if ((extractedMetadataForParts as Record<string, unknown>).description) {
          setDescription((extractedMetadataForParts as Record<string, unknown>).description as string);
        }
        if ((extractedMetadataForParts as Record<string, unknown>).analysis) {
          setAnalysis((extractedMetadataForParts as Record<string, unknown>).analysis as string);
        }
        if ((extractedMetadataForParts as Record<string, unknown>).recommended_actions) {
          setRecommendedActions((extractedMetadataForParts as Record<string, unknown>).recommended_actions as string);
        }
      }
      
      if (capJson.generated) {
        setDraft(capJson.generated as string);
      }
      handleStepChange('2a');
  }

  async function handleSubmit() {
    console.log('handleSubmit called with:', { uploadedImageId, title, draft });
    if (!uploadedImageId) return alert("No image to submit");
    
    if (!isPerformanceConfirmed) {
      setShowRatingWarning(true);
      return;
    }
    
    setIsSubmitting(true);
    
    try {
        // Use stored image IDs for multi-image uploads
        const imageIds = uploadedImageIds.length > 0 ? uploadedImageIds : [uploadedImageId!];
        console.log('DEBUG: Submit - Using image IDs:', imageIds);
        console.log('DEBUG: Submit - uploadedImageIds:', uploadedImageIds);
        console.log('DEBUG: Submit - uploadedImageId:', uploadedImageId);
       
       // Update metadata for each image
       for (let i = 0; i < imageIds.length; i++) {
         const imageId = imageIds[i];
         const metadata = metadataArray[i] || {
           source: source || 'OTHER',
           eventType: eventType || 'OTHER',
        epsg: epsg || 'OTHER',
           countries: countries || []
         };
         
         const metadataBody = {
           source: imageType === 'drone_image' ? undefined : (metadata.source || 'OTHER'),
           event_type: metadata.eventType || 'OTHER',
           epsg: metadata.epsg || 'OTHER',
        image_type: imageType,
           countries: metadata.countries || [],
      };
         
         console.log(`Updating metadata for image ${i + 1}:`, metadataBody);
         const metadataRes = await fetch(`/api/images/${imageId}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(metadataBody),
      });
      const metadataJson = await readJsonSafely(metadataRes);
         if (!metadataRes.ok) throw new Error((metadataJson.error as string) || `Metadata update failed for image ${i + 1}`);
       }
      
      const combinedContent = `Description: ${description}\n\nAnalysis: ${analysis}\n\nRecommended Actions: ${recommendedActions}`;
      
      const captionBody = {
        title: title,
        edited: combinedContent,
        accuracy: scores.accuracy,
        context: scores.context,
        usability: scores.usability,
      };
      console.log('Updating caption:', captionBody);
      const captionRes = await fetch(`/api/images/${uploadedImageId}/caption`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(captionBody),
      });
      const captionJson = await readJsonSafely(captionRes);
      if (!captionRes.ok) throw new Error((captionJson.error as string) || "Caption update failed");
      
      setUploadedImageId(null);
     setUploadedImageIds([]);
      handleStepChange(3);
    } catch (err) {
      handleApiError(err, 'Submit');
    } finally {
      setIsSubmitting(false);
    }
  }

  async function handleDelete() {
    console.log('handleDelete called with uploadedImageId:', uploadedImageId);
    if (!uploadedImageId) {
      alert('No image to delete. Please try refreshing the page.');
      return;
    }
    
    setShowDeleteConfirm(true);
  }

  async function confirmDelete() {
    try {
      console.log('Deleting image with ID:', uploadedImageId);
      const res = await fetch(`/api/images/${uploadedImageId}`, {
        method: "DELETE",
      });
      
      if (!res.ok) {
        const json = await readJsonSafely(res);
        throw new Error((json.error as string) || `Delete failed with status ${res.status}`);
      }
      
      setShowDeleteConfirm(false);
        resetToStep1();
    } catch (err) {
      handleApiError(err, 'Delete');
    }
  }

  const resetToStep1 = () => {
    setIsPerformanceConfirmed(false);
    setStep(1);
    setFile(null);
    setFiles([]);
    setPreview(null);
         setUploadedImageId(null);
     setUploadedImageIds([]);
     setImageUrl(null);
    setTitle('');
    setSource('');
    setEventType('');
    setEpsg('');
    setCountries([]);
    setCenterLon('');
    setCenterLat('');
    setAmslM('');
    setAglM('');
    setHeadingDeg('');
    setYawDeg('');
    setPitchDeg('');
    setRollDeg('');
    setRtkFix(false);
    setStdHM('');
    setStdVM('');
    setScores({ accuracy: 50, context: 50, usability: 50 });
    setDraft('');
    setDescription('');
    setAnalysis('');
    setRecommendedActions('');
    setMetadataArray([]);
    setShowFallbackNotification(false);
    setFallbackInfo(null);
    setShowPreprocessingNotification(false);
    setPreprocessingInfo(null);
    setShowPreprocessingModal(false);
    setPreprocessingFile(null);
    setIsPreprocessing(false);
    setPreprocessingProgress('');
    setShowUnsupportedFormatModal(false);
    setUnsupportedFile(null);
    setShowFileSizeWarningModal(false);
    setOversizedFile(null);
    
    // Clear URL parameters to prevent re-triggering contribute workflow
    navigate('/upload', { replace: true });
  };

  // Navigation handling
  const handleNavigation = useCallback((to: string) => {
    if (to === '/upload' || to === '/') {
      return;
    }
    
    if (uploadedImageIdRef.current) {
      setPendingNavigation(to);
      setShowNavigationConfirm(true);
    } else {
      navigate(to);
    }
  }, [navigate]);

  async function confirmNavigation() {
    if (pendingNavigation && uploadedImageIdRef.current) {
      try {
        await fetch(`/api/images/${uploadedImageIdRef.current}`, { method: "DELETE" });
        setShowNavigationConfirm(false);
        setPendingNavigation(null);
        navigate(pendingNavigation);
      } catch (error) {
        console.error('Failed to delete image before navigation:', error);
        setShowNavigationConfirm(false);
        setPendingNavigation(null);
        navigate(pendingNavigation);
      }
    }
  }

  // Preprocessing handlers
  const handlePreprocessingConfirm = async () => {
    if (!preprocessingFile) return;
    
    setIsPreprocessing(true);
    setPreprocessingProgress('Starting file conversion...');
    
    try {
      const formData = new FormData();
      formData.append('file', preprocessingFile);
      formData.append('preprocess_only', 'true');
      
      setPreprocessingProgress('Converting file format...');
      
      const response = await fetch('/api/images/preprocess', {
        method: 'POST',
        body: formData
      });
      
      if (!response.ok) {
        throw new Error('Preprocessing failed');
      }
      
      const result = await response.json();
      
      setPreprocessingProgress('Finalizing conversion...');
      
      const processedContent = atob(result.processed_content);
      const processedBytes = new Uint8Array(processedContent.length);
      for (let i = 0; i < processedContent.length; i++) {
        processedBytes[i] = processedContent.charCodeAt(i);
      }
      
      const processedFile = new File(
        [processedBytes], 
        result.processed_filename, 
        { type: result.processed_mime_type }
      );
      
      const previewUrl = URL.createObjectURL(processedFile);
      
             // If this is the first file, set it as the single file
       if (files.length === 0) {
         setFile(processedFile);
         setFiles([processedFile]);
       } else {
         // If files already exist, add to the array (multi-upload mode)
         setFiles(prev => [...prev, processedFile]);
       }
       setPreview(previewUrl);
      
      setPreprocessingProgress('Conversion complete!');
      
      setTimeout(() => {
        setShowPreprocessingModal(false);
        setPreprocessingFile(null);
        setIsPreprocessing(false);
        setPreprocessingProgress('');
      }, 1000);
      
    } catch (error) {
      console.error('Preprocessing error:', error);
      setPreprocessingProgress('Conversion failed. Please try again.');
      setTimeout(() => {
        setShowPreprocessingModal(false);
        setPreprocessingFile(null);
        setIsPreprocessing(false);
        setPreprocessingProgress('');
      }, 2000);
    }
  };

  const handlePreprocessingCancel = () => {
    setShowPreprocessingModal(false);
    setPreprocessingFile(null);
    setIsPreprocessing(false);
    setPreprocessingProgress('');
  };

  // Fetch contributed images from database and convert to File objects
  const fetchContributedImages = async (imageIds: string[]) => {
    setIsLoadingContribution(true);
    try {
      const filePromises = imageIds.map(async (imageId) => {
        // Fetch image data from the API
        const response = await fetch(`/api/images/${imageId}`);
        if (!response.ok) {
          throw new Error(`Failed to fetch image ${imageId}`);
        }
        const imageData = await response.json();
        
        // Fetch the actual image file
        const fileResponse = await fetch(`/api/images/${imageId}/file`);
        if (!fileResponse.ok) {
          throw new Error(`Failed to fetch image file ${imageId}`);
        }
        const blob = await fileResponse.blob();
        
        // Create a File object from the blob
        const fileName = imageData.file_key.split('/').pop() || `contributed_${imageId}.png`;
        const file = new File([blob], fileName, { type: blob.type });
        
        return { file, imageData };
      });
      
      const contributedResults = await Promise.all(filePromises);
      const contributedFiles = contributedResults.map(result => result.file);
      const firstImageData = contributedResults[0]?.imageData;
      
      setFiles(contributedFiles);
      
      // Set the image IDs for submit process
      setUploadedImageIds(imageIds);
      if (imageIds.length === 1) {
        setUploadedImageId(imageIds[0]);
      }
      
      // Set the first file as the main file for single upload compatibility
      if (contributedFiles.length >= 1) {
        setFile(contributedFiles[0]);
      }
      
      // Set the image type based on the contributed image's type
      if (firstImageData?.image_type) {
        setImageType(firstImageData.image_type);
      }
      
      // Stay on step 1 to show the images in the file upload section
      
    } catch (error) {
      console.error('Failed to fetch contributed images:', error);
      alert(`Failed to load contributed images: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsLoadingContribution(false);
    }
  };



  // Effects
  useEffect(() => {
    Promise.all([
      fetch('/api/sources').then(r => r.json()),
      fetch('/api/types').then(r => r.json()),
      fetch('/api/spatial-references').then(r => r.json()),
      fetch('/api/image-types').then(r => r.json()),
      fetch('/api/countries').then(r => r.json()),
      fetch('/api/models').then(r => r.json())
    ]).then(([sourcesData, typesData, spatialData, imageTypesData, countriesData, modelsData]) => {
      if (!localStorage.getItem(SELECTED_MODEL_KEY) && modelsData?.length) {
        localStorage.setItem(SELECTED_MODEL_KEY, modelsData[0].m_code);
      }
      setSources(sourcesData);
      setTypes(typesData);
      setSpatialReferences(spatialData);
      setImageTypes(imageTypesData);
      setCountriesOptions(countriesData);
      
      if (sourcesData.length > 0) setSource(sourcesData[0].s_code);
      setEventType('OTHER');
      setEpsg('OTHER');
      if (imageTypesData.length > 0 && !searchParams.get('imageType') && !imageType) {
        setImageType(imageTypesData[0].image_type);
      }
    });
  }, [searchParams, imageType]);

  useEffect(() => {
    window.confirmNavigationIfNeeded = (to: string) => {
      handleNavigation(to);
    };
    
    return () => {
      delete window.confirmNavigationIfNeeded;
    };
  }, [handleNavigation]);

  useEffect(() => {
    const handleBeforeUnload = (event: BeforeUnloadEvent) => {
      if (uploadedImageIdRef.current) {
        const message = 'You have an uploaded image that will be deleted if you leave this page. Are you sure you want to leave?';
        event.preventDefault();
        event.returnValue = message;
        return message;
      }
    };

    const handleCleanup = () => {
      if (uploadedImageIdRef.current) {
        fetch(`/api/images/${uploadedImageIdRef.current}`, { method: "DELETE" }).catch(console.error);
      }
    };

    const handleGlobalClick = (event: MouseEvent) => {
      const target = event.target as HTMLElement;
      const link = target.closest('a[href]') || target.closest('[data-navigate]');
      
      if (link && uploadedImageIdRef.current) {
        const href = link.getAttribute('href') || link.getAttribute('data-navigate');
        if (href && href !== '#' && !href.startsWith('javascript:') && !href.startsWith('mailto:')) {
          event.preventDefault();
          event.stopPropagation();
          handleNavigation(href);
        }
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);
    document.addEventListener('click', handleGlobalClick, true);
    
    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
      document.removeEventListener('click', handleGlobalClick, true);
      handleCleanup();
    };
  }, [handleNavigation]);

  useEffect(() => {
    if (!file) {
      setPreview(null);
      return;
    }
    const url = URL.createObjectURL(file);
    setPreview(url);
    return () => URL.revokeObjectURL(url);
  }, [file]);

  // Handle contribute parameter - fetch images from database
  useEffect(() => {
    const contribute = searchParams.get('contribute');
    const imageIds = searchParams.get('imageIds');
    
    if (contribute === 'true' && imageIds) {
      const ids = imageIds.split(',').filter(id => id.trim());
      if (ids.length > 0) {
        fetchContributedImages(ids);
      }
    }
  }, [searchParams]);

  // Reset carousel index when entering step 2b
  useEffect(() => {
    if (step === '2b') {
      setCurrentImageIndex(0);
    }
  }, [step]);

  // Render
  return (
    <PageContainer>
      {step !== 3 && (
        <div className="max-w-7xl mx-auto">
          <div className={styles.uploadContainer} data-step={step}>
            {/* Step 1: File Upload */}
          {step === 1 && !searchParams.get('step') && !isLoadingContribution && (
              <FileUploadSection
                files={files}
                file={file}
                preview={preview}
                imageType={imageType}
                onFileChange={onFileChange}
                onRemoveImage={removeImage}
                onAddImage={addImage}
                onImageTypeChange={handleImageTypeChange}
                onChangeFile={onChangeFile}
              />
            )}

            {/* Step 1: Contributed Images Display */}
          {step === 1 && searchParams.get('contribute') === 'true' && !isLoadingContribution && files.length > 0 && (
              <FileUploadSection
                files={files}
                file={file}
                preview={preview}
                imageType={imageType}
                onFileChange={onFileChange}
                onRemoveImage={removeImage}
                onAddImage={addImage}
                onImageTypeChange={handleImageTypeChange}
                onChangeFile={onChangeFile}
              />
            )}

            {/* Loading States */}
        {isLoading && (
          <div className={styles.loadingContainer}>
            <Spinner className="text-ifrcRed" />
                                <p className={styles.loadingText}>Generating...</p>
          </div>
        )}

        {isLoadingContribution && (
          <div className={styles.loadingContainer}>
            <Spinner className="text-ifrcRed" />
            <p className={styles.loadingText}>Loading contribution...</p>
          </div>
        )}

            {/* Generate Button */}
        {((step === 1 && !isLoading && !isLoadingContribution) || (step === 1 && searchParams.get('contribute') === 'true' && !isLoading && !isLoadingContribution && files.length > 0)) && (
          <div className={styles.generateButtonContainer}>
            {imageUrl ? (
              <Button
                name="generate-from-url"
                    onClick={handleGenerate}
              >
                Generate Caption
              </Button>
            ) : (
              <Button
                name="generate"
                    disabled={files.length === 0}
                onClick={handleGenerate}
              >
                Generate
              </Button>
            )}
          </div>
        )}

            {/* Step 2A: Metadata */}
        {step === '2a' && (
          <div className={styles.step2Layout}>
            <div className={styles.mapColumn}>
                  <ImagePreviewSection
                    files={files}
                    imageUrl={imageUrl}
                    preview={preview}
                    onViewFullSize={(imageData) => {
                      setSelectedImageData(imageData || null);
                      setIsFullSizeModalOpen(true);
                    }}
                  />
            </div>

            <div className={styles.contentColumn}>
              <div className={styles.metadataSectionCard}>
                    <MetadataFormSection
                      files={files}
                      imageType={imageType}
                      title={title}
                      source={source}
                      eventType={eventType}
                      epsg={epsg}
                      countries={countries}
                      centerLon={centerLon}
                      centerLat={centerLat}
                      amslM={amslM}
                      aglM={aglM}
                      headingDeg={headingDeg}
                      yawDeg={yawDeg}
                      pitchDeg={pitchDeg}
                      rollDeg={rollDeg}
                      rtkFix={rtkFix}
                      stdHM={stdHM}
                      stdVM={stdVM}
                      metadataArray={metadataArray}
                      sources={sources}
                      types={types}
                      spatialReferences={spatialReferences}
                      imageTypes={imageTypes}
                      countriesOptions={countriesOptions}
                      onTitleChange={(value) => setTitle(value || '')}
                      onSourceChange={handleSourceChange}
                      onEventTypeChange={handleEventTypeChange}
                      onEpsgChange={handleEpsgChange}
                      onCountriesChange={handleCountriesChange}
                      onCenterLonChange={handleCenterLonChange}
                      onCenterLatChange={handleCenterLatChange}
                      onAmslMChange={handleAmslMChange}
                      onAglMChange={handleAglMChange}
                      onHeadingDegChange={handleHeadingDegChange}
                      onYawDegChange={handleYawDegChange}
                      onPitchDegChange={handlePitchDegChange}
                      onRollDegChange={handleRollDegChange}
                      onRtkFixChange={handleRtkFixChange}
                      onStdHMChange={handleStdHMChange}
                      onStdVMChange={handleStdVMChange}
                      onImageTypeChange={handleImageTypeChange}
                      updateMetadataForImage={updateMetadataForImage}
                    />
                  <div className={styles.confirmSection}>
                    <IconButton
                      name="delete"
                      variant="tertiary"
                      onClick={handleDelete}
                      title="Delete"
                      ariaLabel="Delete uploaded image"
                    >
                      <DeleteBinLineIcon />
                    </IconButton>
                    <Button
                      name="confirm-metadata"
                           onClick={() => handleStepChange('2b')}
                    >
                      Next
                    </Button>
                  </div>
              </div>
            </div>
          </div>
        )}

            {/* Step 2B: Rating and Generated Text */}
        {step === '2b' && (
          <div className={styles.step2bLayout}>
            {/* Submit Loading State */}
            {isSubmitting && (
              <div className={styles.loadingContainer}>
                <Spinner className="text-ifrcRed" />
                <p className={styles.loadingText}>Submitting...</p>
              </div>
            )}
            
            <div className={`${styles.topRow} ${isPerformanceConfirmed ? styles.ratingHidden : ''}`}>
              <div className={styles.imageSection}>
                    <ImagePreviewSection
                      files={files}
                      imageUrl={imageUrl}
                      preview={preview}
                      onViewFullSize={(imageData) => {
                        setSelectedImageData(imageData || null);
                        setIsFullSizeModalOpen(true);
                      }}
                      currentImageIndex={currentImageIndex}
                      onGoToPrevious={goToPrevious}
                      onGoToNext={goToNext}
                      onGoToImage={goToImage}
                      showCarousel={true}
                    />
              </div>

              {!isPerformanceConfirmed && (
                <div className={styles.metadataSectionCard}>
                      <RatingSection
                        isPerformanceConfirmed={isPerformanceConfirmed}
                        scores={scores}
                        onScoreChange={(key, value) => setScores(prev => ({ ...prev, [key]: value }))}
                        onConfirmRatings={() => setIsPerformanceConfirmed(true)}
                        onEditRatings={() => setIsPerformanceConfirmed(false)}
                      />
                </div>
              )}
            </div>

            <div className={styles.metadataSectionCard}>
                  <GeneratedTextSection
                    description={description}
                    analysis={analysis}
                    recommendedActions={recommendedActions}
                    onDescriptionChange={(value) => setDescription(value || '')}
                    onAnalysisChange={(value) => setAnalysis(value || '')}
                    onRecommendedActionsChange={(value) => setRecommendedActions(value || '')}
                    onBack={() => handleStepChange('2a')}
                    onDelete={handleDelete}
                    onSubmit={handleSubmit}
                    onEditRatings={() => setIsPerformanceConfirmed(false)}
                    isPerformanceConfirmed={isPerformanceConfirmed}
                    isSubmitting={isSubmitting}
                  />
            </div>
          </div>
        )}
        </div>
        </div>
      )}

      {/* Success page */}
      {step === 3 && (
        <div className={styles.successContainer}>
          <Heading level={2} className={styles.successHeading}>Saved!</Heading>
          <p className={styles.successText}>
            {searchParams.get('contribute') === 'true' 
              ? 'Your contribution has been successfully saved.' 
              : 'Your caption has been successfully saved.'
            }
          </p>
          <div className={styles.successButton}>
            <Button
              name="upload-another"
              onClick={() => {
                  resetToStep1();
              }}
            >
              Upload Another
            </Button>
          </div>
        </div>
      )}

      {/* Modals */}
             <FullSizeImageModal
         isOpen={isFullSizeModalOpen}
         imageUrl={imageUrl}
         preview={preview}
         selectedImageData={selectedImageData}
         onClose={() => {
           setIsFullSizeModalOpen(false);
           setSelectedImageData(null);
         }}
       />

      <RatingWarningModal
        isOpen={showRatingWarning}
        onClose={() => setShowRatingWarning(false)}
      />

      <DeleteConfirmModal
        isOpen={showDeleteConfirm}
        onConfirm={confirmDelete}
        onCancel={() => setShowDeleteConfirm(false)}
      />

      <NavigationConfirmModal
        isOpen={showNavigationConfirm}
        onConfirm={confirmNavigation}
        onCancel={() => setShowNavigationConfirm(false)}
      />

      <FallbackNotificationModal
        isOpen={showFallbackNotification}
        fallbackInfo={fallbackInfo}
        onClose={() => setShowFallbackNotification(false)}
      />

      <PreprocessingNotificationModal
        isOpen={showPreprocessingNotification}
        preprocessingInfo={preprocessingInfo}
        onClose={() => setShowPreprocessingNotification(false)}
      />

      <PreprocessingModal
        isOpen={showPreprocessingModal}
        preprocessingFile={preprocessingFile}
        isPreprocessing={isPreprocessing}
        preprocessingProgress={preprocessingProgress}
        onConfirm={handlePreprocessingConfirm}
        onCancel={handlePreprocessingCancel}
      />

      <UnsupportedFormatModal
        isOpen={showUnsupportedFormatModal}
        unsupportedFile={unsupportedFile}
        onClose={() => setShowUnsupportedFormatModal(false)}
      />

      <FileSizeWarningModal
        isOpen={showFileSizeWarningModal}
        oversizedFile={oversizedFile}
        onClose={() => setShowFileSizeWarningModal(false)}
        onCancel={() => setShowFileSizeWarningModal(false)}
      />


    </PageContainer>
  );
}