File size: 67,449 Bytes
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
 
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
5fa54cc
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
 
 
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
5fa54cc
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
 
 
 
 
 
5fa54cc
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
 
 
5fa54cc
 
 
 
 
b366dd7
 
 
 
5fa54cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
5fa54cc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b366dd7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
import React, { useState, useRef, useEffect, useCallback } from 'react';
import {
  Box,
  Typography,
  Card,
  CardContent,
  CircularProgress,
  Chip,
  IconButton,
  Divider,
  Alert,
  LinearProgress,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  Tooltip,
  Button,
  Accordion,
  AccordionSummary,
  AccordionDetails,
  TextField,
  Avatar,
  InputAdornment,
  Paper,
} from '@mui/material';
import {
  ExpandMore as ExpandMoreIcon,
  Refresh as RefreshIcon,
  Code as CodeIcon,
  UnfoldMore as ExpandAllIcon,
  UnfoldLess as CollapseAllIcon,
  ContentCopy as CopyIcon,
  Download as DownloadIcon,
  PlayArrow as EnableScrollIcon,
  Pause as DisableScrollIcon,
  Send as SendIcon,
  SmartToy as BotIcon,
  Person as PersonIcon,
} from '@mui/icons-material';
import {
  API_BASE_URI,
  WEBSOCKET_BASE_URI
} from '../constants';

interface ProcessingMessage {
  type?: string;
  message: string;
  progress_percentage?: number;
  request_id?: string;
  timestamp: string;
  stats?: {
    status: string;
    number_of_records: number;
    request_id: string;
    record_count: number;
  };
  error?: string;
  isUser?: boolean;
}

interface PreviewItem {
  id: string;
  type: 'json' | 'curl' | 'pdf';
  content: string;
  timestamp: string;
  isMinified: boolean;
  pdfUrl?: string;
  filename?: string;
}

interface ProcessingStatusProps {
  fileType: 'Shell' | 'MSAG' | 'Dx Supplementary';
  folderPath: string;
  environment: string;
  inputType: 'file' | 'json';
  json_content?: string;
  isLoading: boolean;
  onLoadingChange: (loading: boolean) => void;
  onStatusChange: (status: 'idle' | 'loading' | 'success' | 'error') => void;
  triggerProcessing?: boolean;
  onProcessingComplete?: () => void;
}

// TypewriterText component for typewriting animation
const TypewriterText: React.FC<{
  text: string;
  speed?: number;
  onComplete?: () => void;
  isJson?: boolean;
  isCurl?: boolean;
  onJsonClick?: () => void;
  onCurlClick?: () => void;
}> = ({ text, speed = 20, onComplete, isJson = false, isCurl = false, onJsonClick, onCurlClick }) => {
  const [displayText, setDisplayText] = useState('');
  const [isComplete, setIsComplete] = useState(false);
  
  // Check if this is a Phase or Step heading
  const isPhaseHeading = text.startsWith("Phase: ");
  const isStepHeading = text.startsWith("Step: ");
  
  useEffect(() => {
    if (text.length === 0) {
      setIsComplete(true);
      onComplete?.();
      return;
    }

    let index = 0;
    const timer = setInterval(() => {
      if (index < text.length) {
        setDisplayText(text.slice(0, index + 1));
        index++;
      } else {
        setIsComplete(true);
        onComplete?.();
        clearInterval(timer);
      }
    }, speed);

    return () => clearInterval(timer);
  }, [text, speed, onComplete]);

  if (isJson) {
    const preview = displayText.length > 50 ? displayText.substring(0, 50) + '...' : displayText;
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Typography variant="body2" sx={{ flex: 1 }}>
          JSON: {preview}
        </Typography>
        {isComplete && (
          <Tooltip title="View JSON">
            <IconButton
              size="small"
              onClick={onJsonClick}
              sx={{ 
                color: 'primary.main',
                '&:hover': {
                  backgroundColor: 'primary.light',
                  color: 'primary.contrastText',
                }
              }}
            >
              <CodeIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        )}
      </Box>
    );
  }

  if (isCurl) {
    const preview = displayText.length > 50 ? displayText.substring(0, 50) + '...' : displayText;
    return (
      <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
        <Typography variant="body2" sx={{ flex: 1 }}>
          CURL: {preview}
        </Typography>
        {isComplete && (
          <Tooltip title="View CURL Command">
            <IconButton
              size="small"
              onClick={onCurlClick}
              sx={{ 
                color: 'warning.main',
                '&:hover': {
                  backgroundColor: 'warning.light',
                  color: 'warning.contrastText',
                }
              }}
            >
              <CodeIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        )}
      </Box>
    );
  }

  // Render Phase headings with H1 styling during animation
  if (isPhaseHeading) {
    return (
      <Typography 
        variant="h6" 
        sx={{ 
          fontWeight: 700,
          color: 'primary.main',
          fontSize: '1.1rem',
          mt: 1,
          mb: 0.5,
          borderBottom: '2px solid',
          borderColor: 'primary.main',
          paddingBottom: 0.5,
          textTransform: 'uppercase',
          letterSpacing: '0.5px'
        }}
      >
        {displayText.replace(/^Phase:\s*/, '')}
        {!isComplete && (
          <Box
            component="span"
            sx={{
              display: 'inline-block',
              width: '2px',
              height: '1em',
              backgroundColor: 'primary.main',
              marginLeft: '1px',
              animation: 'blink 1s infinite',
              '@keyframes blink': {
                '0%, 50%': { opacity: 1 },
                '51%, 100%': { opacity: 0 },
              },
            }}
          />
        )}
      </Typography>
    );
  }

  // Render Step headings with sub-heading styling during animation
  if (isStepHeading) {
    return (
      <Typography 
        variant="subtitle1" 
        sx={{ 
          fontWeight: 600,
          color: 'secondary.main',
          fontSize: '0.95rem',
          mt: 0.5,
          mb: 0.25,
          paddingLeft: 2,
          borderLeft: '3px solid',
          borderColor: 'secondary.main'
        }}
      >
        {displayText.replace(/^Step:\s*/, '')}
        {!isComplete && (
          <Box
            component="span"
            sx={{
              display: 'inline-block',
              width: '2px',
              height: '1em',
              backgroundColor: 'secondary.main',
              marginLeft: '1px',
              animation: 'blink 1s infinite',
              '@keyframes blink': {
                '0%, 50%': { opacity: 1 },
                '51%, 100%': { opacity: 0 },
              },
            }}
          />
        )}
      </Typography>
    );
  }

  return (
    <Typography variant="body2">
      {displayText}
      {!isComplete && (
        <Box
          component="span"
          sx={{
            display: 'inline-block',
            width: '2px',
            height: '1em',
            backgroundColor: 'primary.main',
            marginLeft: '1px',
            animation: 'blink 1s infinite',
            '@keyframes blink': {
              '0%, 50%': { opacity: 1 },
              '51%, 100%': { opacity: 0 },
            },
          }}
        />
      )}
    </Typography>
  );
};

const ProcessingStatus: React.FC<ProcessingStatusProps> = ({ 
  fileType, 
  folderPath, 
  environment, 
  inputType,
  json_content,
  isLoading, 
  onLoadingChange, 
  onStatusChange, 
  triggerProcessing,
  onProcessingComplete 
}) => {
  const [loadStatus, setLoadStatus] = useState<'idle' | 'loading' | 'success' | 'error'>('idle');
  const [accordionExpanded, setAccordionExpanded] = useState(true);
  const [processingMessages, setProcessingMessages] = useState<ProcessingMessage[]>([]);
  const [currentProgress, setCurrentProgress] = useState(0);
  const [finalStats, setFinalStats] = useState<ProcessingMessage['stats'] | null>(null);
  const [connectionError, setConnectionError] = useState<string | null>(null);
  const [isConnecting, setIsConnecting] = useState(false);
  const [hasConnected, setHasConnected] = useState(false);
  const wsRef = useRef<WebSocket | null>(null);
  
  // Refs for autoscroll functionality - target the scrollable Box containers
  const loadingLogRef = useRef<HTMLDivElement | null>(null);
  const completeLogRef = useRef<HTMLDivElement | null>(null);
  const errorLogRef = useRef<HTMLDivElement | null>(null);
  
  // JSON Dialog state
  const [jsonDialogOpen, setJsonDialogOpen] = useState(false);
  const [selectedJsonContent, setSelectedJsonContent] = useState<string>('');
  const [isJsonExpanded, setIsJsonExpanded] = useState(true);
  
  // Curl Dialog state
  const [curlDialogOpen, setCurlDialogOpen] = useState(false);
  const [selectedCurlContent, setSelectedCurlContent] = useState<string>('');
  const [isCurlExpanded, setIsCurlExpanded] = useState(true);
  
  // Download state
  const [isDownloading, setIsDownloading] = useState(false);

  // State for typewriting animation
  const [completedMessages, setCompletedMessages] = useState<Set<number>>(new Set());

  // State for delayed progress and completion updates
  const [pendingProgressUpdate, setPendingProgressUpdate] = useState<number | null>(null);
  const [pendingCompletionData, setPendingCompletionData] = useState<{
    stats: ProcessingMessage['stats'];
    progress: number;
  } | null>(null);

  // State to track current phase and step
  const [currentPhase, setCurrentPhase] = useState<string>('');
  const [currentStep, setCurrentStep] = useState<string>('');

  // State for auto-scroll functionality
  const [autoScrollEnabled, setAutoScrollEnabled] = useState<boolean>(true);

  // Ref for the main scrollable container
  const mainContainerRef = useRef<HTMLDivElement | null>(null);

  // State for preview items (JSON/CURL/PDF)
  const [previewItems, setPreviewItems] = useState<PreviewItem[]>([]);
  const [activePreviewId, setActivePreviewId] = useState<string | null>(null);

  // State for customized processing tooltip
  const [processingTooltip, setProcessingTooltip] = useState<'Processing' | 'Thinking' | 'Validating'>('Processing');
  const [isThinkingMode, setIsThinkingMode] = useState(false);
  const [isValidatingMode, setIsValidatingMode] = useState(false);

  // Chat interface state
  const [userInput, setUserInput] = useState('');
  const [hasUserInteracted, setHasUserInteracted] = useState(false);
  const [isInputDisabled, setIsInputDisabled] = useState(false);

  // State for JSON delay timer
  const [jsonDelayTimer, setJsonDelayTimer] = useState<NodeJS.Timeout | null>(null);

  // Helper function to add preview item (moved before loadPdfPreview)
  const addPreviewItem = useCallback((type: 'json' | 'curl' | 'pdf', content: string, pdfUrl?: string, filename?: string) => {
    const newItem: PreviewItem = {
      id: `${type}-${Date.now()}-${Math.random()}`,
      type,
      content,
      timestamp: new Date().toLocaleTimeString(),
      isMinified: false,
      pdfUrl,
      filename
    };

    setPreviewItems(prev => {
      // Minify all existing items and add new item at the beginning (top)
      const minifiedItems = prev.map(item => ({ ...item, isMinified: true }));
      return [newItem, ...minifiedItems];
    });

    setActivePreviewId(newItem.id);
  }, []);

  // Function to load PDF from API endpoint (moved before useEffect)
  const loadPdfPreview = useCallback(async (filename: string) => {
    try {
      const response = await fetch(`http://localhost:3000/${filename}`);
      
      if (!response.ok) {
        console.error(`Failed to load PDF: ${response.statusText}`);
        return;
      }

      // Create blob URL for PDF preview
      const blob = await response.blob();
      const pdfUrl = window.URL.createObjectURL(blob);
      
      // Add PDF to preview items
      addPreviewItem('pdf', filename, pdfUrl, filename);
      
    } catch (error) {
      console.error('PDF loading failed:', error);
    }
  }, [addPreviewItem]);

  // Effect to handle processing trigger - allow reconnection for new processing requests
  useEffect(() => {
    // Only connect if trigger is true, we're not already connecting, AND user has interacted (typed input)
    if (!triggerProcessing || isConnecting || !hasUserInteracted) {
      return;
    }

    // Validate required parameters
    if (!environment || (inputType === 'file' && !folderPath)) {
      console.warn('Missing required parameters for WebSocket connection');
      return;
    }

    const connectWebSocket = () => {
      // Close any existing connection first
      if (wsRef.current) {
        wsRef.current.close();
        wsRef.current = null;
      }

      setIsConnecting(true);
      
      try {
        const ws = new WebSocket(`${WEBSOCKET_BASE_URI}/ws`);
        wsRef.current = ws;

        ws.onopen = () => {
          console.log('WebSocket connected');
          setConnectionError(null);
          setHasConnected(true);
          setIsConnecting(false);
          
          // Send the initial processing request with input_type, environment and filetype
          const request = {
            input_type: inputType,
            environment: environment,
            filetype: fileType,
            ...(inputType === 'file' && { foldername: folderPath })
          };
          ws.send(JSON.stringify(request));
          
          // If input type is json, send the json content as a separate message
          if (inputType === 'json' && json_content) {
            ws.send(JSON.stringify({ json: json_content }));
          }
        };

        ws.onmessage = (event) => {
          try {
            const data: ProcessingMessage = JSON.parse(event.data);
            
            if (data.error) {
              setConnectionError(data.error);
              setLoadStatus('error');
              onLoadingChange(false);
              onStatusChange('error');
              return;
            }

            // Check for Display messages and load PDF preview
            if (isDisplayMessage(data.message)) {
              const filename = extractFilename(data.message);
              loadPdfPreview(filename);
              // Don't add Display messages to the processing messages log
              return;
            }

            // Special handling for JSON messages during "Thinking" mode
            if (isThinkingMode && isValidJSON(data.message)) {
              // Clear any existing timer
              if (jsonDelayTimer) {
                clearTimeout(jsonDelayTimer);
              }
              
              // Set a 1.5 second delay before displaying the message and changing tooltip
              const timer = setTimeout(() => {
                // Add the delayed message to processing messages
                setProcessingMessages(prev => [...prev, data]);
                
                // Change tooltip from "Thinking" to "Processing"
                setIsThinkingMode(false);
                setProcessingTooltip('Processing');
                
                // Clear the timer
                setJsonDelayTimer(null);
                
                // Handle progress updates
                if (data.progress_percentage !== undefined) {
                  setPendingProgressUpdate(data.progress_percentage);
                }
              }, 1500); // 1.5 seconds delay
              
              setJsonDelayTimer(timer);
              return; // Don't process this message immediately
            }

            // Track current phase and step from messages
            if (data.message.startsWith("Phase: ")) {
              setCurrentPhase(data.message.replace(/^Phase:\s*/, ''));
              setCurrentStep(''); // Reset step when new phase starts
            } else if (data.message.startsWith("Step: ")) {
              setCurrentStep(data.message.replace(/^Step:\s*/, ''));
            }

            // Add message to processing messages (normal flow)
            setProcessingMessages(prev => [...prev, data]);

            // Store progress updates for later application (don't apply immediately)
            if (data.progress_percentage !== undefined) {
              setPendingProgressUpdate(data.progress_percentage);
            }

            // Store completion data ONLY for very specific final completion indicators
            if (data.type === 'completion' && data.stats) {
              // This is an explicit completion message with stats from the server
              setPendingCompletionData({
                stats: data.stats,
                progress: 100
              });
            } else if (data.message.toLowerCase().trim() === 'data processing completed' ||
                       (data.message.toLowerCase().includes('data processing completed') && 
                        !data.message.toLowerCase().includes('step') && 
                        !data.message.toLowerCase().includes('phase') &&
                        data.message.length < 50)) { // Ensure it's a short final message, not a detailed step
              
              // Only trigger on the final summary "Data processing Completed" message
              let recordCount = 0;
              const recordMatch = data.message.match(/(\d+)\s+records?\s+found/i);
              if (recordMatch) {
                recordCount = parseInt(recordMatch[1]);
              }

              const stats = {
                status: 'Complete',
                number_of_records: recordCount,
                record_count: recordCount,
                request_id: Date.now().toString()
              };

              setPendingCompletionData({
                stats: stats,
                progress: 100
              });
            }
          } catch (error) {
            console.error('Error parsing WebSocket message:', error);
            setConnectionError('Failed to parse server response');
            setLoadStatus('error');
            onLoadingChange(false);
            onStatusChange('error');
          }
        };

        ws.onerror = (error) => {
          console.error('WebSocket error:', error);
          setConnectionError('Failed to connect to processing server. Make sure the backend is running on port 8000.');
          setLoadStatus('error');
          setIsConnecting(false);
          onLoadingChange(false);
          onStatusChange('error');
        };

        ws.onclose = () => {
          console.log('WebSocket disconnected');
          wsRef.current = null;
          setIsConnecting(false);
        };
      } catch (error) {
        console.error('Failed to create WebSocket connection:', error);
        setConnectionError('Failed to initialize WebSocket connection');
        setLoadStatus('error');
        setIsConnecting(false);
        onLoadingChange(false);
        onStatusChange('error');
      }
    };

    // Initialize processing state
    setLoadStatus('loading');
    setAccordionExpanded(true);
    setProcessingMessages([]);
    setCurrentProgress(0);
    setFinalStats(null);
    setConnectionError(null);
    setCompletedMessages(new Set());
    setCurrentPhase('');
    setCurrentStep('');
    setHasConnected(false);  // Reset connection state for new processing session
    onLoadingChange(true);
    onStatusChange('loading');

    // Start the connection
    connectWebSocket();
    
  }, [triggerProcessing, isConnecting, hasConnected, environment, inputType, folderPath, json_content, fileType, onLoadingChange, onStatusChange, isThinkingMode, jsonDelayTimer, loadPdfPreview, hasUserInteracted]); // Include necessary dependencies

  // Cleanup WebSocket on component unmount
  useEffect(() => {
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
      // Clear any pending JSON delay timer to prevent memory leaks
      if (jsonDelayTimer) {
        clearTimeout(jsonDelayTimer);
      }
    };
  }, [jsonDelayTimer]);

  // Effect to handle delayed progress and completion updates
  useEffect(() => {
    const lastMessageIndex = processingMessages.length - 1;
    const isLastMessageComplete = completedMessages.has(lastMessageIndex);
    const allMessagesComplete = processingMessages.length > 0 && 
      processingMessages.every((_, index) => completedMessages.has(index));
    
    // Only apply updates if ALL messages have completed their animations
    if (allMessagesComplete && processingMessages.length > 0) {
      // Apply pending progress update
      if (pendingProgressUpdate !== null) {
        setCurrentProgress(pendingProgressUpdate);
        setPendingProgressUpdate(null);
      }
      
      // Apply pending completion update only after ALL messages are done
      if (pendingCompletionData) {
        setFinalStats(pendingCompletionData.stats);
        setLoadStatus('success');
        onLoadingChange(false);
        onStatusChange('success');
        setCurrentProgress(pendingCompletionData.progress);
        setPendingCompletionData(null);
        onProcessingComplete?.();
      }
    } else if (isLastMessageComplete && pendingProgressUpdate !== null && !pendingCompletionData) {
      // Apply progress updates for non-completion messages immediately after they finish
      setCurrentProgress(pendingProgressUpdate);
      setPendingProgressUpdate(null);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [completedMessages, processingMessages.length, pendingProgressUpdate, pendingCompletionData, onLoadingChange, onStatusChange, onProcessingComplete]);

  // Autoscroll functionality - scroll to bottom when new messages are added
  useEffect(() => {
    if (processingMessages.length > 0 && autoScrollEnabled) {
      // Scroll individual log containers to bottom
      if (loadingLogRef.current && loadStatus === 'loading') {
        loadingLogRef.current.scrollTop = loadingLogRef.current.scrollHeight;
      }
      if (completeLogRef.current && loadStatus === 'success') {
        completeLogRef.current.scrollTop = completeLogRef.current.scrollHeight;
      }
      if (errorLogRef.current && loadStatus === 'error') {
        errorLogRef.current.scrollTop = errorLogRef.current.scrollHeight;
      }
      
      // Auto-scroll the main container to bottom to show latest content
      if (mainContainerRef.current) {
        mainContainerRef.current.scrollTop = mainContainerRef.current.scrollHeight;
      }
    }
  }, [processingMessages, loadStatus, autoScrollEnabled]);

  // Helper function to detect if a string is valid JSON
  const isValidJSON = (str: string): boolean => {
    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  };

  // Helper function to format JSON with proper indentation
  const formatJSON = (jsonString: string, indent: number = 2): string => {
    try {
      const parsed = JSON.parse(jsonString);
      return JSON.stringify(parsed, null, indent);
    } catch (e) {
      return jsonString;
    }
  };

  // Helper function to minify JSON
  const minifyJSON = (jsonString: string): string => {
    try {
      const parsed = JSON.parse(jsonString);
      return JSON.stringify(parsed);
    } catch (e) {
      return jsonString;
    }
  };

  // Helper function to detect if a string is a curl command
  const isCurlCommand = (str: string): boolean => {
    return str.trim().startsWith('curl');
  };

  // Helper function to format curl command with proper indentation
  const formatCurl = (curlString: string): string => {
    // Basic curl formatting - split on common flags and add line breaks
    return curlString
      .replace(/\s+/g, ' ') // Normalize whitespace
      .replace(/\s-([a-zA-Z])/g, ' \\\n  -$1') // Add line breaks before flags
      .replace(/\s(https?:\/\/[^\s]+)/g, ' \\\n  $1') // Add line breaks before URLs
      .replace(/\s--([a-zA-Z-]+)/g, ' \\\n  --$1') // Add line breaks before long flags
      .trim();
  };

  // Helper function to minify curl command
  const minifyCurl = (curlString: string): string => {
    return curlString.replace(/\s+/g, ' ').trim();
  };

  // Helper function to detect if a string is a Display message
  const isDisplayMessage = (str: string): boolean => {
    return str.startsWith('Display: ');
  };

  // Helper function to extract filename from Display message
  const extractFilename = (displayMessage: string): string => {
    return displayMessage.replace(/^Display:\s*/, '').trim();
  };

  // Helper function to detect JSON content
  const detectJsonContent = (text: string): string | null => {
    try {
      // Look for JSON-like patterns
      const jsonMatch = text.match(/\{[\s\S]*\}/);
      if (jsonMatch) {
        const potentialJson = jsonMatch[0];
        JSON.parse(potentialJson); // Validate it's valid JSON
        return potentialJson;
      }
    } catch (e) {
      // Not valid JSON
    }
    return null;
  };

  // Helper function to detect CURL content
  const detectCurlContent = (text: string): string | null => {
    const curlMatch = text.match(/curl\s+[\s\S]*?(?=\n\n|\n"|$)/);
    return curlMatch ? curlMatch[0] : null;
  };

  // Helper function to format JSON for preview
  const formatJsonPreview = (jsonString: string): string => {
    try {
      const parsed = JSON.parse(jsonString);
      return JSON.stringify(parsed, null, 2);
    } catch (e) {
      return jsonString;
    }
  };

  // Helper function to format CURL for preview
  const formatCurlPreview = (curlString: string): string => {
    return curlString
      .replace(/\s+--/g, ' \\\n  --')
      .replace(/\s+-([a-zA-Z])/g, ' \\\n  -$1')
      .replace(/\s+(https?:\/\/[^\s]+)/g, ' \\\n  $1')
      .trim();
  };

  // Ref for the preview container to handle auto-scroll to top
  const previewContainerRef = useRef<HTMLDivElement | null>(null);

  // Auto-scroll to top when new preview items are added
  useEffect(() => {
    if (previewItems.length > 0 && previewContainerRef.current) {
      // Scroll to top to show the latest item
      previewContainerRef.current.scrollTop = 0;
    }
  }, [previewItems.length]);

  // Function to toggle preview item minification
  const togglePreviewMinification = (id: string) => {
    setPreviewItems(prev =>
      prev.map(item =>
        item.id === id ? { ...item, isMinified: !item.isMinified } : item
      )
    );
    setActivePreviewId(id);
  };

  // Function to handle JSON dialog
  const handleOpenJsonDialog = (jsonContent: string) => {
    setSelectedJsonContent(jsonContent);
    setJsonDialogOpen(true);
    setIsJsonExpanded(true);
  };

  const handleCloseJsonDialog = () => {
    setJsonDialogOpen(false);
    setSelectedJsonContent('');
  };

  const handleCopyJson = () => {
    navigator.clipboard.writeText(selectedJsonContent);
  };

  // Function to handle curl dialog
  const handleOpenCurlDialog = (curlContent: string) => {
    setSelectedCurlContent(curlContent);
    setCurlDialogOpen(true);
    setIsCurlExpanded(true);
  };

  const handleCloseCurlDialog = () => {
    setCurlDialogOpen(false);
    setSelectedCurlContent('');
  };

  const handleCopyCurl = () => {
    navigator.clipboard.writeText(selectedCurlContent);
  };

  // Function to handle Excel download
  const handleDownload = async (requestId: string) => {
    setIsDownloading(true);
    try {
      const response = await fetch(`${API_BASE_URI}/${requestId}/download`);
      
      if (!response.ok) {
        throw new Error(`Download failed: ${response.statusText}`);
      }

      // Get the filename from the response headers or use a default
      const contentDisposition = response.headers.get('content-disposition');
      let filename = `Benefit_Agent_Report.xlsx`;
      
      if (contentDisposition) {
        const filenameMatch = contentDisposition.match(/filename="?(.+)"?/);
        if (filenameMatch) {
          filename = filenameMatch[1];
        }
      }

      // Convert response to blob and download
      const blob = await response.blob();
      const url = window.URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      document.body.appendChild(link);
      link.click();
      
      // Cleanup
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
    } catch (error) {
      console.error('Download failed:', error);
      setConnectionError(`Failed to download Excel: ${error instanceof Error ? error.message : 'Unknown error'}`);
    } finally {
      setIsDownloading(false);
    }
  };

  // Function to render message content with typewriting animation
  const renderMessageContent = (message: string, index: number) => {
    const isLastMessage = index === processingMessages.length - 1;
    const shouldAnimate = isLastMessage && loadStatus === 'loading' && !completedMessages.has(index);
    
    const handleAnimationComplete = () => {
      setCompletedMessages(prev => new Set([...Array.from(prev), index]));
      
      // After animation completes, check for JSON/CURL content
      const jsonContent = detectJsonContent(message);
      if (jsonContent) {
        addPreviewItem('json', jsonContent);
      }

      const curlContent = detectCurlContent(message);
      if (curlContent) {
        addPreviewItem('curl', curlContent);
      }
    };

    // Check if message is a Phase heading
    const isPhaseHeading = message.startsWith("Phase: ");
    // Check if message is a Step sub-heading
    const isStepHeading = message.startsWith("Step: ");

    // For non-animated messages, check for JSON/CURL content immediately
    if (!shouldAnimate && !completedMessages.has(index)) {
      const jsonContent = detectJsonContent(message);
      if (jsonContent) {
        addPreviewItem('json', jsonContent);
      }

      const curlContent = detectCurlContent(message);
      if (curlContent) {
        addPreviewItem('curl', curlContent);
      }
      
      setCompletedMessages(prev => new Set([...Array.from(prev), index]));
    }

    if (isValidJSON(message)) {
      if (shouldAnimate) {
        return (
          <TypewriterText
            text={message}
            onComplete={handleAnimationComplete}
            isJson={true}
            onJsonClick={() => handleOpenJsonDialog(message)}
          />
        );
      }
      
      // Static display for completed messages
      const preview = message.length > 50 ? message.substring(0, 50) + '...' : message;
      return (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="body2" sx={{ flex: 1 }}>
            JSON: {preview}
          </Typography>
          <Tooltip title="View JSON">
            <IconButton
              size="small"
              onClick={() => handleOpenJsonDialog(message)}
              sx={{ 
                color: 'primary.main',
                '&:hover': {
                  backgroundColor: 'primary.light',
                  color: 'primary.contrastText',
                }
              }}
            >
              <CodeIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      );
    }

    if (isCurlCommand(message)) {
      if (shouldAnimate) {
        return (
          <TypewriterText
            text={message}
            onComplete={handleAnimationComplete}
            isCurl={true}
            onCurlClick={() => handleOpenCurlDialog(message)}
          />
        );
      }

      // Static display for completed messages
      const preview = message.length > 50 ? message.substring(0, 50) + '...' : message;
      return (
        <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
          <Typography variant="body2" sx={{ flex: 1 }}>
            CURL: {preview}
          </Typography>
          <Tooltip title="View CURL Command">
            <IconButton
              size="small"
              onClick={() => handleOpenCurlDialog(message)}
              sx={{ 
                color: 'warning.main',
                '&:hover': {
                  backgroundColor: 'warning.light',
                  color: 'warning.contrastText',
                }
              }}
            >
              <CodeIcon fontSize="small" />
            </IconButton>
          </Tooltip>
        </Box>
      );
    }
    
    if (shouldAnimate) {
      return (
        <TypewriterText
          text={message}
          onComplete={handleAnimationComplete}
        />
      );
    }
    
    // Render Phase headings with H1 styling
    if (isPhaseHeading) {
      return (
        <Typography 
          variant="h6" 
          sx={{ 
            fontWeight: 700,
            color: 'primary.main',
            fontSize: '1.1rem',
            mt: 1,
            mb: 0.5,
            borderBottom: '2px solid',
            borderColor: 'primary.main',
            paddingBottom: 0.5,
            textTransform: 'uppercase',
            letterSpacing: '0.5px'
          }}
        >
          {message.replace(/^Phase:\s*/, '')}
        </Typography>
      );
    }

    // Render Step headings with sub-heading styling
    if (isStepHeading) {
      return (
        <Typography 
          variant="subtitle1" 
          sx={{ 
            fontWeight: 600,
            color: 'secondary.main',
            fontSize: '0.95rem',
            mt: 0.5,
            mb: 0.25,
            paddingLeft: 2,
            borderLeft: '3px solid',
            borderColor: 'secondary.main'
          }}
        >
          {message.replace(/^Step:\s*/, '')}
        </Typography>
      );
    }
    
    return (
      <Typography variant="body2">
        {message}
      </Typography>
    );
  };

  // Effect to monitor processing messages and update tooltip state
  useEffect(() => {
    if (processingMessages.length === 0) {
      setProcessingTooltip('Processing');
      setIsThinkingMode(false);
      setIsValidatingMode(false);
      return;
    }

    const latestMessage = processingMessages[processingMessages.length - 1];
    const messageText = latestMessage.message.toLowerCase();

    // Check for "Quality Assurance and Finalization" heading or status
    if (messageText.includes('quality assurance and finalization') || 
        messageText.includes('quality assurance') || 
        messageText.includes('finalization')) {
      setIsValidatingMode(true);
      setIsThinkingMode(false);
      setProcessingTooltip('Validating');
      return;
    }

    // If we're in validating mode, stay in validating mode until completion
    if (isValidatingMode && !messageText.includes('complete')) {
      setProcessingTooltip('Validating');
      return;
    }

    // Check for curl message - switch to "Thinking"
    if (isCurlCommand(latestMessage.message)) {
      setIsThinkingMode(true);
      setIsValidatingMode(false);
      setProcessingTooltip('Thinking');
      return;
    }

    // Check for JSON message - revert to "Processing" from "Thinking"
    if (isThinkingMode && isValidJSON(latestMessage.message)) {
      setIsThinkingMode(false);
      setProcessingTooltip('Processing');
      return;
    }

    // Default state - if not in special modes, show "Processing"
    if (!isThinkingMode && !isValidatingMode) {
      setProcessingTooltip('Processing');
    }
  }, [processingMessages, isThinkingMode, isValidatingMode]);

  const clearData = () => {
    // Close WebSocket connection if open
    if (wsRef.current) {
      wsRef.current.close();
      wsRef.current = null;  // Clear the reference
    }
    
    // Clear any pending JSON delay timer
    if (jsonDelayTimer) {
      clearTimeout(jsonDelayTimer);
      setJsonDelayTimer(null);
    }
    
    setLoadStatus('idle');
    setProcessingMessages([]);
    setCurrentProgress(0);
    setFinalStats(null);
    setConnectionError(null);
    setIsDownloading(false);
    setCompletedMessages(new Set());
    setCurrentPhase('');
    setCurrentStep('');
    setPreviewItems([]);
    setActivePreviewId(null);
    
    // Clear processing state
    setProcessingTooltip('Processing');
    setIsThinkingMode(false);
    setIsValidatingMode(false);
    
    // Reset connection state completely
    setIsConnecting(false);
    setHasConnected(false);
    
    // Reset chat state
    setHasUserInteracted(false);
    setIsInputDisabled(false);
    setUserInput('');
    
    onLoadingChange(false);
    onStatusChange('idle');
  };

  // Send chat message handler
  const handleSendMessage = () => {
    if (!userInput.trim()) return;

    // Add user message to the processing log
    const userMessage: ProcessingMessage = {
      message: userInput,
      timestamp: new Date().toLocaleTimeString(),
      isUser: true
    };

    setProcessingMessages(prev => [...prev, userMessage]);
    setHasUserInteracted(true);
    setUserInput('');
    setIsInputDisabled(true); // Disable input after sending, re-enable if reset
  };

  // Key press handler for input
  const handleInputKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  return (
    <Box sx={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Processing Status Accordion */}
      <Accordion 
        expanded={accordionExpanded} 
        onChange={() => setAccordionExpanded(!accordionExpanded)}
        sx={{ 
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          minHeight: 0,
          overflow: 'hidden',
          '& .MuiAccordionDetails-root': {
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            overflow: 'hidden',
            minHeight: 0,
            maxHeight: 'calc(100vh - 220px)'
          }
        }}
      >
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          sx={{
            backgroundColor: 'grey.50',
            '& .MuiAccordionSummary-content': {
              alignItems: 'center',
            },
          }}
        >
          <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%' }}>
            <Box sx={{ display: 'flex', alignItems: 'center' }}>
              <Typography variant="h6" sx={{ fontWeight: 600 }}>
                Processing Status
                {loadStatus === 'loading' && (
                  <Tooltip title={processingTooltip}>
                    <Chip
                      label={processingTooltip}
                      color="primary"
                      size="small"
                      sx={{ ml: 2 }}
                    />
                  </Tooltip>
                )}
                {loadStatus === 'success' && (
                  <Chip
                    label="Completed"
                    color="success"
                    size="small"
                    sx={{ ml: 2 }}
                  />
                )}
                {loadStatus === 'error' && (
                  <Chip
                    label="Error"
                    color="error"
                    size="small"
                    sx={{ ml: 2 }}
                  />
                )}
              </Typography>
            </Box>
            
            {/* Auto-scroll toggle button */}
            <Tooltip title={autoScrollEnabled ? "Disable auto-scroll" : "Enable auto-scroll"}>
              <IconButton
                size="small"
                onClick={(e) => {
                  e.stopPropagation();
                  setAutoScrollEnabled(!autoScrollEnabled);
                }}
                sx={{
                  color: autoScrollEnabled ? 'primary.main' : 'text.secondary',
                  '&:hover': {
                    backgroundColor: autoScrollEnabled ? 'primary.light' : 'grey.200',
                  },
                }}
              >
                {autoScrollEnabled ? (
                  <DisableScrollIcon sx={{ fontSize: '1.2rem' }} />
                ) : (
                  <EnableScrollIcon sx={{ fontSize: '1.2rem' }} />
                )}
              </IconButton>
            </Tooltip>
          </Box>
        </AccordionSummary>
        <AccordionDetails sx={{ p: 3, flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden', minHeight: 0 }}>
          {connectionError && (
            <Alert severity="error" sx={{ mb: 2, flexShrink: 0 }}>
              {connectionError}
            </Alert>
          )}
          
          {loadStatus === 'idle' && (
            <Typography color="text.secondary">
              Configure processing settings and click Load to begin processing.
            </Typography>
          )}

          {loadStatus === 'loading' && (
            <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              {/* Progress Bar */}
              <Box sx={{ mb: 3, flexShrink: 0 }}>
                <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 1 }}>
                  <Typography variant="body2" color="text.secondary">
                    Processing Progress
                  </Typography>
                  <Typography variant="body2" color="text.secondary">
                    {currentProgress.toFixed(1)}%
                  </Typography>
                </Box>
                <LinearProgress
                  variant="determinate"
                  value={currentProgress}
                  sx={{
                    height: 6,
                    borderRadius: 3,
                    backgroundColor: 'grey.200',
                    '& .MuiLinearProgress-bar': {
                      borderRadius: 3,
                    },
                  }}
                />
                {currentPhase && (
                  <Typography variant="caption" color="primary.main" sx={{ mt: 1, display: 'block' }}>
                    Current Phase: {currentPhase}
                    {currentStep && ` - ${currentStep}`}
                  </Typography>
                )}
              </Box>

              {/* Messages Container with Two Columns */}
              <Box sx={{ flex: 1, display: 'flex', gap: 2, overflow: 'hidden', minHeight: 0 }}>
                {/* Preview Items Column */}
                {previewItems.length > 0 && (
                  <Box sx={{ width: '300px', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                    <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}>
                      Preview Output
                    </Typography>
                    <Box 
                      ref={previewContainerRef}
                      sx={{ 
                        flex: 1,
                        overflow: 'auto',
                        backgroundColor: 'grey.50',
                        borderRadius: 1,
                        p: 1,
                        border: '1px solid',
                        borderColor: 'grey.200'
                      }}
                    >
                      {previewItems.map((item) => (
                        <Card
                          key={item.id}
                          sx={{
                            mb: 1,
                            cursor: 'pointer',
                            border: item.id === activePreviewId ? '2px solid' : '1px solid',
                            borderColor: item.id === activePreviewId ? 'primary.main' : 'grey.300',
                            transition: 'all 0.2s ease-in-out',
                            '&:hover': {
                              borderColor: 'primary.main',
                              transform: 'translateY(-1px)',
                              boxShadow: 2,
                            }
                          }}
                          onClick={() => togglePreviewMinification(item.id)}
                        >
                          <CardContent sx={{ p: 2, '&:last-child': { pb: 2 } }}>
                            <Box sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', mb: 1 }}>
                              <Chip
                                label={item.type.toUpperCase()}
                                size="small"
                                color={item.type === 'json' ? 'primary' : item.type === 'curl' ? 'warning' : 'info'}
                                sx={{ fontSize: '0.7rem' }}
                              />
                              <Typography variant="caption" color="text.secondary">
                                {item.timestamp}
                              </Typography>
                            </Box>
                            
                            {item.type === 'pdf' ? (
                              <Box>
                                <Typography variant="body2" sx={{ fontWeight: 500, mb: 1 }}>
                                  {item.filename}
                                </Typography>
                                {item.isMinified ? (
                                  <Typography variant="caption" color="text.secondary">
                                    Click to view PDF
                                  </Typography>
                                ) : (
                                  item.pdfUrl && (
                                    <Box sx={{ height: '200px', overflow: 'hidden', borderRadius: 1 }}>
                                      <embed
                                        src={item.pdfUrl}
                                        type="application/pdf"
                                        width="100%"
                                        height="100%"
                                        style={{ border: 'none' }}
                                      />
                                    </Box>
                                  )
                                )}
                              </Box>
                            ) : (
                              <Box>
                                <Typography 
                                  variant="body2" 
                                  sx={{ 
                                    fontFamily: 'monospace',
                                    fontSize: '0.75rem',
                                    backgroundColor: 'grey.100',
                                    p: 1,
                                    borderRadius: 1,
                                    whiteSpace: item.isMinified ? 'nowrap' : 'pre-wrap',
                                    overflow: item.isMinified ? 'hidden' : 'auto',
                                    textOverflow: item.isMinified ? 'ellipsis' : 'unset',
                                    maxHeight: item.isMinified ? 'none' : '150px'
                                  }}
                                >
                                  {item.isMinified 
                                    ? (item.content.length > 100 ? item.content.substring(0, 100) + '...' : item.content)
                                    : (item.type === 'json' ? formatJsonPreview(item.content) : formatCurlPreview(item.content))
                                  }
                                </Typography>
                                {!item.isMinified && (
                                  <Box sx={{ mt: 1, display: 'flex', gap: 1 }}>
                                    <Tooltip title="Copy to clipboard">
                                      <IconButton
                                        size="small"
                                        onClick={(e) => {
                                          e.stopPropagation();
                                          navigator.clipboard.writeText(item.content);
                                        }}
                                      >
                                        <CopyIcon fontSize="small" />
                                      </IconButton>
                                    </Tooltip>
                                    <Tooltip title="View full content">
                                      <IconButton
                                        size="small"
                                        onClick={(e) => {
                                          e.stopPropagation();
                                          if (item.type === 'json') {
                                            handleOpenJsonDialog(item.content);
                                          } else {
                                            handleOpenCurlDialog(item.content);
                                          }
                                        }}
                                      >
                                        <CodeIcon fontSize="small" />
                                      </IconButton>
                                    </Tooltip>
                                  </Box>
                                )}
                              </Box>
                            )}
                          </CardContent>
                        </Card>
                      ))}
                    </Box>
                  </Box>
                )}

                {/* Processing Messages Column - Chat Interface */}
                <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                  <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}>
                    Chat Assistant
                  </Typography>
                  <Box 
                    ref={loadingLogRef}
                    sx={{ 
                      flex: 1,
                      overflow: 'auto',
                      backgroundColor: 'grey.50',
                      borderRadius: 1,
                      p: 2,
                      border: '1px solid',
                      borderColor: 'grey.200',
                      mb: 2,
                      display: 'flex',
                      flexDirection: 'column'
                    }}
                  >
                    {!hasUserInteracted && (
                       <Box sx={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100%', flexDirection: 'column', opacity: 0.6 }}>
                          <BotIcon sx={{ fontSize: 48, mb: 2, color: 'primary.main' }} />
                          <Typography variant="body1" align="center" gutterBottom>
                            Hello! I'm your Benefit Agent Assistant.
                          </Typography>
                          <Typography variant="body2" align="center">
                            Type a message below to start processing your request.
                          </Typography>
                       </Box>
                    )}
                    {processingMessages.map((msg, index) => (
                      <Box key={index} sx={{ 
                        display: 'flex', 
                        justifyContent: msg.isUser ? 'flex-end' : 'flex-start', 
                        mb: 2,
                        width: '100%'
                      }}>
                        {!msg.isUser && (
                          <Avatar sx={{ width: 32, height: 32, mr: 1, bgcolor: 'primary.main' }}>
                            <BotIcon fontSize="small" />
                          </Avatar>
                        )}
                        
                        <Paper
                          elevation={1}
                          sx={{
                            p: 2,
                            maxWidth: '85%',
                            borderRadius: 2,
                            backgroundColor: msg.isUser ? 'primary.main' : 'white',
                            color: msg.isUser ? 'primary.contrastText' : 'text.primary',
                            borderTopLeftRadius: !msg.isUser ? 0 : 12,
                            borderTopRightRadius: msg.isUser ? 0 : 12,
                            borderBottomLeftRadius: 12,
                            borderBottomRightRadius: 12,
                            '& .MuiTypography-root': { color: msg.isUser ? 'inherit' : 'text.primary' } 
                          }}
                        >
                          {/* If it is a user message, just render text, otherwise use the complex renderer */}
                          {msg.isUser ? (
                            <Typography variant="body2">{msg.message}</Typography>
                          ) : (
                            renderMessageContent(msg.message, index)
                          )}
                          <Typography variant="caption" sx={{ display: 'block', mt: 0.5, opacity: 0.7, textAlign: 'right', fontSize: '0.7rem', color: 'inherit' }}>
                            {msg.timestamp}
                          </Typography>
                        </Paper>

                        {msg.isUser && (
                          <Avatar sx={{ width: 32, height: 32, ml: 1, bgcolor: 'secondary.main' }}>
                            <PersonIcon fontSize="small" />
                          </Avatar>
                        )}
                      </Box>
                    ))}
                  </Box>

                  {/* Input Area */}
                  <Box sx={{ display: 'flex', gap: 1 }}>
                    <TextField
                      fullWidth
                      placeholder={hasUserInteracted ? "Processing in progress..." : "Type your request here to start..."}
                      value={userInput}
                      onChange={(e) => setUserInput(e.target.value)}
                      onKeyDown={handleInputKeyPress}
                      disabled={hasUserInteracted && isInputDisabled}
                      size="small"
                      variant="outlined"
                      sx={{ backgroundColor: 'white' }}
                      InputProps={{
                        endAdornment: (
                          <InputAdornment position="end">
                            <IconButton 
                              onClick={handleSendMessage}
                              disabled={!userInput.trim() || (hasUserInteracted && isInputDisabled)}
                              color="primary"
                              edge="end"
                            >
                              <SendIcon />
                            </IconButton>
                          </InputAdornment>
                        ),
                      }}
                    />
                  </Box>
                </Box>
              </Box>
            </Box>
          )}

          {loadStatus === 'success' && (
            <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              {/* Success Status Card */}
              <Card sx={{ mb: 3, flexShrink: 0 }}>
                <CardContent>
                  <Box sx={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', mb: 2 }}>
                    <Typography variant="h6" color="success.main" sx={{ fontWeight: 600 }}>
                      Processing Complete
                    </Typography>
                    <Chip
                      label={`${currentProgress}% Complete`}
                      color="success"
                      variant="outlined"
                    />
                  </Box>
                  
                  {finalStats && (
                    <Box>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        Status: <strong>{finalStats.status}</strong>
                      </Typography>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        Records Processed: <strong>{finalStats.number_of_records}</strong>
                      </Typography>
                      <Typography variant="body2" color="text.secondary" gutterBottom>
                        Request ID: <strong>{finalStats.request_id}</strong>
                      </Typography>
                      
                      {/* Download Button */}
                      <Box sx={{ mt: 2 }}>
                        <Button
                          variant="contained"
                          color="success"
                          startIcon={isDownloading ? <CircularProgress size={16} /> : <DownloadIcon />}
                          disabled={isDownloading}
                          onClick={() => handleDownload(finalStats.request_id)}
                          sx={{ mr: 2 }}
                        >
                          {isDownloading ? 'Downloading...' : 'Download Excel Report'}
                        </Button>
                        <Button
                          variant="outlined"
                          onClick={clearData}
                          startIcon={<RefreshIcon />}
                        >
                          Start New Processing
                        </Button>
                      </Box>
                    </Box>
                  )}
                </CardContent>
              </Card>

              {/* Completed Messages Log */}
              <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}>
                  Conversation History
                </Typography>
                <Box 
                  ref={completeLogRef}
                  sx={{ 
                    flex: 1,
                    overflow: 'auto',
                    backgroundColor: 'grey.50',
                    borderRadius: 1,
                    p: 2,
                    border: '1px solid',
                    borderColor: 'grey.200'
                  }}
                >
                  {processingMessages.map((msg, index) => (
                    <Box key={index} sx={{ 
                      display: 'flex', 
                      justifyContent: msg.isUser ? 'flex-end' : 'flex-start', 
                      mb: 2,
                      width: '100%'
                    }}>
                      {!msg.isUser && (
                        <Avatar sx={{ width: 32, height: 32, mr: 1, bgcolor: 'primary.main' }}>
                          <BotIcon fontSize="small" />
                        </Avatar>
                      )}
                      
                      <Paper
                        elevation={1}
                        sx={{
                          p: 2,
                          maxWidth: '85%',
                          borderRadius: 2,
                          backgroundColor: msg.isUser ? 'primary.main' : 'white',
                          color: msg.isUser ? 'primary.contrastText' : 'text.primary',
                          borderTopLeftRadius: !msg.isUser ? 0 : 12,
                          borderTopRightRadius: msg.isUser ? 0 : 12,
                          borderBottomLeftRadius: 12,
                          borderBottomRightRadius: 12,
                          '& .MuiTypography-root': { color: msg.isUser ? 'inherit' : 'text.primary' } 
                        }}
                      >
                        {msg.isUser ? (
                          <Typography variant="body2">{msg.message}</Typography>
                        ) : (
                          renderMessageContent(msg.message, index)
                        )}
                        <Typography variant="caption" sx={{ display: 'block', mt: 0.5, opacity: 0.7, textAlign: 'right', fontSize: '0.7rem', color: 'inherit' }}>
                          {msg.timestamp}
                        </Typography>
                      </Paper>

                      {msg.isUser && (
                        <Avatar sx={{ width: 32, height: 32, ml: 1, bgcolor: 'secondary.main' }}>
                          <PersonIcon fontSize="small" />
                        </Avatar>
                      )}
                    </Box>
                  ))}
                </Box>
              </Box>
            </Box>
          )}

          {loadStatus === 'error' && (
            <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              {/* Error Status Card */}
              <Card sx={{ mb: 3, flexShrink: 0, backgroundColor: 'error.light' }}>
                <CardContent>
                  <Typography variant="h6" color="error.main" sx={{ fontWeight: 600, mb: 2 }}>
                    Processing Failed
                  </Typography>
                  <Button
                    variant="contained"
                    color="error"
                    onClick={clearData}
                    startIcon={<RefreshIcon />}
                  >
                    Reset and Try Again
                  </Button>
                </CardContent>
              </Card>

              {/* Error Messages Log */}
              {processingMessages.length > 0 && (
                <Box sx={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
                  <Typography variant="subtitle2" sx={{ mb: 1, fontWeight: 600, color: 'text.primary' }}>
                    Conversation History
                  </Typography>
                  <Box 
                    ref={errorLogRef}
                    sx={{ 
                      flex: 1,
                      overflow: 'auto',
                      backgroundColor: 'grey.50',
                      borderRadius: 1,
                      p: 2,
                      border: '1px solid',
                      borderColor: 'error.light'
                    }}
                  >
                    {processingMessages.map((msg, index) => (
                      <Box key={index} sx={{ 
                        display: 'flex', 
                        justifyContent: msg.isUser ? 'flex-end' : 'flex-start', 
                        mb: 2,
                        width: '100%'
                      }}>
                        {!msg.isUser && (
                          <Avatar sx={{ width: 32, height: 32, mr: 1, bgcolor: 'error.main' }}>
                            <BotIcon fontSize="small" />
                          </Avatar>
                        )}
                        
                        <Paper
                          elevation={1}
                          sx={{
                            p: 2,
                            maxWidth: '85%',
                            borderRadius: 2,
                            backgroundColor: msg.isUser ? 'primary.main' : 'white',
                            color: msg.isUser ? 'primary.contrastText' : 'text.primary',
                            borderTopLeftRadius: !msg.isUser ? 0 : 12,
                            borderTopRightRadius: msg.isUser ? 0 : 12,
                            borderBottomLeftRadius: 12,
                            borderBottomRightRadius: 12,
                            '& .MuiTypography-root': { color: msg.isUser ? 'inherit' : 'text.primary' } 
                          }}
                        >
                          {msg.isUser ? (
                            <Typography variant="body2">{msg.message}</Typography>
                          ) : (
                            renderMessageContent(msg.message, index)
                          )}
                          <Typography variant="caption" sx={{ display: 'block', mt: 0.5, opacity: 0.7, textAlign: 'right', fontSize: '0.7rem', color: 'inherit' }}>
                            {msg.timestamp}
                          </Typography>
                        </Paper>

                        {msg.isUser && (
                          <Avatar sx={{ width: 32, height: 32, ml: 1, bgcolor: 'secondary.main' }}>
                            <PersonIcon fontSize="small" />
                          </Avatar>
                        )}
                      </Box>
                    ))}
                  </Box>
                </Box>
              )}
            </Box>
          )}
        </AccordionDetails>
      </Accordion>

      {/* JSON Dialog */}
      <Dialog
        open={jsonDialogOpen}
        onClose={handleCloseJsonDialog}
        maxWidth="lg"
        fullWidth
        PaperProps={{
          sx: { height: '80vh' }
        }}
      >
        <DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 1 }}>
          <Typography variant="h6">JSON Content</Typography>
          <Box>
            <Tooltip title={isJsonExpanded ? "Minimize JSON" : "Format JSON"}>
              <IconButton
                onClick={() => setIsJsonExpanded(!isJsonExpanded)}
                size="small"
                sx={{ mr: 1 }}
              >
                {isJsonExpanded ? <CollapseAllIcon /> : <ExpandAllIcon />}
              </IconButton>
            </Tooltip>
            <Tooltip title="Copy to clipboard">
              <IconButton
                onClick={handleCopyJson}
                size="small"
                sx={{ mr: 1 }}
              >
                <CopyIcon />
              </IconButton>
            </Tooltip>
          </Box>
        </DialogTitle>
        <DialogContent sx={{ p: 0 }}>
          <Box
            sx={{
              fontFamily: 'monospace',
              fontSize: '0.875rem',
              whiteSpace: 'pre-wrap',
              backgroundColor: 'grey.100',
              p: 2,
              height: '100%',
              overflow: 'auto',
              border: 'none',
              outline: 'none',
              resize: 'none',
            }}
            component="textarea"
            value={isJsonExpanded ? formatJSON(selectedJsonContent) : minifyJSON(selectedJsonContent)}
            readOnly
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseJsonDialog}>Close</Button>
        </DialogActions>
      </Dialog>

      {/* CURL Dialog */}
      <Dialog
        open={curlDialogOpen}
        onClose={handleCloseCurlDialog}
        maxWidth="lg"
        fullWidth
        PaperProps={{
          sx: { height: '80vh' }
        }}
      >
        <DialogTitle sx={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', pb: 1 }}>
          <Typography variant="h6">CURL Command</Typography>
          <Box>
            <Tooltip title={isCurlExpanded ? "Minimize CURL" : "Format CURL"}>
              <IconButton
                onClick={() => setIsCurlExpanded(!isCurlExpanded)}
                size="small"
                sx={{ mr: 1 }}
              >
                {isCurlExpanded ? <CollapseAllIcon /> : <ExpandAllIcon />}
              </IconButton>
            </Tooltip>
            <Tooltip title="Copy to clipboard">
              <IconButton
                onClick={handleCopyCurl}
                size="small"
                sx={{ mr: 1 }}
              >
                <CopyIcon />
              </IconButton>
            </Tooltip>
          </Box>
        </DialogTitle>
        <DialogContent sx={{ p: 0 }}>
          <Box
            sx={{
              fontFamily: 'monospace',
              fontSize: '0.875rem',
              whiteSpace: 'pre-wrap',
              backgroundColor: 'grey.100',
              p: 2,
              height: '100%',
              overflow: 'auto',
              border: 'none',
              outline: 'none',
              resize: 'none',
            }}
            component="textarea"
            value={isCurlExpanded ? formatCurl(selectedCurlContent) : minifyCurl(selectedCurlContent)}
            readOnly
          />
        </DialogContent>
        <DialogActions>
          <Button onClick={handleCloseCurlDialog}>Close</Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
};

export default ProcessingStatus;