File size: 73,166 Bytes
b9cd14b
7a38f4f
b9cd14b
2c28af1
e76cac2
9253509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810c33d
9253509
e76cac2
 
b9cd14b
 
e76cac2
150f04b
b9cd14b
 
 
 
 
 
2c28af1
e76cac2
 
 
 
 
 
 
 
b9cd14b
 
37fda38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e76cac2
 
 
 
 
 
 
 
 
 
 
 
 
 
42babfe
 
 
 
 
 
 
 
 
b187543
b9cd14b
 
 
 
 
 
 
 
b187543
 
 
 
 
 
b9cd14b
 
 
2c28af1
b9cd14b
 
 
 
42babfe
 
 
 
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
edcff68
b9cd14b
 
 
 
 
7394679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
 
 
 
 
c85593f
b9cd14b
 
 
 
 
810c33d
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c85593f
 
b9cd14b
 
 
 
 
 
 
c85593f
 
 
 
810c33d
 
 
 
 
c85593f
 
 
 
 
 
 
 
 
 
810c33d
 
 
 
 
c85593f
 
 
 
 
b9cd14b
 
 
c85593f
b9cd14b
c85593f
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c85593f
b9cd14b
c85593f
 
b9cd14b
 
 
 
 
 
b187543
9253509
 
 
 
b187543
 
 
 
 
 
 
 
9253509
 
 
 
 
 
2c28af1
9253509
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b187543
9253509
 
 
 
7394679
 
 
 
 
 
 
e76cac2
 
 
b9cd14b
 
e76cac2
 
150f04b
b187543
37fda38
7a38f4f
2ba39f6
e76cac2
b9cd14b
 
 
 
 
 
 
 
 
 
 
2c28af1
810c33d
37fda38
2d73657
 
 
b9cd14b
af27681
b9cd14b
2c28af1
 
9253509
8f69e9d
 
b9cd14b
 
 
 
 
 
 
 
 
e76cac2
b9cd14b
 
 
 
e76cac2
 
 
b9cd14b
 
e76cac2
 
150f04b
b187543
37fda38
b9cd14b
 
 
 
 
 
 
 
 
 
2c28af1
810c33d
37fda38
2d73657
 
b9cd14b
2c28af1
e76cac2
 
 
8f69e9d
 
 
 
 
 
 
 
 
 
 
 
e76cac2
810c33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9253509
 
 
 
8f69e9d
 
 
 
 
 
 
 
 
 
7394679
 
 
 
9253509
 
 
 
 
 
 
 
 
 
 
 
810c33d
 
9253509
 
 
 
810c33d
 
 
37fda38
 
 
 
810c33d
 
 
 
 
 
 
 
37fda38
810c33d
 
 
37fda38
 
 
 
 
 
 
 
 
 
 
 
 
 
810c33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b187543
9253509
 
 
 
 
 
 
7394679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8f69e9d
9253509
7394679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9253509
 
 
 
e76cac2
 
 
 
 
 
 
 
 
 
 
 
 
 
7a38f4f
 
 
2ba39f6
7a38f4f
 
 
2ba39f6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7a38f4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42babfe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
 
b187543
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d2b0e4f
b9cd14b
 
 
 
 
 
 
b187543
b9cd14b
2c28af1
 
 
 
 
 
 
 
 
 
 
 
 
810c33d
37fda38
 
 
 
 
2c28af1
 
 
 
 
 
 
 
 
 
 
 
 
 
810c33d
37fda38
2c28af1
 
37fda38
 
 
2d73657
 
 
 
 
 
 
 
 
37fda38
 
2d73657
 
 
 
 
 
 
 
 
 
 
 
37fda38
 
2d73657
37fda38
2d73657
 
37fda38
 
 
2c28af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
 
 
 
 
 
810c33d
b9cd14b
 
 
 
 
 
 
2c28af1
 
 
 
 
 
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810c33d
 
 
56eda2f
 
 
 
 
 
810c33d
37fda38
 
 
 
2d73657
 
37fda38
 
2c28af1
 
 
 
 
b9cd14b
 
 
2c28af1
37fda38
2d73657
 
b9cd14b
 
8f69e9d
 
 
b9cd14b
 
 
 
2c28af1
37fda38
2d73657
 
b9cd14b
 
8f69e9d
 
 
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c28af1
b9cd14b
 
e76cac2
b9cd14b
 
 
 
e76cac2
b9cd14b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e76cac2
 
b9cd14b
 
 
 
 
 
 
 
 
 
 
e76cac2
2c28af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e76cac2
 
 
 
 
 
 
 
 
7394679
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b187543
7394679
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
 
 
 
 
 
2c28af1
b9cd14b
 
 
 
 
2c28af1
 
b9cd14b
 
2c28af1
e76cac2
7394679
e76cac2
 
2c28af1
 
 
 
 
 
 
 
 
 
 
 
 
e76cac2
7394679
e76cac2
b9cd14b
 
 
150f04b
b187543
9253509
 
 
2c28af1
 
e76cac2
 
 
 
7394679
 
 
 
 
 
 
 
 
e76cac2
 
 
 
 
 
 
 
 
 
 
 
 
7394679
e76cac2
150f04b
 
 
b9cd14b
150f04b
 
e76cac2
 
 
 
 
 
7394679
e76cac2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b9cd14b
e76cac2
 
 
 
b9cd14b
e76cac2
 
 
 
dca1812
e76cac2
 
 
 
 
 
 
 
b9cd14b
e76cac2
 
 
 
 
 
 
b9cd14b
 
 
e76cac2
b9cd14b
 
 
 
 
 
e76cac2
b9cd14b
 
e76cac2
 
 
 
 
7a38f4f
 
 
b187543
 
7a38f4f
2ba39f6
37fda38
 
7a38f4f
e76cac2
b9cd14b
 
 
 
 
 
 
810c33d
2c28af1
 
 
 
810c33d
 
 
2c28af1
 
810c33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c28af1
 
 
 
 
 
 
 
 
 
810c33d
2c28af1
 
 
 
b9cd14b
af27681
b9cd14b
 
 
af27681
 
 
 
b9cd14b
2c28af1
37fda38
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2d73657
37fda38
 
 
 
 
2c28af1
810c33d
2c28af1
 
 
 
 
810c33d
 
 
 
 
 
 
 
56eda2f
 
810c33d
 
 
 
 
 
 
b9cd14b
 
 
 
 
7394679
b9cd14b
 
 
 
 
810c33d
b9cd14b
 
 
 
 
 
e76cac2
 
9253509
 
b187543
9253509
 
2c28af1
 
 
 
 
 
 
 
 
9253509
 
 
2c28af1
 
150f04b
9253509
 
2c28af1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
810c33d
 
 
 
 
 
 
 
9253509
 
 
 
 
efb696b
9253509
 
 
 
 
 
 
 
 
 
e76cac2
9253509
 
 
 
 
e76cac2
 
 
 
 
31d48c9
 
 
 
 
2c28af1
31d48c9
2c28af1
31d48c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c28af1
31d48c9
 
 
 
e76cac2
 
 
 
 
 
 
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
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { apiFetch } from '@/lib/api';
import { mergeSequenceIntoContacts } from '@/lib/mergeSequenceIntoContacts';
import { buildGenerateSequencesUrl } from '@/lib/campaignGenerationStream';
import { createPortal } from 'react-dom';
import {
    X,
    Upload,
    ArrowRight,
    ArrowLeft,
    Sparkles,
    Loader2,
    CheckCircle2,
    Search,
    Filter,
    Mail,
    UserPlus,
    MessageCircle,
    Clock,
    ChevronRight,
    AlertTriangle,
} from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Progress } from '@/components/ui/progress';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { cn } from '@/lib/utils';
import CampaignSequenceBuilder, { createDefaultSequenceSteps } from '@/components/campaigns/CampaignSequenceBuilder';
import ProductSelector from '@/components/products/ProductSelector';
import PromptEditor, {
    DEFAULT_TEMPLATES,
    LINKEDIN_DEFAULT_TEMPLATES,
} from '@/components/prompts/PromptEditor';
import SequenceCard from '@/components/sequences/SequenceCard';
import { formatWaitStep } from '@/lib/waitStepUtils';

const STEPS = [
    { id: 1, label: 'Upload & Select' },
    { id: 2, label: 'Configure Sequence' },
    { id: 3, label: 'Generate Contents' },
    { id: 4, label: 'Review & Launch' },
];

const WIZARD_SEQUENCE_TAG = '🔒 CAMPAIGN WIZARD — SEQUENCE';

function defaultEmailSendingSettings() {
    let timezone = '';
    try {
        timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || '';
    } catch {
        timezone = '';
    }
    return {
        timezone,
        businessHoursStart: 8,
        businessHoursEnd: 18,
        businessDays: [1, 2, 3, 4, 5],
        intervalSeconds: 60,
    };
}

function estimateCsvRows(file) {
    if (!file) return 0;
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.onload = (e) => {
            const text = String(e.target?.result || '');
            const lines = text.split(/\r?\n/).filter((line) => line.trim().length > 0);
            resolve(Math.max(0, lines.length - 1));
        };
        reader.onerror = () => resolve(0);
        reader.readAsText(file.slice(0, Math.min(file.size, 512 * 1024)));
    });
}

function mailboxLabelForAppendixStep(step, mailboxDefaults) {
    if (step.channel !== 'gmail' || !mailboxDefaults) return '';
    const ref =
        step.unipile_account_ref_id ?? mailboxDefaults.default_mailbox_unipile_account_ref_id ?? null;
    if (ref == null) return '';
    const a = (mailboxDefaults.accounts || []).find((x) => Number(x.id) === Number(ref));
    return ((a?.display_name || a?.label || '') || '').trim();
}

function buildCampaignSequenceAppendix(steps, mailboxDefaults = null, parallelTracks = false) {
    const lines = [
        WIZARD_SEQUENCE_TAG,
        '(AUTHORITATIVE — OVERRIDES ANY FIXED “N EMAILS” OR “N MESSAGES” COUNT IN THIS PROMPT)',
        '',
        'The campaign sequence is fixed. Generate content only for the channels below; the system maps rows to Gmail vs LinkedIn.',
        'Respect wait steps as pacing context between touches (do not invent extra touches for waits).',
        '',
    ];
    if (parallelTracks) {
        lines.push(
            'Execution note: Gmail and LinkedIn run on separate timelines — a wait after an email does not delay LinkedIn steps (and vice versa).',
            ''
        );
    }
    let n = 0;
    (steps || []).forEach((s) => {
        if (s.type === 'wait') {
            lines.push(`• ${formatWaitStep(s)}`);
        }
        if (s.type === 'action') {
            n += 1;
            if (s.channel === 'gmail') {
                const mb = mailboxLabelForAppendixStep(s, mailboxDefaults);
                lines.push(
                    `${n}. Gmail — ${s.title || 'Email'}${mb ? ` (sending mailbox: ${mb})` : ''}`
                );
            } else if (s.channel === 'linkedin') {
                const kind =
                    s.action === 'linkedin_connect'
                        ? 'LinkedIn connection request (must be the first LinkedIn output before any DM)'
                        : 'LinkedIn DM / follow-up';
                lines.push(`${n}. ${kind} — ${s.title || ''}`);
            }
        }
    });
    lines.push(
        '',
        'LinkedIn: the first LinkedIn message in your output must be the connection request whenever the sequence includes a connection step before DMs.',
        'Write exactly one labeled LinkedIn message (Message i) per LinkedIn action listed above — same count and order; do not add extra LinkedIn messages beyond those actions.',
        'Keep narrative continuity with Gmail touches in the same campaign week where relevant.'
    );
    return lines.join('\n');
}

function progressFromGenerationStatus(st) {
    if (st?.is_complete) return 100;
    const total = st.total_contacts || 0;
    if (!total) return 0;
    const done = st.completed_count || 0;
    const exp =
        st.campaign_sequence_actions && total > 0
            ? total * st.campaign_sequence_actions
            : st.has_linkedin_prompts
              ? total * 2
              : total;
    return exp ? Math.min(100, Math.round((done / exp) * 100)) : 0;
}

function sequenceListToContacts(list) {
    let contacts = [];
    (list || []).forEach((row) => {
        contacts = mergeSequenceIntoContacts(contacts, {
            id: row.id,
            emailNumber: row.emailNumber,
            firstName: row.firstName,
            lastName: row.lastName,
            email: row.email,
            company: row.company,
            title: row.title,
            product: row.product,
            subject: row.subject,
            emailContent: row.emailContent,
            channel: row.channel || 'email',
            stepOrder: row.stepOrder != null ? row.stepOrder : undefined,
        });
    });
    contacts.sort((a, b) => (a.id || 0) - (b.id || 0));
    return contacts;
}

function WizardSequencePreview({
    contacts,
    sequences,
    isGenerating,
    generationComplete,
    generationStarted,
    progress,
    contactCount,
    selectedProducts,
    sequenceHasLinkedin,
    genPhase,
    hasFailures,
}) {
    const [searchQuery, setSearchQuery] = useState('');
    const [filterProduct, setFilterProduct] = useState('all');
    const [displayedCount, setDisplayedCount] = useState(50);

    useEffect(() => {
        setDisplayedCount(50);
    }, [searchQuery, filterProduct]);

    const filteredContacts = contacts.filter((contact) => {
        const matchesSearch =
            searchQuery === '' ||
            contact.firstName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            contact.lastName?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            contact.company?.toLowerCase().includes(searchQuery.toLowerCase()) ||
            contact.email?.toLowerCase().includes(searchQuery.toLowerCase());
        const matchesFilter = filterProduct === 'all' || contact.product === filterProduct;
        return matchesSearch && matchesFilter;
    });
    const displayedContacts = filteredContacts.slice(0, displayedCount);
    const hasMore = filteredContacts.length > displayedCount;
    const showProgress =
        generationStarted && (isGenerating || !generationComplete);
    const phaseLabel =
        sequenceHasLinkedin && genPhase === 'linkedin' && isGenerating
            ? 'LinkedIn sequences'
            : 'Email sequences';

    return (
        <div className="w-full space-y-4">
            {generationStarted ? (
                <div className="mb-2 rounded-2xl border border-slate-200 bg-white p-6">
                    <div className="mb-4 flex items-center justify-between">
                        <div className="flex items-center gap-3">
                            {generationComplete && hasFailures ? (
                                <div className="rounded-xl bg-amber-100 p-3">
                                    <AlertTriangle className="h-6 w-6 text-amber-600" />
                                </div>
                            ) : generationComplete ? (
                                <div className="rounded-xl bg-green-100 p-3">
                                    <CheckCircle2 className="h-6 w-6 text-green-600" />
                                </div>
                            ) : (
                                <div className="rounded-xl bg-violet-100 p-3">
                                    <Loader2 className="h-6 w-6 animate-spin text-violet-600" />
                                </div>
                            )}
                            <div>
                                <h3 className="font-semibold text-slate-800">
                                    {generationComplete
                                        ? hasFailures
                                            ? 'Generation finished with errors'
                                            : 'Generation complete!'
                                        : `Generating ${phaseLabel}…`}
                                </h3>
                                <p className="text-sm text-slate-500">
                                    {contacts.length} contacts · {sequences.length} generated rows
                                    {contactCount ? ` · ~${contactCount} contacts in file` : ''}
                                </p>
                            </div>
                        </div>
                    </div>
                    {showProgress ? <Progress value={progress} className="h-2" /> : null}
                </div>
            ) : null}

            {sequences.length > 0 && (
                <div className="flex flex-col gap-3 sm:flex-row">
                    <div className="relative flex-1">
                        <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" />
                        <Input
                            placeholder="Search contacts…"
                            value={searchQuery}
                            onChange={(e) => setSearchQuery(e.target.value)}
                            className="pl-10"
                        />
                    </div>
                    <Select value={filterProduct} onValueChange={setFilterProduct}>
                        <SelectTrigger className="w-full sm:w-48">
                            <Filter className="mr-2 h-4 w-4 text-slate-400" />
                            <SelectValue placeholder="Filter by product" />
                        </SelectTrigger>
                        <SelectContent>
                            <SelectItem value="all">All Products</SelectItem>
                            {selectedProducts.map((product) => (
                                <SelectItem key={product.id} value={product.name}>
                                    {product.name}
                                </SelectItem>
                            ))}
                        </SelectContent>
                    </Select>
                </div>
            )}

            <div className="custom-scrollbar max-h-[min(420px,50vh)] space-y-3 overflow-y-auto pr-1">
                {displayedContacts.map((contact, index) => (
                    <SequenceCard
                        key={contact.id || `${contact.firstName}-${contact.lastName}-${contact.email}`}
                        contact={contact}
                        index={index}
                    />
                ))}
                {hasMore && (
                    <div className="py-3 text-center">
                        <Button
                            type="button"
                            variant="outline"
                            onClick={() => setDisplayedCount((c) => Math.min(c + 50, filteredContacts.length))}
                        >
                            Load more ({filteredContacts.length - displayedCount} remaining)
                        </Button>
                    </div>
                )}
            </div>

            {!generationStarted && contacts.length === 0 && sequences.length === 0 && (
                <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/80 py-12 text-center text-sm text-slate-500">
                    Generated messages will appear here after you click Generate. You can continue to the next step
                    while generation runs in the background.
                </div>
            )}
        </div>
    );
}

function ReviewSequenceTimeline({ steps, parallelTracks }) {
    if (!steps?.length) {
        return <p className="text-sm text-slate-500">No sequence steps.</p>;
    }
    return (
        <div>
            {parallelTracks ? (
                <p className="mb-3 text-xs text-slate-600">
                    Parallel tracks: Gmail and LinkedIn advance on separate timers — waits only apply within the same
                    channel.
                </p>
            ) : null}
            <div className="flex flex-wrap items-center gap-1 py-2">
            {steps.map((s, i) => (
                <React.Fragment key={s.id || i}>
                    {i > 0 ? <ChevronRight className="mx-0.5 h-4 w-4 shrink-0 text-slate-300" /> : null}
                    {s.type === 'wait' ? (
                        <span className="inline-flex items-center gap-1 rounded-lg border border-dashed border-blue-200 bg-sky-50 px-2.5 py-1.5 text-xs font-medium text-slate-700">
                            <Clock className="h-3.5 w-3.5 text-blue-600" />
                            Wait {formatWaitStep(s, { short: true })}
                        </span>
                    ) : (
                        <span
                            className={cn(
                                'inline-flex max-w-[200px] items-center gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs font-medium',
                                s.channel === 'linkedin'
                                    ? 'border-sky-200 bg-sky-50 text-sky-900'
                                    : 'border-violet-200 bg-violet-50 text-violet-900'
                            )}
                        >
                            {s.action === 'linkedin_connect' ? (
                                <UserPlus className="h-3.5 w-3.5 shrink-0" />
                            ) : s.channel === 'linkedin' ? (
                                <MessageCircle className="h-3.5 w-3.5 shrink-0" />
                            ) : (
                                <Mail className="h-3.5 w-3.5 shrink-0" />
                            )}
                            <span className="truncate">{s.title || (s.channel === 'gmail' ? 'Email' : 'LinkedIn')}</span>
                        </span>
                    )}
                </React.Fragment>
            ))}
            </div>
        </div>
    );
}

export default function CreateCampaignWizard({
    open,
    onOpenChange,
    onComplete,
    onDraftPersist,
    initialCampaign = null,
}) {
    const [step, setStep] = useState(1);
    const [campaignName, setCampaignName] = useState('');
    const [prospectFile, setProspectFile] = useState(null);
    const [wizardUpload, setWizardUpload] = useState(null);
    const [uploadingCsv, setUploadingCsv] = useState(false);
    const [dragOver, setDragOver] = useState(false);
    const [estimatedContacts, setEstimatedContacts] = useState(0);
    const [sequenceSteps, setSequenceSteps] = useState(() => createDefaultSequenceSteps());
    const [parallelTracks, setParallelTracks] = useState(false);
    const [emailSendingSettings, setEmailSendingSettings] = useState(() => defaultEmailSendingSettings());
    const [linkedinDefaults, setLinkedinDefaults] = useState(null);
    const [mailboxDefaults, setMailboxDefaults] = useState(null);

    const [selectedProducts, setSelectedProducts] = useState([]);
    const [prompts, setPrompts] = useState({});
    const [linkedinPrompts, setLinkedinPrompts] = useState({});

    const [genSequences, setGenSequences] = useState([]);
    const [genContacts, setGenContacts] = useState([]);
    const [genProgress, setGenProgress] = useState(0);
    const [genRunning, setGenRunning] = useState(false);
    const [genComplete, setGenComplete] = useState(false);
    const [genPhase, setGenPhase] = useState('email');
    const [genRunId, setGenRunId] = useState(0);
    const [genPreviewOnly, setGenPreviewOnly] = useState(false);
    const [genFailedContacts, setGenFailedContacts] = useState([]);
    const [genStopping, setGenStopping] = useState(false);
    const [genStopTakingLong, setGenStopTakingLong] = useState(false);
    const genStopTimerRef = useRef(null);
    useEffect(() => () => clearTimeout(genStopTimerRef.current), []);
    const eventSourceRef = useRef(null);
    const promptEditorRef = useRef(null);
    const prevGenRunIdRef = useRef(null);
    const previewTriggeredRef = useRef(false);
    const genRunOptionsRef = useRef({ reset: true, preview: false });
    const hydratedCampaignIdRef = useRef(null);
    const openRef = useRef(open);
    openRef.current = open;

    const sequenceHasLinkedin = useMemo(
        () =>
            sequenceSteps.some(
                (s) => s.type === 'action' && s.channel === 'linkedin' && s.action !== 'email'
            ),
        [sequenceSteps]
    );

    const reset = useCallback(() => {
        if (eventSourceRef.current) {
            eventSourceRef.current.close();
            eventSourceRef.current = null;
        }
        setStep(1);
        setCampaignName('');
        setProspectFile(null);
        setWizardUpload(null);
        setUploadingCsv(false);
        setEstimatedContacts(0);
        setDragOver(false);
        setSequenceSteps(createDefaultSequenceSteps());
        setParallelTracks(false);
        setEmailSendingSettings(defaultEmailSendingSettings());
        setSelectedProducts([]);
        setPrompts({});
        setLinkedinPrompts({});
        setGenSequences([]);
        setGenContacts([]);
        setGenProgress(0);
        setGenRunning(false);
        setGenComplete(false);
        setGenPhase('email');
        setGenRunId(0);
        setGenPreviewOnly(false);
        setGenFailedContacts([]);
        setGenStopping(false);
        setGenStopTakingLong(false);
        clearTimeout(genStopTimerRef.current);
        prevGenRunIdRef.current = null;
        previewTriggeredRef.current = false;
    }, []);

    useEffect(() => {
        if (!open) {
            if (genRunning) return;
            reset();
        }
    }, [open, genRunning, reset]);

    /** Fresh "Create" session — clear any in-component state (including orphan streams). */
    useEffect(() => {
        if (open && !initialCampaign?.id) {
            reset();
        }
    }, [open, initialCampaign?.id, reset]);

    // Debounced backend auto-save of campaign identity — fires on name edits and every step
    // transition, not only when the wizard is explicitly closed, so an abrupt tab close never
    // strands already-generated server-side content with no way back to it.
    useEffect(() => {
        if (!open || !wizardUpload?.fileId) return;
        const fileId = wizardUpload.fileId;
        const name = campaignName.trim() || 'Untitled campaign';
        const timer = setTimeout(() => {
            apiFetch(`/api/campaign-files/${encodeURIComponent(fileId)}/meta`, {
                method: 'PATCH',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ file_id: fileId, campaign_name: name, status: 'draft' }),
            }).catch((e) => console.error(e));
        }, 800);
        return () => clearTimeout(timer);
    }, [open, wizardUpload?.fileId, campaignName, step]);

    useEffect(() => {
        if (!open || !initialCampaign?.id) return;
        if (hydratedCampaignIdRef.current === initialCampaign.id) return;
        hydratedCampaignIdRef.current = initialCampaign.id;
        const incomingFile = initialCampaign.fileId || null;
        const currentFile = wizardUpload?.fileId ?? null;
        if (eventSourceRef.current) {
            const keepStream =
                !!incomingFile && !!currentFile && incomingFile === currentFile;
            if (!keepStream) {
                eventSourceRef.current.close();
                eventSourceRef.current = null;
            }
        }
        setGenSequences([]);
        setGenContacts([]);
        setGenRunId(0);
        prevGenRunIdRef.current = null;
        setCampaignName(initialCampaign.name || '');
        setProspectFile(null);
        if (initialCampaign.fileId) {
            setWizardUpload({
                fileId: initialCampaign.fileId,
                contactCount: initialCampaign.contacts ?? 0,
                name: initialCampaign.prospectFileName || '',
            });
        } else {
            setWizardUpload(null);
        }
        const seq = initialCampaign.sequence;
        const hasLocalSequence = Array.isArray(seq) && seq.length > 0;
        if (hasLocalSequence) {
            setSequenceSteps(seq);
        } else {
            setSequenceSteps(createDefaultSequenceSteps());
        }
        // Local dashboard state can be missing the sequence entirely — e.g. a campaign
        // reconciled in from the backend list on a fresh session never had local `sequence`
        // populated. Fall back to the backend's saved sequence_plan_json so reopening a
        // campaign never silently resets it to the default Gmail-only template. Email pacing
        // settings live only on the backend record (never in local dashboard state), so this
        // fetch also runs when a local sequence is already present, purely to restore those.
        if (initialCampaign.fileId) {
            const fid = initialCampaign.fileId;
            const campaignId = initialCampaign.id;
            (async () => {
                try {
                    const res = await apiFetch(`/api/campaign-files/${encodeURIComponent(fid)}`);
                    if (!res.ok) return;
                    const detail = await res.json();
                    if (hydratedCampaignIdRef.current !== campaignId) return;
                    if (!hasLocalSequence && Array.isArray(detail.sequence_plan) && detail.sequence_plan.length > 0) {
                        setSequenceSteps(detail.sequence_plan);
                        setParallelTracks(!!detail.parallel_tracks);
                    }
                    if (detail.email_timezone !== undefined) {
                        setEmailSendingSettings({
                            timezone: detail.email_timezone || defaultEmailSendingSettings().timezone,
                            businessHoursStart:
                                detail.email_business_hours_start ?? 8,
                            businessHoursEnd: detail.email_business_hours_end ?? 18,
                            businessDays: (detail.email_business_days || '1,2,3,4,5')
                                .split(',')
                                .map((d) => parseInt(d, 10))
                                .filter((d) => !Number.isNaN(d)),
                            intervalSeconds: detail.email_send_interval_seconds ?? 60,
                        });
                    }
                    if (!hasLocalSequence && detail.prompts && Object.keys(detail.prompts).length) {
                        setPrompts((prev) => (Object.keys(prev).length ? prev : detail.prompts));
                    }
                    if (detail.linkedin_prompts && Object.keys(detail.linkedin_prompts).length) {
                        setLinkedinPrompts((prev) =>
                            Object.keys(prev).length ? prev : detail.linkedin_prompts
                        );
                    }
                    if (Array.isArray(detail.products) && detail.products.length) {
                        setSelectedProducts((prev) =>
                            prev.length
                                ? prev
                                : detail.products.map((name, i) => ({ id: `backend-${i}-${name}`, name }))
                        );
                    }
                } catch (e) {
                    console.error(e);
                }
            })();
        }
        setParallelTracks(!!initialCampaign.parallelTracks);
        setSelectedProducts(
            Array.isArray(initialCampaign.selectedProducts) ? initialCampaign.selectedProducts : []
        );
        setEstimatedContacts(initialCampaign.contacts || 0);
        setGenComplete(!!initialCampaign.generationComplete);
        setGenRunning(false);
        setGenProgress(initialCampaign.generationProgressPercent ?? 0);
        const ws =
            typeof initialCampaign.wizardStep === 'number'
                ? Math.min(4, Math.max(1, initialCampaign.wizardStep))
                : 1;
        setStep(ws);
        setPrompts(
            initialCampaign.wizardPrompts && typeof initialCampaign.wizardPrompts === 'object'
                ? { ...initialCampaign.wizardPrompts }
                : {}
        );
        setLinkedinPrompts(
            initialCampaign.wizardLinkedinPrompts &&
                typeof initialCampaign.wizardLinkedinPrompts === 'object'
                ? { ...initialCampaign.wizardLinkedinPrompts }
                : {}
        );
    }, [open, initialCampaign?.id, wizardUpload?.fileId]);

    useEffect(() => {
        if (!open || !wizardUpload?.fileId || !initialCampaign?.id) return;
        let cancelled = false;
        (async () => {
            try {
                const [stRes, seqRes] = await Promise.all([
                    apiFetch(`/api/generation-status?file_id=${encodeURIComponent(wizardUpload.fileId)}`),
                    apiFetch(`/api/sequences?file_id=${encodeURIComponent(wizardUpload.fileId)}`),
                ]);
                if (cancelled) return;
                if (seqRes.ok) {
                    const data = await seqRes.json();
                    const list = data.sequences || [];
                    setGenSequences(list);
                    setGenContacts(sequenceListToContacts(list));
                }
                if (stRes.ok) {
                    const st = await stRes.json();
                    if (!cancelled) {
                        setGenComplete(!!st.is_complete);
                        setGenProgress(progressFromGenerationStatus(st));
                    }
                }
            } catch (e) {
                if (!cancelled) console.error(e);
            }
        })();
        return () => {
            cancelled = true;
        };
    }, [open, wizardUpload?.fileId, initialCampaign?.id]);

    useEffect(() => {
        if (!open) hydratedCampaignIdRef.current = null;
    }, [open]);

    useEffect(() => {
        if (!prospectFile) {
            setEstimatedContacts(0);
            return;
        }
        let cancelled = false;
        estimateCsvRows(prospectFile).then((n) => {
            if (!cancelled) setEstimatedContacts(n);
        });
        return () => {
            cancelled = true;
        };
    }, [prospectFile]);

    useEffect(() => {
        if (!open) {
            setLinkedinDefaults(null);
            setMailboxDefaults(null);
            return;
        }
        let cancelled = false;
        Promise.allSettled([
            apiFetch('/api/unipile/linkedin/campaign-defaults').then((r) => r.json()),
            apiFetch('/api/unipile/mailbox/campaign-defaults').then((r) => r.json()),
        ]).then(([li, mb]) => {
            if (cancelled) return;
            setLinkedinDefaults(
                li.status === 'fulfilled'
                    ? li.value
                    : {
                          accounts: [],
                          linkedin_profile_display_name: '',
                          default_unipile_account_ref_id: null,
                      }
            );
            setMailboxDefaults(
                mb.status === 'fulfilled'
                    ? mb.value
                    : {
                          accounts: [],
                          mailbox_profile_display_name: '',
                          default_mailbox_unipile_account_ref_id: null,
                      }
            );
        });
        return () => {
            cancelled = true;
        };
    }, [open]);

    useEffect(() => {
        if (!linkedinDefaults) return;
        setSequenceSteps((prev) =>
            prev.map((s) => {
                if (s.type !== 'action' || s.channel !== 'linkedin') return s;
                const ref =
                    s.unipile_account_ref_id ?? linkedinDefaults.default_unipile_account_ref_id ?? null;
                const sender =
                    (s.sender_profile_name || '').trim() ||
                    (linkedinDefaults.linkedin_profile_display_name || '').trim();
                return {
                    ...s,
                    unipile_account_ref_id: ref,
                    sender_profile_name: sender,
                };
            })
        );
    }, [linkedinDefaults]);

    useEffect(() => {
        if (!mailboxDefaults) return;
        const accounts = mailboxDefaults.accounts || [];
        const fallbackId = accounts[0]?.id != null ? Number(accounts[0].id) : null;
        setSequenceSteps((prev) =>
            prev.map((s) => {
                if (s.type !== 'action' || s.channel !== 'gmail') return s;
                const ref =
                    s.unipile_account_ref_id ??
                    (mailboxDefaults.default_mailbox_unipile_account_ref_id != null
                        ? Number(mailboxDefaults.default_mailbox_unipile_account_ref_id)
                        : null) ??
                    fallbackId;
                return { ...s, unipile_account_ref_id: ref };
            })
        );
    }, [mailboxDefaults]);

    useEffect(() => {
        if (step !== 3 || selectedProducts.length === 0) return;
        const appendix = buildCampaignSequenceAppendix(sequenceSteps, mailboxDefaults, parallelTracks);
        setPrompts((prev) => {
            const next = { ...prev };
            let changed = false;
            selectedProducts.forEach((p) => {
                let cur = (next[p.name] || '').trim();
                if (!cur) {
                    cur = DEFAULT_TEMPLATES[p.name] || '';
                }
                if (!cur || cur.includes(WIZARD_SEQUENCE_TAG)) return;
                next[p.name] = `${cur}\n\n${appendix}`;
                changed = true;
            });
            return changed ? next : prev;
        });
        if (!sequenceHasLinkedin) return;
        setLinkedinPrompts((prev) => {
            const next = { ...prev };
            let changed = false;
            selectedProducts.forEach((p) => {
                let cur = (next[p.name] || '').trim();
                if (!cur) {
                    cur =
                        LINKEDIN_DEFAULT_TEMPLATES[p.name] ||
                        `🔒 LINKEDIN SYSTEM PROMPT\n\nYou write LinkedIn connection notes and DMs for ${p.name}. Message 1: peer-style connection only (~280 chars), no pitch; later messages add detail. Sign DMs with {{sender_name}}.\nMatch the Message count in the generation request exactly.`;
                }
                if (!cur || cur.includes(WIZARD_SEQUENCE_TAG)) return;
                next[p.name] = `${cur}\n\n${appendix}`;
                changed = true;
            });
            return changed ? next : prev;
        });
    }, [step, sequenceSteps, selectedProducts, sequenceHasLinkedin, mailboxDefaults, parallelTracks]);

    const savePromptsToServer = useCallback(async () => {
        promptEditorRef.current?.commitCampaignPrompts?.();
        const res = await apiFetch('/api/save-prompts', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                file_id: wizardUpload.fileId,
                prompts,
                products: selectedProducts.map((p) => p.name),
                linkedin_prompts: sequenceHasLinkedin ? linkedinPrompts : {},
                sequence_plan: parallelTracks
                    ? { parallel_tracks: true, steps: sequenceSteps }
                    : sequenceSteps,
                campaign_name: campaignName.trim() || 'Untitled campaign',
                email_timezone: emailSendingSettings.timezone || null,
                email_business_hours_start: emailSendingSettings.businessHoursStart,
                email_business_hours_end: emailSendingSettings.businessHoursEnd,
                email_business_days: (emailSendingSettings.businessDays || []).join(','),
                email_send_interval_seconds: emailSendingSettings.intervalSeconds,
            }),
        });
        if (!res.ok) {
            const err = await res.json().catch(() => ({}));
            throw new Error(err.detail || res.statusText);
        }
    }, [
        wizardUpload?.fileId,
        prompts,
        selectedProducts,
        linkedinPrompts,
        sequenceHasLinkedin,
        sequenceSteps,
        parallelTracks,
        campaignName,
        emailSendingSettings,
    ]);

    const stopGeneration = useCallback(async () => {
        if (!wizardUpload?.fileId) return;
        setGenStopping(true);
        setGenStopTakingLong(false);
        clearTimeout(genStopTimerRef.current);
        // The backend only notices the cancel flag at its next per-contact checkpoint, so a
        // contact mid-generation can take a while to wind down. Relabel the button rather than
        // leaving a bare spinner that looks stuck once this stretches past a few seconds.
        genStopTimerRef.current = setTimeout(() => setGenStopTakingLong(true), 8000);

        const postCancel = () =>
            apiFetch(`/api/campaign-files/${encodeURIComponent(wizardUpload.fileId)}/generation/cancel`, {
                method: 'POST',
            });
        try {
            let res = await postCancel();
            if (!res.ok) {
                // One retry for a transient failure before giving up — a silently-failed cancel
                // request would otherwise leave the flag unset and generation running forever
                // while the button stays stuck on "Stopping…".
                res = await postCancel();
            }
            if (!res.ok) {
                const err = await res.json().catch(() => ({}));
                throw new Error(err.detail || `Cancel request failed (${res.status})`);
            }
        } catch (e) {
            console.error(e);
            alert(e.message || 'Could not stop generation — please try again.');
            setGenStopping(false);
            setGenStopTakingLong(false);
            clearTimeout(genStopTimerRef.current);
        }
    }, [wizardUpload?.fileId]);

    const startGenerationRun = useCallback(
        ({ reset, preview = false }) => {
            if (!wizardUpload?.fileId) return;
            genRunOptionsRef.current = { reset: !!reset, preview: !!preview };
            setGenPreviewOnly(!!preview);
            setGenRunId((r) => r + 1);
            setGenRunning(true);
            if (reset) {
                setGenSequences([]);
                setGenContacts([]);
                setGenProgress(0);
                setGenComplete(false);
                setGenPhase('email');
            }
        },
        [wizardUpload?.fileId]
    );

    useEffect(() => {
        if (!genRunning || !wizardUpload?.fileId) return;

        const isNewRun = prevGenRunIdRef.current !== genRunId;
        if (isNewRun) {
            prevGenRunIdRef.current = genRunId;
            setGenFailedContacts([]);
        }

        if (eventSourceRef.current) {
            eventSourceRef.current.close();
            eventSourceRef.current = null;
        }

        const runOpts = genRunOptionsRef.current;
        const url = buildGenerateSequencesUrl(wizardUpload.fileId, {
            reset: runOpts.reset,
            preview: runOpts.preview,
            contactLimit: runOpts.preview ? 1 : null,
        });
        const es = new EventSource(url);
        eventSourceRef.current = es;

        es.onmessage = (event) => {
            try {
                const data = JSON.parse(event.data);
                if (data.type === 'sequence') {
                    const seq = data.sequence;
                    setGenSequences((prev) => {
                        const sig = `${seq.id}-${seq.emailNumber}-${seq.channel || 'email'}-${seq.stepOrder ?? ''}`;
                        if (
                            prev.some(
                                (s) =>
                                    `${s.id}-${s.emailNumber}-${s.channel || 'email'}-${s.stepOrder ?? ''}` === sig
                            )
                        ) {
                            return prev;
                        }
                        return [...prev, seq];
                    });
                    setGenContacts((prev) => mergeSequenceIntoContacts(prev, seq));
                } else if (data.type === 'progress' && typeof data.progress === 'number') {
                    setGenProgress(data.progress);
                } else if (data.type === 'phase' && data.phase === 'linkedin') {
                    setGenPhase('linkedin');
                } else if (data.type === 'contact_error') {
                    setGenFailedContacts((prev) => [
                        ...prev,
                        {
                            email: data.email || '',
                            name: data.name || '',
                            channel: data.channel || '',
                            error: data.error || '',
                        },
                    ]);
                } else if (data.type === 'cancelled') {
                    setGenRunning(false);
                    setGenPreviewOnly(false);
                    setGenStopping(false);
                    setGenStopTakingLong(false);
                    clearTimeout(genStopTimerRef.current);
                    es.close();
                    if (eventSourceRef.current === es) eventSourceRef.current = null;
                } else if (data.type === 'preview_complete') {
                    setGenRunning(false);
                    setGenPreviewOnly(false);
                    es.close();
                    if (eventSourceRef.current === es) eventSourceRef.current = null;
                } else if (data.type === 'complete') {
                    setGenRunning(false);
                    setGenComplete(true);
                    setGenPreviewOnly(false);
                    setGenStopping(false);
                    setGenStopTakingLong(false);
                    clearTimeout(genStopTimerRef.current);
                    es.close();
                    if (eventSourceRef.current === es) eventSourceRef.current = null;
                    if (!openRef.current) {
                        reset();
                    }
                } else if (data.type === 'error') {
                    console.error(data.error);
                    alert(`Generation error: ${data.error}`);
                    setGenRunning(false);
                    setGenPreviewOnly(false);
                    setGenStopping(false);
                    setGenStopTakingLong(false);
                    clearTimeout(genStopTimerRef.current);
                    es.close();
                    if (eventSourceRef.current === es) eventSourceRef.current = null;
                    if (!openRef.current) {
                        reset();
                    }
                }
            } catch (e) {
                console.error(e);
            }
        };

        es.onerror = () => {
            es.close();
            if (eventSourceRef.current === es) eventSourceRef.current = null;
        };

        return () => {
            es.close();
            if (eventSourceRef.current === es) eventSourceRef.current = null;
        };
    }, [genRunning, wizardUpload?.fileId, genRunId, reset]);

    const pickFile = async (file) => {
        if (!file) return;
        if (!file.name.toLowerCase().endsWith('.csv')) {
            alert('Please upload a .csv file (Apollo export), same as Email / AI Generator.');
            return;
        }
        setProspectFile(file);
        setWizardUpload(null);
        setUploadingCsv(true);
        try {
            const formData = new FormData();
            formData.append('file', file);
            const response = await apiFetch('/api/upload-csv', {
                method: 'POST',
                body: formData,
            });
            if (!response.ok) {
                throw new Error('Upload failed');
            }
            const data = await response.json();
            setWizardUpload({
                fileId: data.file_id,
                contactCount: data.contact_count,
                name: file.name,
            });
        } catch (err) {
            console.error(err);
            alert('Could not upload CSV. Please try again.');
            setProspectFile(null);
            setWizardUpload(null);
        } finally {
            setUploadingCsv(false);
        }
    };

    const canContinueStep1 =
        campaignName.trim().length > 0 && !!wizardUpload?.fileId && !uploadingCsv;

    const canGenerate = useMemo(() => {
        const emailOk =
            selectedProducts.length > 0 &&
            selectedProducts.every((p) => (prompts[p.name] || '').trim());
        if (!emailOk || !wizardUpload?.fileId) return false;
        if (!sequenceHasLinkedin) return true;
        return selectedProducts.every((p) => (linkedinPrompts[p.name] || '').trim());
    }, [selectedProducts, prompts, linkedinPrompts, wizardUpload?.fileId, sequenceHasLinkedin]);

    const triggerPreviewGeneration = useCallback(async () => {
        if (!canGenerate || !wizardUpload?.fileId || genRunning) return;
        if (previewTriggeredRef.current && genContacts.length > 0) return;
        previewTriggeredRef.current = true;
        try {
            await savePromptsToServer();
            startGenerationRun({
                reset: genSequences.length === 0,
                preview: true,
            });
        } catch (e) {
            console.error(e);
            previewTriggeredRef.current = false;
        }
    }, [
        canGenerate,
        wizardUpload?.fileId,
        genRunning,
        genContacts.length,
        genSequences.length,
        savePromptsToServer,
        startGenerationRun,
    ]);

    useEffect(() => {
        if (step === 4 && canGenerate && wizardUpload?.fileId && genContacts.length === 0 && !genRunning) {
            void triggerPreviewGeneration();
        }
    }, [step, canGenerate, wizardUpload?.fileId, genContacts.length, genRunning, triggerPreviewGeneration]);

    const handleContinue = () => {
        if (step === 1 && !canContinueStep1) return;
        if (step < 4) setStep((s) => s + 1);
    };

    const handleBack = () => {
        if (step > 1) setStep((s) => s - 1);
    };

    const requestClose = () => {
        const committed = promptEditorRef.current?.commitCampaignPrompts?.() ?? null;
        const mergedPrompts =
            committed && typeof committed === 'object' && committed.prompts
                ? committed.prompts
                : prompts;
        const mergedLinkedin =
            committed && typeof committed === 'object' && committed.linkedinPrompts
                ? committed.linkedinPrompts
                : linkedinPrompts;
        const payload = {
            id: initialCampaign?.id,
            name: campaignName.trim() || 'Untitled campaign',
            contacts: wizardUpload?.contactCount ?? estimatedContacts ?? 0,
            prospectFileName: wizardUpload?.name || prospectFile?.name || '',
            fileId: wizardUpload?.fileId || null,
            sequence: sequenceSteps,
            parallelTracks,
            selectedProducts,
            generationComplete: genComplete,
            generationProgressPercent: Math.min(100, Math.round(genProgress || 0)),
            wizardStep: step,
            wizardPrompts: mergedPrompts,
            wizardLinkedinPrompts: mergedLinkedin,
        };
        if (onDraftPersist && (payload.fileId || payload.id)) {
            onDraftPersist(payload);
        }
        onOpenChange(false);
    };

    const handleGenerate = async () => {
        if (!canGenerate) {
            alert('Select products and fill all prompt templates before generating.');
            return;
        }
        try {
            await savePromptsToServer();
        } catch (e) {
            console.error(e);
            alert('Failed to save prompts. Please try again.');
            return;
        }
        previewTriggeredRef.current = true;
        startGenerationRun({ reset: true, preview: false });
    };

    const handleLaunch = async () => {
        if (!onComplete) {
            requestClose();
            return;
        }
        try {
            if (canGenerate && wizardUpload?.fileId) {
                await savePromptsToServer();
            }
        } catch (e) {
            console.error(e);
            alert('Failed to save campaign settings. Please try again.');
            return;
        }

        const hasPartial = genSequences.length > 0 && !genComplete;
        const needsBackgroundGen = !genComplete;

        onComplete({
            campaignId: initialCampaign?.id ?? null,
            name: campaignName.trim(),
            contacts: wizardUpload?.contactCount || estimatedContacts || 0,
            prospectFileName: wizardUpload?.name || prospectFile?.name || '',
            fileId: wizardUpload?.fileId || null,
            sequence: sequenceSteps,
            parallelTracks,
            selectedProducts,
            generationComplete: genComplete,
            generationProgressPercent: Math.min(100, Math.round(genProgress || 0)),
            startBackgroundGeneration: needsBackgroundGen,
            resumeGeneration: hasPartial,
        });
        onOpenChange(false);
    };

    useEffect(() => {
        if (!open) return;
        const onKey = (e) => {
            if (e.key === 'Escape') requestClose();
        };
        window.addEventListener('keydown', onKey);
        return () => window.removeEventListener('keydown', onKey);
    }, [open, requestClose]);

    if (!open) return null;

    const modal = (
        <div
            className="fixed inset-0 z-[100] flex items-center justify-center p-4 sm:p-6"
            role="dialog"
            aria-modal="true"
            aria-labelledby="create-campaign-title"
        >
            <button
                type="button"
                className="absolute inset-0 bg-slate-900/40 backdrop-blur-[2px]"
                aria-label="Close"
                onClick={() => requestClose()}
            />
            <div
                className={cn(
                    'relative z-[101] flex max-h-[min(92vh,900px)] w-full flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl shadow-violet-200/30',
                    step === 2 || step === 3 ? 'max-w-4xl' : 'max-w-3xl'
                )}
            >
                <div className="flex items-center justify-between border-b border-slate-100 px-5 py-4">
                    <h2 id="create-campaign-title" className="text-lg font-semibold text-slate-900">
                        Create Campaign
                    </h2>
                    <button
                        type="button"
                        onClick={() => requestClose()}
                        className="rounded-lg p-2 text-slate-400 transition hover:bg-slate-100 hover:text-slate-700"
                    >
                        <X className="h-5 w-5" />
                    </button>
                </div>

                <div className="border-b border-slate-100 bg-slate-50/80 px-4 py-4 sm:px-6">
                    <div className="flex flex-wrap items-start justify-between gap-4">
                        {STEPS.map((s) => {
                            const active = step === s.id;
                            const done = step > s.id;
                            return (
                                <div key={s.id} className="flex min-w-[120px] flex-1 flex-col items-center gap-2">
                                    <div
                                        className={cn(
                                            'flex h-10 w-10 items-center justify-center rounded-full text-sm font-semibold transition',
                                            active &&
                                                'bg-violet-600 text-white ring-4 ring-violet-100',
                                            done && !active && 'bg-violet-100 text-violet-800',
                                            !active && !done && 'border-2 border-slate-200 bg-white text-slate-400'
                                        )}
                                    >
                                        {s.id}
                                    </div>
                                    <span
                                        className={cn(
                                            'text-center text-xs font-medium sm:text-sm',
                                            active ? 'text-violet-700' : 'text-slate-500'
                                        )}
                                    >
                                        {s.label}
                                    </span>
                                </div>
                            );
                        })}
                    </div>
                </div>

                <div className="min-h-0 flex-1 overflow-y-auto px-5 py-6 sm:px-8">
                    {step === 1 ? (
                        <div className="space-y-6">
                            <div>
                                <span className="inline-flex rounded-md bg-slate-100 px-2 py-0.5 text-[10px] font-medium uppercase tracking-wide text-slate-500">
                                    Step 1
                                </span>
                            </div>
                            <div>
                                <label className="mb-1.5 block text-sm font-medium text-slate-800">
                                    Campaign Name
                                </label>
                                <Input
                                    placeholder="e.g., Q4 Enterprise Tech Outreach"
                                    value={campaignName}
                                    onChange={(e) => setCampaignName(e.target.value)}
                                    className="max-w-lg"
                                />
                            </div>
                            <div>
                                <label className="mb-1.5 block text-sm font-medium text-slate-800">
                                    Prospect List (Apollo CSV)
                                </label>
                                <div
                                    className={cn(
                                        'relative flex min-h-[200px] cursor-pointer flex-col items-center justify-center rounded-xl border-2 border-dashed px-4 py-8 transition',
                                        dragOver
                                            ? 'border-violet-400 bg-violet-50/50'
                                            : 'border-slate-200 bg-slate-50/50 hover:border-violet-300'
                                    )}
                                    onDragOver={(e) => {
                                        e.preventDefault();
                                        setDragOver(true);
                                    }}
                                    onDragLeave={() => setDragOver(false)}
                                    onDrop={(e) => {
                                        e.preventDefault();
                                        setDragOver(false);
                                        const f = e.dataTransfer.files?.[0];
                                        pickFile(f);
                                    }}
                                    onClick={() => !uploadingCsv && document.getElementById('wizard-csv-input')?.click()}
                                >
                                    <input
                                        id="wizard-csv-input"
                                        type="file"
                                        accept=".csv"
                                        className="hidden"
                                        onChange={(e) => pickFile(e.target.files?.[0])}
                                    />
                                    <div className="flex h-12 w-12 items-center justify-center rounded-full bg-violet-100 text-violet-600">
                                        <Upload className="h-6 w-6" />
                                    </div>
                                    <p className="mt-3 text-center text-sm font-semibold text-slate-800">
                                        Drag and drop your CSV here
                                    </p>
                                    <Button
                                        type="button"
                                        variant="outline"
                                        className="mt-4"
                                        disabled={uploadingCsv}
                                        onClick={(e) => {
                                            e.stopPropagation();
                                            document.getElementById('wizard-csv-input')?.click();
                                        }}
                                    >
                                        Browse Files
                                    </Button>
                                    {uploadingCsv ? (
                                        <p className="mt-3 text-xs font-medium text-violet-700">Uploading…</p>
                                    ) : wizardUpload ? (
                                        <p className="mt-3 text-xs font-medium text-violet-700">
                                            {wizardUpload.name}
                                            {wizardUpload.contactCount
                                                ? ` · ${Number(wizardUpload.contactCount).toLocaleString()} contacts`
                                                : estimatedContacts > 0
                                                  ? ` · ~${estimatedContacts.toLocaleString()} rows`
                                                  : ''}
                                        </p>
                                    ) : prospectFile ? (
                                        <p className="mt-3 text-xs text-amber-700">Upload failed — try another file.</p>
                                    ) : null}
                                </div>
                            </div>
                        </div>
                    ) : step === 2 ? (
                        <CampaignSequenceBuilder
                            value={sequenceSteps}
                            onChange={setSequenceSteps}
                            parallelTracks={parallelTracks}
                            onParallelTracksChange={setParallelTracks}
                            linkedinDefaults={linkedinDefaults}
                            mailboxDefaults={mailboxDefaults}
                            emailSendingSettings={emailSendingSettings}
                            onEmailSendingSettingsChange={setEmailSendingSettings}
                        />
                    ) : step === 3 ? (
                        <div className="space-y-8">
                            <ProductSelector
                                selectedProducts={selectedProducts}
                                onProductsChange={setSelectedProducts}
                            />
                            {selectedProducts.length > 0 ? (
                                <>
                                    {!genRunning && (!genComplete || genFailedContacts.length > 0) ? (
                                        <div className="rounded-xl border-2 border-violet-300 bg-gradient-to-br from-violet-50 via-white to-purple-50 p-5 shadow-sm shadow-violet-100/80">
                                            <div className="flex flex-col gap-4 sm:flex-row sm:items-center sm:justify-between">
                                                <div>
                                                    <p className="text-base font-semibold text-slate-900">
                                                        {genFailedContacts.length > 0
                                                            ? 'Retry failed contacts'
                                                            : 'Generate personalized content'}
                                                    </p>
                                                    <p className="mt-1 max-w-xl text-sm text-slate-600">
                                                        {genFailedContacts.length > 0 ? (
                                                            <>
                                                                Some contacts failed to generate. Click{' '}
                                                                <strong className="font-semibold text-violet-800">
                                                                    Retry generation
                                                                </strong>{' '}
                                                                to regenerate content for all contacts.
                                                            </>
                                                        ) : (
                                                            <>
                                                                Click <strong className="font-semibold text-violet-800">Generate</strong>{' '}
                                                                to create emails and LinkedIn copy for all contacts. You can also skip
                                                                this and continue — we&apos;ll auto-preview the first contact on the
                                                                next step.
                                                            </>
                                                        )}
                                                    </p>
                                                </div>
                                                <Button
                                                    type="button"
                                                    size="lg"
                                                    disabled={!canGenerate}
                                                    className="h-12 shrink-0 bg-gradient-to-r from-violet-600 to-purple-600 px-8 text-base font-semibold shadow-md shadow-violet-200 hover:from-violet-700 hover:to-purple-700"
                                                    onClick={handleGenerate}
                                                >
                                                    <Sparkles className="mr-2 h-5 w-5" />
                                                    {genFailedContacts.length > 0 ? 'Retry generation' : 'Generate all contacts'}
                                                </Button>
                                            </div>
                                        </div>
                                    ) : null}
                                    <PromptEditor
                                        ref={promptEditorRef}
                                        selectedProducts={selectedProducts}
                                        prompts={prompts}
                                        onPromptsChange={setPrompts}
                                        variant="campaign"
                                        includeLinkedinInCampaign={sequenceHasLinkedin}
                                        linkedinPrompts={linkedinPrompts}
                                        onLinkedinPromptsChange={setLinkedinPrompts}
                                    />
                                    {genRunning ? (
                                        <div className="flex flex-wrap items-center justify-between gap-2 rounded-lg border border-violet-200 bg-violet-50/80 px-4 py-3 text-sm text-violet-900">
                                            <span className="flex items-center gap-2">
                                                <Loader2 className="h-4 w-4 shrink-0 animate-spin" />
                                                Generating in the background — you can continue to Review &amp; Launch anytime.
                                            </span>
                                            <Button
                                                type="button"
                                                size="sm"
                                                variant="outline"
                                                className="shrink-0 border-violet-300 bg-white text-violet-800 hover:bg-violet-100"
                                                disabled={genStopping}
                                                onClick={stopGeneration}
                                            >
                                                {genStopping ? (
                                                    <>
                                                        <Loader2 className="mr-1.5 h-3.5 w-3.5 animate-spin" />
                                                        {genStopTakingLong ? 'Finishing current contact…' : 'Stopping…'}
                                                    </>
                                                ) : (
                                                    'Stop generation'
                                                )}
                                            </Button>
                                        </div>
                                    ) : genComplete && genFailedContacts.length === 0 ? (
                                        <div className="flex items-center gap-2 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-800">
                                            <CheckCircle2 className="h-4 w-4 shrink-0" />
                                            All contact content generated. Continue to review and launch.
                                        </div>
                                    ) : null}
                                    {genFailedContacts.length > 0 ? (
                                        <div className="rounded-lg border border-amber-200 bg-amber-50 px-4 py-3 text-sm text-amber-900">
                                            <p className="font-medium">
                                                {genFailedContacts.length} contact{genFailedContacts.length === 1 ? '' : 's'} failed
                                                to generate — retry generation to fill in the rest.
                                            </p>
                                            <ul className="mt-1.5 max-h-24 space-y-0.5 overflow-y-auto text-xs text-amber-800">
                                                {genFailedContacts.slice(0, 10).map((f, i) => (
                                                    <li key={`${f.email || f.name}-${i}`}>
                                                        {f.email || f.name || 'Unknown contact'}
                                                        {f.channel ? ` (${f.channel})` : ''}
                                                        {f.error ? `: ${f.error}` : ''}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    ) : null}
                                    <WizardSequencePreview
                                        contacts={genContacts}
                                        sequences={genSequences}
                                        isGenerating={genRunning}
                                        generationComplete={genComplete}
                                        generationStarted={genRunId > 0 || genSequences.length > 0}
                                        progress={genProgress}
                                        contactCount={wizardUpload?.contactCount}
                                        selectedProducts={selectedProducts}
                                        sequenceHasLinkedin={sequenceHasLinkedin}
                                        genPhase={genPhase}
                                        hasFailures={genFailedContacts.length > 0}
                                    />
                                </>
                            ) : (
                                <p className="text-sm text-slate-500">Select at least one product to edit prompts.</p>
                            )}
                        </div>
                    ) : (
                        <div className="space-y-6">
                            <div className="rounded-xl border border-slate-200 bg-white p-4 shadow-sm">
                                <p className="text-sm font-medium text-slate-800">Sequence</p>
                                <ReviewSequenceTimeline steps={sequenceSteps} parallelTracks={parallelTracks} />
                            </div>
                            <div>
                                <p className="mb-2 text-sm font-medium text-slate-800">Sample preview (first contact)</p>
                                {genRunning && !genContacts[0] ? (
                                    <div className="rounded-xl border border-violet-200 bg-violet-50/50 px-4 py-10 text-center">
                                        <Loader2 className="mx-auto h-8 w-8 animate-spin text-violet-600" />
                                        <p className="mt-3 text-sm font-medium text-slate-700">
                                            Generating preview for your first contact…
                                        </p>
                                    </div>
                                ) : genContacts[0] ? (
                                    <SequenceCard contact={genContacts[0]} index={0} />
                                ) : (
                                    <div className="rounded-xl border border-dashed border-slate-200 bg-slate-50/80 px-4 py-10 text-center text-sm text-slate-600">
                                        Preview will appear here shortly. You can still launch — remaining contacts
                                        generate in the background on the dashboard.
                                    </div>
                                )}
                            </div>
                            {(genRunning || (!genComplete && genSequences.length > 0)) ? (
                                <div className="rounded-xl border border-violet-200 bg-white p-4 shadow-sm">
                                    <div className="mb-2 flex items-center justify-between text-sm">
                                        <span className="font-medium text-slate-800">
                                            {genComplete
                                                ? 'Content generation complete'
                                                : genPreviewOnly
                                                  ? 'Generating preview…'
                                                  : 'Generating all contacts…'}
                                        </span>
                                        <span className="font-semibold text-violet-700">
                                            {Math.min(100, Math.round(genProgress || 0))}%
                                        </span>
                                    </div>
                                    <Progress value={genProgress} className="h-2" />
                                    {!genComplete ? (
                                        <p className="mt-2 text-xs text-slate-500">
                                            Launch now — generation continues on the dashboard. Sending starts automatically
                                            when every contact is ready.
                                        </p>
                                    ) : null}
                                </div>
                            ) : null}
                            {!genRunning && genFailedContacts.length > 0 ? (
                                <div className="rounded-xl border border-amber-200 bg-amber-50 p-4 text-sm text-amber-900">
                                    <p className="font-medium">
                                        {genFailedContacts.length} contact{genFailedContacts.length === 1 ? '' : 's'} failed to
                                        generate content and will not have a sequence unless you go back and retry generation.
                                    </p>
                                </div>
                            ) : null}
                            <div className="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-slate-100 bg-slate-50/80 px-4 py-3 text-sm text-slate-700">
                                <div>
                                    <span className="font-semibold text-slate-900">{campaignName || 'Campaign'}</span>
                                    <span className="mx-2 text-slate-300">·</span>
                                    <span>
                                        {(wizardUpload?.contactCount ?? estimatedContacts ?? 0).toLocaleString()}{' '}
                                        prospects
                                    </span>
                                    {(wizardUpload?.name || prospectFile?.name) && (
                                        <>
                                            <span className="mx-2 text-slate-300">·</span>
                                            <span className="text-slate-600">
                                                {wizardUpload?.name || prospectFile?.name}
                                            </span>
                                        </>
                                    )}
                                </div>
                                {genRunning || (genSequences.length > 0 && !genComplete) ? (
                                    <span className="text-xs font-medium text-violet-700">
                                        Content generation {genComplete ? 'complete' : 'in progress'}
                                    </span>
                                ) : null}
                            </div>
                        </div>
                    )}
                </div>

                <div className="flex flex-wrap items-center justify-end gap-2 border-t border-slate-100 bg-white px-5 py-4 sm:px-8">
                    {step === 4 ? (
                        <Button
                            type="button"
                            className="bg-violet-600 text-white hover:bg-violet-700"
                            onClick={() => void handleLaunch()}
                        >
                            {genComplete ? 'Launch campaign' : 'Launch & finish generating'}
                        </Button>
                    ) : null}
                    {step > 1 ? (
                        <Button type="button" variant="outline" onClick={handleBack}>
                            <ArrowLeft className="mr-2 h-4 w-4" />
                            Back
                        </Button>
                    ) : null}
                    {step < 4 ? (
                        <Button
                            type="button"
                            disabled={step === 1 && !canContinueStep1}
                            className="bg-violet-600 text-white hover:bg-violet-700 disabled:opacity-40"
                            onClick={handleContinue}
                        >
                            {step === 1
                                ? 'Continue to Sequence'
                                : step === 3
                                  ? 'Continue to Review (auto-preview first contact)'
                                  : `Continue to ${STEPS[step]?.label ?? 'next'}`}
                            <ArrowRight className="ml-2 h-4 w-4" />
                        </Button>
                    ) : null}
                </div>
            </div>
        </div>
    );

    return typeof document !== 'undefined' ? createPortal(modal, document.body) : null;
}