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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# enhanced_verification_ui.py
"""
Enhanced Verification UI Components for Multi-Mode Verification.

Provides interface components for mode selection, session resumption,
and enhanced verification workflows across different modes.

Requirements: 1.1, 1.2, 1.3, 1.4, 1.5
"""

import gradio as gr
from typing import List, Dict, Tuple, Optional, Any
from dataclasses import dataclass
from datetime import datetime
import uuid

from src.core.verification_models import (
    EnhancedVerificationSession,
    VerificationRecord,
    TestMessage,
    TestDataset,
)
from src.core.verification_store import JSONVerificationStore
from src.core.test_datasets import TestDatasetManager
from src.interface.enhanced_dataset_interface import EnhancedDatasetInterfaceController


@dataclass
class ModeSelectionState:
    """State container for mode selection interface."""
    current_mode: Optional[str] = None
    incomplete_sessions: List[EnhancedVerificationSession] = None
    selected_session: Optional[EnhancedVerificationSession] = None
    
    def __post_init__(self):
        if self.incomplete_sessions is None:
            self.incomplete_sessions = []


class EnhancedVerificationUIComponents:
    """Enhanced UI components for multi-mode verification."""
    
    # Mode definitions with descriptions
    MODE_OPTIONS = {
        "enhanced_dataset": {
            "icon": "πŸ“Š",
            "title": "Enhanced Datasets",
            "description": "Use existing test datasets with editing capabilities. Add, modify, or delete test cases to customize datasets for specific testing scenarios.",
            "features": [
                "Edit existing datasets",
                "Add new test cases",
                "Modify message text and classifications",
                "Delete test cases with confirmation",
                "Dataset versioning and backup"
            ]
        },
        "manual_input": {
            "icon": "✏️",
            "title": "Manual Input",
            "description": "Manually enter individual messages for immediate testing. Perfect for exploring edge cases or testing specific scenarios in real-time.",
            "features": [
                "Real-time message classification",
                "Immediate feedback collection",
                "Session results accumulation",
                "Quick testing of specific cases",
                "Export manual input results"
            ]
        },
        "file_upload": {
            "icon": "πŸ“",
            "title": "File Upload",
            "description": "Upload CSV or XLSX files containing test messages for batch processing. Ideal for large-scale testing with pre-prepared datasets.",
            "features": [
                "CSV and XLSX file support",
                "Batch processing with progress tracking",
                "Automated verification against expected results",
                "File format validation and error reporting",
                "Comprehensive export options"
            ]
        }
    }
    
    @staticmethod
    def create_mode_selection_interface() -> gr.Blocks:
        """
        Create the main mode selection interface.
        
        Returns:
            Gradio Blocks component for mode selection
        """
        with gr.Blocks() as mode_selection:
            # Header
            gr.Markdown("# πŸ” Enhanced Verification Modes")
            gr.Markdown("Choose your verification approach based on your testing needs and data source.")
            
            # Incomplete sessions section
            incomplete_sessions_section = gr.Row(visible=False)
            with incomplete_sessions_section:
                with gr.Column():
                    gr.Markdown("## πŸ“‹ Resume Previous Sessions")
                    gr.Markdown("You have incomplete verification sessions. You can resume where you left off or start a new session.")
                    
                    incomplete_sessions_display = gr.HTML(
                        value="",
                        label="Incomplete Sessions"
                    )
                    
                    with gr.Row():
                        resume_session_btn = gr.Button(
                            "▢️ Resume Selected Session",
                            variant="primary",
                            scale=2
                        )
                        clear_sessions_btn = gr.Button(
                            "πŸ—‘οΈ Clear All Sessions",
                            variant="secondary",
                            scale=1
                        )
            
            # Mode selection cards
            gr.Markdown("## 🎯 Select Verification Mode")
            
            with gr.Row():
                # Enhanced Dataset Mode
                with gr.Column(scale=1):
                    mode_info = EnhancedVerificationUIComponents.MODE_OPTIONS["enhanced_dataset"]
                    gr.Markdown(f"### {mode_info['icon']} {mode_info['title']}")
                    gr.Markdown(mode_info["description"])
                    
                    gr.Markdown("**Features:**")
                    for feature in mode_info["features"]:
                        gr.Markdown(f"β€’ {feature}")
                    
                    enhanced_dataset_btn = gr.Button(
                        f"{mode_info['icon']} Start Enhanced Dataset Mode",
                        variant="primary",
                        size="lg"
                    )
                
                # Manual Input Mode
                with gr.Column(scale=1):
                    mode_info = EnhancedVerificationUIComponents.MODE_OPTIONS["manual_input"]
                    gr.Markdown(f"### {mode_info['icon']} {mode_info['title']}")
                    gr.Markdown(mode_info["description"])
                    
                    gr.Markdown("**Features:**")
                    for feature in mode_info["features"]:
                        gr.Markdown(f"β€’ {feature}")
                    
                    manual_input_btn = gr.Button(
                        f"{mode_info['icon']} Start Manual Input Mode",
                        variant="primary",
                        size="lg"
                    )
                
                # File Upload Mode
                with gr.Column(scale=1):
                    mode_info = EnhancedVerificationUIComponents.MODE_OPTIONS["file_upload"]
                    gr.Markdown(f"### {mode_info['icon']} {mode_info['title']}")
                    gr.Markdown(mode_info["description"])
                    
                    gr.Markdown("**Features:**")
                    for feature in mode_info["features"]:
                        gr.Markdown(f"β€’ {feature}")
                    
                    file_upload_btn = gr.Button(
                        f"{mode_info['icon']} Start File Upload Mode",
                        variant="primary",
                        size="lg"
                    )
            
            # Progress preservation warning
            progress_warning = gr.Markdown(
                "",
                visible=False,
                label="Progress Warning"
            )
            
            # Confirmation dialog for mode switching
            mode_switch_dialog = gr.Row(visible=False)
            with mode_switch_dialog:
                with gr.Column():
                    gr.Markdown("### ⚠️ Switch Mode Confirmation")
                    switch_warning_text = gr.Markdown(
                        "You have unsaved progress in the current mode. What would you like to do?",
                        label="Warning"
                    )
                    
                    with gr.Row():
                        save_and_switch_btn = gr.Button(
                            "πŸ’Ύ Save Progress & Switch",
                            variant="primary",
                            scale=2
                        )
                        discard_and_switch_btn = gr.Button(
                            "πŸ—‘οΈ Discard & Switch",
                            variant="secondary",
                            scale=1
                        )
                        cancel_switch_btn = gr.Button(
                            "❌ Cancel",
                            scale=1
                        )
            
            # Status message
            status_message = gr.Markdown(
                "",
                visible=True,
                label="Status"
            )
            
            # Hidden state for tracking
            current_mode_state = gr.State(value=None)
            incomplete_sessions_state = gr.State(value=[])
            selected_session_state = gr.State(value=None)
            pending_mode_switch = gr.State(value=None)
        
        return mode_selection
    
    @staticmethod
    def render_incomplete_sessions_display(sessions: List[EnhancedVerificationSession]) -> str:
        """
        Render HTML display for incomplete sessions.
        
        Args:
            sessions: List of incomplete verification sessions
            
        Returns:
            HTML string for displaying incomplete sessions
        """
        if not sessions:
            return ""
        
        html = """
        <div style="font-family: system-ui; padding: 1em; background-color: #f9fafb; border-radius: 8px; border: 1px solid #e5e7eb;">
        """
        
        for session in sessions:
            mode_info = EnhancedVerificationUIComponents.MODE_OPTIONS.get(
                session.mode_type, 
                {"icon": "❓", "title": "Unknown Mode"}
            )
            
            progress_pct = (session.verified_count / session.total_messages * 100) if session.total_messages > 0 else 0
            accuracy = (session.correct_count / session.verified_count * 100) if session.verified_count > 0 else 0
            
            # Format creation time
            time_ago = EnhancedVerificationUIComponents._format_time_ago(session.created_at)
            
            html += f"""
            <div style="margin-bottom: 1em; padding: 1em; background-color: white; border-radius: 6px; border: 1px solid #d1d5db; cursor: pointer;" 
                 onclick="this.style.backgroundColor='#eff6ff'; this.style.borderColor='#3b82f6';">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.5em;">
                    <h4 style="margin: 0; color: #1f2937;">
                        {mode_info['icon']} {mode_info['title']} - {session.dataset_name}
                    </h4>
                    <span style="font-size: 0.875em; color: #6b7280;">{time_ago}</span>
                </div>
                
                <div style="margin-bottom: 0.5em;">
                    <div style="display: flex; justify-content: space-between; margin-bottom: 0.25em;">
                        <span style="font-size: 0.875em; color: #374151;">Progress: {session.verified_count}/{session.total_messages}</span>
                        <span style="font-size: 0.875em; color: #374151;">{progress_pct:.0f}%</span>
                    </div>
                    <div style="width: 100%; background-color: #e5e7eb; border-radius: 4px; height: 8px;">
                        <div style="width: {progress_pct}%; background-color: #3b82f6; border-radius: 4px; height: 8px;"></div>
                    </div>
                </div>
                
                <div style="display: flex; gap: 1em; font-size: 0.875em; color: #6b7280;">
                    <span>βœ“ Correct: {session.correct_count}</span>
                    <span>βœ— Incorrect: {session.incorrect_count}</span>
                    <span>πŸ“Š Accuracy: {accuracy:.1f}%</span>
                </div>
                
                <div style="margin-top: 0.5em; font-size: 0.75em; color: #9ca3af;">
                    Session ID: {session.session_id[:8]}...
                </div>
            </div>
            """
        
        html += """
        </div>
        <p style="font-size: 0.875em; color: #6b7280; margin-top: 0.5em;">
        πŸ’‘ <strong>Tip:</strong> Click on a session above to select it, then click "Resume Selected Session" to continue where you left off.
        </p>
        """
        
        return html
    
    @staticmethod
    def _format_time_ago(timestamp: datetime) -> str:
        """
        Format timestamp as time ago string.
        
        Args:
            timestamp: Datetime to format
            
        Returns:
            Human-readable time ago string
        """
        now = datetime.now()
        diff = now - timestamp
        
        if diff.days > 0:
            return f"{diff.days} day{'s' if diff.days != 1 else ''} ago"
        elif diff.seconds > 3600:
            hours = diff.seconds // 3600
            return f"{hours} hour{'s' if hours != 1 else ''} ago"
        elif diff.seconds > 60:
            minutes = diff.seconds // 60
            return f"{minutes} minute{'s' if minutes != 1 else ''} ago"
        else:
            return "Just now"
    
    @staticmethod
    def check_for_incomplete_sessions(store: JSONVerificationStore) -> Tuple[bool, List[EnhancedVerificationSession], str]:
        """
        Check for incomplete sessions and return display information.
        
        Args:
            store: Verification data store
            
        Returns:
            Tuple of (has_incomplete, sessions_list, display_html)
        """
        try:
            incomplete_sessions = store.get_incomplete_sessions()
            
            # Filter to only enhanced sessions for this interface
            enhanced_sessions = [
                s for s in incomplete_sessions 
                if isinstance(s, EnhancedVerificationSession)
            ]
            
            if enhanced_sessions:
                display_html = EnhancedVerificationUIComponents.render_incomplete_sessions_display(enhanced_sessions)
                return True, enhanced_sessions, display_html
            else:
                return False, [], ""
                
        except Exception as e:
            error_html = f"""
            <div style="padding: 1em; background-color: #fef2f2; border-left: 4px solid #dc2626; border-radius: 4px;">
                <h4 style="color: #dc2626; margin-top: 0;">❌ Error Loading Sessions</h4>
                <p style="margin-bottom: 0;">Could not load incomplete sessions: {str(e)}</p>
            </div>
            """
            return False, [], error_html
    
    @staticmethod
    def create_mode_switch_confirmation(current_mode: str, target_mode: str, has_progress: bool) -> Tuple[str, bool]:
        """
        Create mode switch confirmation message.
        
        Args:
            current_mode: Current verification mode
            target_mode: Target verification mode
            has_progress: Whether there is unsaved progress
            
        Returns:
            Tuple of (warning_message, show_dialog)
        """
        if not has_progress:
            return "", False
        
        current_info = EnhancedVerificationUIComponents.MODE_OPTIONS.get(current_mode, {"title": "Unknown"})
        target_info = EnhancedVerificationUIComponents.MODE_OPTIONS.get(target_mode, {"title": "Unknown"})
        
        warning_message = f"""
        You are currently in **{current_info['title']}** mode and have unsaved progress.
        
        Switching to **{target_info['title']}** mode will:
        - Save your current progress automatically
        - Switch to the new verification mode
        - Allow you to resume the current session later
        
        **What would you like to do?**
        """
        
        return warning_message, True
    
    @staticmethod
    def create_enhanced_dataset_interface() -> gr.Blocks:
        """
        Create enhanced dataset mode interface.
        
        Returns:
            Gradio Blocks component for enhanced dataset mode
        """
        with gr.Blocks() as enhanced_dataset_interface:
            gr.Markdown("# πŸ“Š Enhanced Dataset Mode")
            gr.Markdown("Select and customize test datasets for verification. You can edit existing datasets or create new test cases.")
            
            # Back to mode selection
            back_to_modes_btn = gr.Button("← Back to Mode Selection", size="sm")
            
            # Application state
            current_dataset_state = gr.State(value=None)
            editing_mode_state = gr.State(value=False)
            selected_test_case_state = gr.State(value=None)
            dataset_manager_state = gr.State(value=None)
            
            # Dataset selection and editing interface
            with gr.Row():
                with gr.Column(scale=2):
                    gr.Markdown("## πŸ“‹ Select Dataset")
                    
                    # Dataset selector
                    dataset_selector = gr.Dropdown(
                        choices=[],
                        label="Available Datasets",
                        info="Choose a dataset to verify or edit",
                        interactive=True
                    )
                    
                    with gr.Row():
                        load_dataset_btn = gr.Button("πŸ“₯ Load Dataset", variant="primary", scale=2)
                        edit_dataset_btn = gr.Button("✏️ Edit Dataset", variant="secondary", scale=1)
                        create_new_btn = gr.Button("βž• Create New", variant="secondary", scale=1)
                
                with gr.Column(scale=1):
                    gr.Markdown("## πŸ“Š Dataset Information")
                    dataset_info_display = gr.Markdown(
                        "Select a dataset to view details",
                        label="Dataset Details"
                    )
            
            # Dataset creation section (initially hidden)
            dataset_creation_section = gr.Row(visible=False)
            with dataset_creation_section:
                with gr.Column():
                    gr.Markdown("## βž• Create New Dataset")
                    
                    with gr.Row():
                        with gr.Column(scale=2):
                            new_dataset_name = gr.Textbox(
                                label="Dataset Name",
                                placeholder="e.g., Custom Test Messages",
                                interactive=True
                            )
                        
                        with gr.Column(scale=1):
                            template_selector = gr.Dropdown(
                                choices=[],
                                label="Template (Optional)",
                                info="Start with a template",
                                interactive=True
                            )
                    
                    new_dataset_description = gr.Textbox(
                        label="Dataset Description",
                        placeholder="Describe the purpose and content of this dataset...",
                        lines=2,
                        interactive=True
                    )
                    
                    with gr.Row():
                        create_dataset_btn = gr.Button("✨ Create Dataset", variant="primary", scale=2)
                        cancel_create_btn = gr.Button("❌ Cancel", scale=1)
            
            # Dataset editing section (initially hidden)
            dataset_editing_section = gr.Row(visible=False)
            with dataset_editing_section:
                with gr.Column():
                    gr.Markdown("## ✏️ Edit Dataset")
                    
                    # Dataset metadata editing
                    with gr.Row():
                        edit_dataset_name = gr.Textbox(
                            label="Dataset Name",
                            interactive=True
                        )
                        
                        edit_dataset_description = gr.Textbox(
                            label="Dataset Description",
                            lines=2,
                            interactive=True
                        )
                    
                    # Test case list
                    test_cases_display = gr.HTML(
                        value="",
                        label="Test Cases"
                    )
                    
                    # Add new test case
                    gr.Markdown("### βž• Add New Test Case")
                    with gr.Row():
                        with gr.Column(scale=3):
                            new_message_text = gr.Textbox(
                                label="Message Text",
                                placeholder="Enter patient message...",
                                lines=3,
                                interactive=True
                            )
                        
                        with gr.Column(scale=1):
                            new_classification = gr.Radio(
                                choices=[
                                    ("🟒 GREEN - No Distress", "green"),
                                    ("🟑 YELLOW - Potential Distress", "yellow"),
                                    ("πŸ”΄ RED - Severe Distress", "red")
                                ],
                                label="Expected Classification",
                                value="green",
                                interactive=True
                            )
                    
                    with gr.Row():
                        add_test_case_btn = gr.Button("βž• Add Test Case", variant="primary", scale=2)
                        save_dataset_btn = gr.Button("πŸ’Ύ Save Dataset", variant="secondary", scale=1)
                        cancel_edit_btn = gr.Button("❌ Cancel", scale=1)
            
            # Test case editing modal (initially hidden)
            test_case_edit_modal = gr.Row(visible=False)
            with test_case_edit_modal:
                with gr.Column():
                    gr.Markdown("### ✏️ Edit Test Case")
                    
                    edit_message_text = gr.Textbox(
                        label="Message Text",
                        lines=3,
                        interactive=True
                    )
                    
                    edit_classification = gr.Radio(
                        choices=[
                            ("🟒 GREEN - No Distress", "green"),
                            ("🟑 YELLOW - Potential Distress", "yellow"),
                            ("πŸ”΄ RED - Severe Distress", "red")
                        ],
                        label="Expected Classification",
                        interactive=True
                    )
                    
                    with gr.Row():
                        save_test_case_btn = gr.Button("πŸ’Ύ Save Changes", variant="primary", scale=2)
                        delete_test_case_btn = gr.Button("πŸ—‘οΈ Delete", variant="stop", scale=1)
                        cancel_test_case_edit_btn = gr.Button("❌ Cancel", scale=1)
            
            # Verification interface (initially hidden)
            verification_section = gr.Row(visible=False)
            with verification_section:
                with gr.Column():
                    gr.Markdown("## πŸ” Dataset Verification")
                    
                    # Verification controls
                    with gr.Row():
                        with gr.Column(scale=2):
                            verifier_name_input = gr.Textbox(
                                label="Verifier Name",
                                placeholder="Enter your name...",
                                interactive=True
                            )
                        
                        with gr.Column(scale=1):
                            start_verification_btn = gr.Button(
                                "πŸš€ Start Verification",
                                variant="primary",
                                size="lg"
                            )
                    
                    # Progress display
                    verification_progress = gr.Markdown(
                        "Ready to start verification",
                        label="Progress"
                    )
                    
                    # Message review area (initially hidden)
                    message_review_area = gr.Row(visible=False)
                    with message_review_area:
                        with gr.Column(scale=2):
                            # Current message display
                            current_message_display = gr.Textbox(
                                label="πŸ“ Patient Message",
                                interactive=False,
                                lines=4
                            )
                            
                            # Classification results
                            classifier_decision_display = gr.Markdown(
                                "πŸ”„ Loading...",
                                label="🎯 Classifier Decision"
                            )
                            
                            classifier_confidence_display = gr.Markdown(
                                "Loading...",
                                label="πŸ“Š Confidence Level"
                            )
                            
                            classifier_indicators_display = gr.Markdown(
                                "Loading...",
                                label="πŸ” Detected Indicators"
                            )
                            
                            # Verification buttons
                            with gr.Row():
                                correct_classification_btn = gr.Button(
                                    "βœ“ Correct",
                                    variant="primary",
                                    scale=1
                                )
                                
                                incorrect_classification_btn = gr.Button(
                                    "βœ— Incorrect",
                                    variant="stop",
                                    scale=1
                                )
                            
                            # Correction section (initially hidden)
                            correction_section = gr.Row(visible=False)
                            with correction_section:
                                correction_selector = gr.Radio(
                                    choices=[
                                        ("🟒 Should be GREEN - No Distress", "green"),
                                        ("🟑 Should be YELLOW - Potential Distress", "yellow"),
                                        ("πŸ”΄ Should be RED - Severe Distress", "red")
                                    ],
                                    label="Correct Classification",
                                    interactive=True
                                )
                                
                                correction_notes = gr.Textbox(
                                    label="Notes (Optional)",
                                    placeholder="Why is this incorrect?",
                                    lines=2,
                                    interactive=True
                                )
                                
                                submit_correction_btn = gr.Button("βœ“ Submit", variant="primary")
                        
                        with gr.Column(scale=1):
                            # Session statistics
                            gr.Markdown("### πŸ“Š Session Statistics")
                            
                            session_stats_display = gr.Markdown(
                                """
                                **Messages Processed:** 0
                                **Correct Classifications:** 0
                                **Incorrect Classifications:** 0
                                **Accuracy:** 0%
                                """,
                                label="Statistics"
                            )
                            
                            # Export options
                            gr.Markdown("### πŸ’Ύ Export Options")
                            with gr.Column():
                                export_csv_btn = gr.Button("πŸ“„ Export CSV", size="sm")
                                export_json_btn = gr.Button("πŸ“‹ Export JSON", size="sm")
                                export_xlsx_btn = gr.Button("πŸ“Š Export XLSX", size="sm")
            
            # Status and error messages
            status_message = gr.Markdown("", visible=True)
        
        return enhanced_dataset_interface
    
    @staticmethod
    def create_manual_input_interface() -> gr.Blocks:
        """
        Create manual input mode interface.
        
        Returns:
            Gradio Blocks component for manual input mode
        """
        with gr.Blocks() as manual_input_interface:
            gr.Markdown("# ✏️ Manual Input Mode")
            gr.Markdown("Enter individual messages for immediate classification and verification. Perfect for testing specific scenarios.")
            
            # Back to mode selection
            back_to_modes_btn = gr.Button("← Back to Mode Selection", size="sm")
            
            with gr.Row():
                with gr.Column(scale=2):
                    # Message input area
                    gr.Markdown("## πŸ“ Enter Patient Message")
                    
                    message_input = gr.Textbox(
                        label="Patient Message",
                        placeholder="Type or paste a patient message here...",
                        lines=6,
                        max_lines=10
                    )
                    
                    classify_btn = gr.Button(
                        "πŸ” Classify Message",
                        variant="primary",
                        size="lg"
                    )
                    
                    # Classification results (initially hidden)
                    classification_results = gr.Row(visible=False)
                    with classification_results:
                        with gr.Column():
                            gr.Markdown("### 🎯 Classification Results")
                            
                            decision_display = gr.Markdown("", label="Decision")
                            confidence_display = gr.Markdown("", label="Confidence")
                            indicators_display = gr.Markdown("", label="Indicators")
                            
                            # Verification buttons
                            with gr.Row():
                                correct_btn = gr.Button("βœ“ Correct", variant="primary", scale=1)
                                incorrect_btn = gr.Button("βœ— Incorrect", variant="stop", scale=1)
                            
                            # Correction selector (initially hidden)
                            correction_section = gr.Row(visible=False)
                            with correction_section:
                                correction_selector = gr.Radio(
                                    choices=[
                                        ("🟒 Should be GREEN - No Distress", "green"),
                                        ("🟑 Should be YELLOW - Potential Distress", "yellow"),
                                        ("πŸ”΄ Should be RED - Severe Distress", "red")
                                    ],
                                    label="Correct Classification"
                                )
                                
                                notes_input = gr.Textbox(
                                    label="Notes (Optional)",
                                    placeholder="Why is this incorrect?",
                                    lines=2
                                )
                                
                                submit_correction_btn = gr.Button("βœ“ Submit", variant="primary")
                
                with gr.Column(scale=1):
                    # Session statistics
                    gr.Markdown("## πŸ“Š Session Statistics")
                    
                    session_stats = gr.Markdown(
                        """
                        **Messages Processed:** 0
                        **Correct Classifications:** 0
                        **Incorrect Classifications:** 0
                        **Accuracy:** 0%
                        """,
                        label="Statistics"
                    )
                    
                    # Recent results
                    gr.Markdown("## πŸ“‹ Recent Results")
                    recent_results = gr.HTML(
                        value="<p>No messages processed yet.</p>",
                        label="Recent Results"
                    )
                    
                    # Export options
                    gr.Markdown("## πŸ’Ύ Export Results")
                    with gr.Column():
                        export_csv_btn = gr.Button("πŸ“„ Export CSV", size="sm")
                        export_json_btn = gr.Button("πŸ“‹ Export JSON", size="sm")
                        clear_session_btn = gr.Button("πŸ—‘οΈ Clear Session", size="sm")
            
            # Status messages
            status_message = gr.Markdown("", visible=True)
        
        return manual_input_interface
    
    @staticmethod
    def create_file_upload_interface() -> gr.Blocks:
        """
        Create file upload mode interface.
        
        Returns:
            Gradio Blocks component for file upload mode
        """
        with gr.Blocks() as file_upload_interface:
            gr.Markdown("# πŸ“ File Upload Mode")
            gr.Markdown("Upload CSV or XLSX files containing test messages for batch processing and verification.")
            
            # Back to mode selection
            back_to_modes_btn = gr.Button("← Back to Mode Selection", size="sm")
            
            with gr.Row():
                with gr.Column(scale=2):
                    # File upload area
                    gr.Markdown("## πŸ“€ Upload Test File")
                    
                    file_upload = gr.File(
                        label="Select CSV or XLSX File",
                        file_types=[".csv", ".xlsx"],
                        file_count="single"
                    )
                    
                    # Format requirements
                    gr.Markdown("""
                    **Required Columns:**
                    - `message` or `text`: Patient message text
                    - `expected_classification` or `classification`: Expected result (GREEN, YELLOW, RED)
                    
                    **Supported Formats:**
                    - CSV files (comma, semicolon, or tab delimited)
                    - XLSX files (first worksheet only)
                    """)
                    
                    # Template download
                    with gr.Row():
                        download_csv_template_btn = gr.Button("πŸ“„ Download CSV Template", size="sm")
                        download_xlsx_template_btn = gr.Button("πŸ“Š Download XLSX Template", size="sm")
                    
                    # File validation results (initially hidden)
                    validation_results = gr.Row(visible=False)
                    with validation_results:
                        with gr.Column():
                            gr.Markdown("### βœ… File Validation Results")
                            
                            validation_summary = gr.Markdown("", label="Summary")
                            file_preview = gr.HTML("", label="Preview")
                            
                            start_processing_btn = gr.Button(
                                "πŸš€ Start Batch Processing",
                                variant="primary",
                                size="lg"
                            )
                
                with gr.Column(scale=1):
                    # Processing status
                    gr.Markdown("## πŸ“Š Processing Status")
                    
                    processing_stats = gr.Markdown(
                        """
                        **File:** Not uploaded
                        **Total Messages:** 0
                        **Processed:** 0
                        **Accuracy:** 0%
                        """,
                        label="Status"
                    )
                    
                    # Progress bar
                    progress_bar = gr.HTML(
                        value="",
                        label="Progress"
                    )
                    
                    # Batch results
                    gr.Markdown("## πŸ“‹ Batch Results")
                    batch_results = gr.HTML(
                        value="<p>No file processed yet.</p>",
                        label="Results"
                    )
                    
                    # Export options
                    gr.Markdown("## πŸ’Ύ Export Results")
                    with gr.Column():
                        export_detailed_csv_btn = gr.Button("πŸ“„ Export Detailed CSV", size="sm")
                        export_summary_btn = gr.Button("πŸ“Š Export Summary", size="sm")
                        export_errors_btn = gr.Button("⚠️ Export Errors", size="sm")
            
            # Status messages
            status_message = gr.Markdown("", visible=True)
        
        return file_upload_interface

    @staticmethod
    def create_enhanced_dataset_interface_with_handlers() -> gr.Blocks:
        """
        Create enhanced dataset mode interface with complete event handlers.
        
        Returns:
            Gradio Blocks component for enhanced dataset mode with functionality
        """
        # Initialize controller
        controller = EnhancedDatasetInterfaceController()
        
        with gr.Blocks() as enhanced_dataset_interface:
            gr.Markdown("# πŸ“Š Enhanced Dataset Mode")
            gr.Markdown("Select and customize test datasets for verification. You can edit existing datasets or create new test cases.")
            
            # Status and error messages
            status_message = gr.Markdown("", visible=True)
        
        return enhanced_dataset_interface


def create_enhanced_verification_app() -> gr.Blocks:
    """
    Create the complete enhanced verification application.
    
    Returns:
        Gradio Blocks application with mode selection and all verification modes
    """
    # Initialize store
    store = JSONVerificationStore()
    
    with gr.Blocks(title="Enhanced Verification Modes") as app:
        # Application state
        current_mode = gr.State(value=None)
        current_session = gr.State(value=None)
        
        # Mode selection interface
        mode_selection = EnhancedVerificationUIComponents.create_mode_selection_interface()
        
        # Individual mode interfaces (initially hidden)
        enhanced_dataset_interface = gr.Row(visible=False)
        with enhanced_dataset_interface:
            enhanced_dataset_ui = EnhancedVerificationUIComponents.create_enhanced_dataset_interface()
        
        manual_input_interface = gr.Row(visible=False)
        with manual_input_interface:
            manual_input_ui = EnhancedVerificationUIComponents.create_manual_input_interface()
        
        file_upload_interface = gr.Row(visible=False)
        with file_upload_interface:
            file_upload_ui = EnhancedVerificationUIComponents.create_file_upload_interface()
        
        # Event handlers for mode selection
        def initialize_app():
            """Initialize the application and check for incomplete sessions."""
            has_incomplete, sessions, display_html = EnhancedVerificationUIComponents.check_for_incomplete_sessions(store)
            
            if has_incomplete:
                return (
                    gr.Row(visible=True),  # Show incomplete sessions section
                    display_html,  # Display sessions
                    sessions,  # Store sessions in state
                    "✨ Welcome back! You have incomplete sessions."
                )
            else:
                return (
                    gr.Row(visible=False),  # Hide incomplete sessions section
                    "",  # Empty display
                    [],  # Empty sessions list
                    "✨ Welcome to Enhanced Verification Modes! Choose a mode to get started."
                )
        
        def switch_to_mode(mode_type: str, current_mode_val: str, current_session_val: EnhancedVerificationSession):
            """Switch to a specific verification mode."""
            # Check if we need to show progress preservation warning
            has_progress = (current_session_val is not None and 
                          not current_session_val.is_complete and 
                          current_session_val.verified_count > 0)
            
            if has_progress and current_mode_val != mode_type:
                warning_msg, show_dialog = EnhancedVerificationUIComponents.create_mode_switch_confirmation(
                    current_mode_val, mode_type, has_progress
                )
                return (
                    gr.Row(visible=True),  # Show confirmation dialog
                    warning_msg,  # Warning message
                    mode_type,  # Store pending mode switch
                    current_mode_val,  # Keep current mode
                    current_session_val,  # Keep current session
                    f"⚠️ Confirm mode switch to {EnhancedVerificationUIComponents.MODE_OPTIONS[mode_type]['title']}"
                )
            else:
                # Direct switch
                return perform_mode_switch(mode_type, current_session_val)
        
        def perform_mode_switch(mode_type: str, session_to_save: EnhancedVerificationSession = None):
            """Perform the actual mode switch."""
            # Save current session if exists
            if session_to_save and not session_to_save.is_complete:
                store.save_session(session_to_save)
            
            # Hide all interfaces
            interfaces_visibility = [gr.Row(visible=False)] * 4  # mode_selection, enhanced_dataset, manual_input, file_upload
            
            # Show selected interface
            if mode_type == "enhanced_dataset":
                interfaces_visibility[1] = gr.Row(visible=True)
            elif mode_type == "manual_input":
                interfaces_visibility[2] = gr.Row(visible=True)
            elif mode_type == "file_upload":
                interfaces_visibility[3] = gr.Row(visible=True)
            else:
                interfaces_visibility[0] = gr.Row(visible=True)  # Default to mode selection
            
            return (
                *interfaces_visibility,
                gr.Row(visible=False),  # Hide confirmation dialog
                "",  # Clear warning message
                None,  # Clear pending mode switch
                mode_type,  # Set current mode
                None,  # Clear current session (will be set by mode interface)
                f"βœ… Switched to {EnhancedVerificationUIComponents.MODE_OPTIONS.get(mode_type, {}).get('title', 'Unknown')} mode"
            )
        
        # Initialize app on load
        app.load(
            initialize_app,
            outputs=[
                # These would be bound to actual components in the full implementation
                # For now, returning placeholder values
            ]
        )
    
    return app



        
        with gr.Blocks() as enhanced_dataset_interface:
            gr.Markdown("# πŸ“Š Enhanced Dataset Mode")
            gr.Markdown("Select and customize test datasets for verification. You can edit existing datasets or create new test cases.")
            
            # Back to mode selection
            back_to_modes_btn = gr.Button("← Back to Mode Selection", size="sm")
            
            # Application state
            current_dataset_state = gr.State(value=None)
            editing_mode_state = gr.State(value=False)
            selected_test_case_state = gr.State(value=None)
            verification_session_state = gr.State(value=None)
            
            # Dataset selection and editing interface
            with gr.Row():
                with gr.Column(scale=2):
                    gr.Markdown("## πŸ“‹ Select Dataset")
                    
                    # Dataset selector
                    dataset_selector = gr.Dropdown(
                        choices=[],
                        label="Available Datasets",
                        info="Choose a dataset to verify or edit",
                        interactive=True
                    )
                    
                    with gr.Row():
                        load_dataset_btn = gr.Button("πŸ“₯ Load Dataset", variant="primary", scale=2)
                        edit_dataset_btn = gr.Button("✏️ Edit Dataset", variant="secondary", scale=1)
                        create_new_btn = gr.Button("βž• Create New", variant="secondary", scale=1)
                
                with gr.Column(scale=1):
                    gr.Markdown("## πŸ“Š Dataset Information")
                    dataset_info_display = gr.Markdown(
                        "Select a dataset to view details",
                        label="Dataset Details"
                    )
            
            # Dataset creation section (initially hidden)
            dataset_creation_section = gr.Row(visible=False)
            with dataset_creation_section:
                with gr.Column():
                    gr.Markdown("## βž• Create New Dataset")
                    
                    with gr.Row():
                        with gr.Column(scale=2):
                            new_dataset_name = gr.Textbox(
                                label="Dataset Name",
                                placeholder="e.g., Custom Test Messages",
                                interactive=True
                            )
                        
                        with gr.Column(scale=1):
                            template_selector = gr.Dropdown(
                                choices=[],
                                label="Template (Optional)",
                                info="Start with a template",
                                interactive=True
                            )
                    
                    new_dataset_description = gr.Textbox(
                        label="Dataset Description",
                        placeholder="Describe the purpose and content of this dataset...",
                        lines=2,
                        interactive=True
                    )
                    
                    with gr.Row():
                        create_dataset_btn = gr.Button("✨ Create Dataset", variant="primary", scale=2)
                        cancel_create_btn = gr.Button("❌ Cancel", scale=1)
            
            # Dataset editing section (initially hidden)
            dataset_editing_section = gr.Row(visible=False)
            with dataset_editing_section:
                with gr.Column():
                    gr.Markdown("## ✏️ Edit Dataset")
                    
                    # Dataset metadata editing
                    with gr.Row():
                        edit_dataset_name = gr.Textbox(
                            label="Dataset Name",
                            interactive=True
                        )
                        
                        edit_dataset_description = gr.Textbox(
                            label="Dataset Description",
                            lines=2,
                            interactive=True
                        )
                    
                    # Test case list
                    test_cases_display = gr.HTML(
                        value="",
                        label="Test Cases"
                    )
                    
                    # Add new test case
                    gr.Markdown("### βž• Add New Test Case")
                    with gr.Row():
                        with gr.Column(scale=3):
                            new_message_text = gr.Textbox(
                                label="Message Text",
                                placeholder="Enter patient message...",
                                lines=3,
                                interactive=True
                            )
                        
                        with gr.Column(scale=1):
                            new_classification = gr.Radio(
                                choices=[
                                    ("🟒 GREEN - No Distress", "green"),
                                    ("🟑 YELLOW - Potential Distress", "yellow"),
                                    ("πŸ”΄ RED - Severe Distress", "red")
                                ],
                                label="Expected Classification",
                                value="green",
                                interactive=True
                            )
                    
                    with gr.Row():
                        add_test_case_btn = gr.Button("βž• Add Test Case", variant="primary", scale=2)
                        save_dataset_btn = gr.Button("πŸ’Ύ Save Dataset", variant="secondary", scale=1)
                        cancel_edit_btn = gr.Button("❌ Cancel", scale=1)
            
            # Verification interface (initially hidden)
            verification_section = gr.Row(visible=False)
            with verification_section:
                with gr.Column():
                    gr.Markdown("## πŸ” Dataset Verification")
                    
                    # Verification controls
                    with gr.Row():
                        with gr.Column(scale=2):
                            verifier_name_input = gr.Textbox(
                                label="Verifier Name",
                                placeholder="Enter your name...",
                                interactive=True
                            )
                        
                        with gr.Column(scale=1):
                            start_verification_btn = gr.Button(
                                "πŸš€ Start Verification",
                                variant="primary",
                                size="lg"
                            )
                    
                    # Progress display
                    verification_progress = gr.Markdown(
                        "Ready to start verification",
                        label="Progress"
                    )
                    
                    # Message review area (initially hidden)
                    message_review_area = gr.Row(visible=False)
                    with message_review_area:
                        with gr.Column(scale=2):
                            # Current message display
                            current_message_display = gr.Textbox(
                                label="πŸ“ Patient Message",
                                interactive=False,
                                lines=4
                            )
                            
                            # Classification results
                            classifier_decision_display = gr.Markdown(
                                "πŸ”„ Loading...",
                                label="🎯 Classifier Decision"
                            )
                            
                            classifier_confidence_display = gr.Markdown(
                                "Loading...",
                                label="πŸ“Š Confidence Level"
                            )
                            
                            classifier_indicators_display = gr.Markdown(
                                "Loading...",
                                label="πŸ” Detected Indicators"
                            )
                            
                            # Verification buttons
                            with gr.Row():
                                correct_classification_btn = gr.Button(
                                    "βœ“ Correct",
                                    variant="primary",
                                    scale=1
                                )
                                
                                incorrect_classification_btn = gr.Button(
                                    "βœ— Incorrect",
                                    variant="stop",
                                    scale=1
                                )
                            
                            # Correction section (initially hidden)
                            correction_section = gr.Row(visible=False)
                            with correction_section:
                                correction_selector = gr.Radio(
                                    choices=[
                                        ("🟒 Should be GREEN - No Distress", "green"),
                                        ("🟑 Should be YELLOW - Potential Distress", "yellow"),
                                        ("πŸ”΄ Should be RED - Severe Distress", "red")
                                    ],
                                    label="Correct Classification",
                                    interactive=True
                                )
                                
                                correction_notes = gr.Textbox(
                                    label="Notes (Optional)",
                                    placeholder="Why is this incorrect?",
                                    lines=2,
                                    interactive=True
                                )
                                
                                submit_correction_btn = gr.Button("βœ“ Submit", variant="primary")
                        
                        with gr.Column(scale=1):
                            # Session statistics
                            gr.Markdown("### πŸ“Š Session Statistics")
                            
                            session_stats_display = gr.Markdown(
                                """
                                **Messages Processed:** 0
                                **Correct Classifications:** 0
                                **Incorrect Classifications:** 0
                                **Accuracy:** 0%
                                """,
                                label="Statistics"
                            )
                            
                            # Export options
                            gr.Markdown("### πŸ’Ύ Export Options")
                            with gr.Column():
                                export_csv_btn = gr.Button("πŸ“„ Export CSV", size="sm")
                                export_json_btn = gr.Button("πŸ“‹ Export JSON", size="sm")
                                export_xlsx_btn = gr.Button("πŸ“Š Export XLSX", size="sm")
            
            # Status and error messages
            status_message = gr.Markdown("", visible=True)
            
            # Event handlers
            def initialize_interface():
                """Initialize the interface with datasets and templates."""
                dataset_choices, dataset_info, status_msg, templates = controller.initialize_interface()
                
                template_choices = [
                    f"{t['name']} - {t['description']}"
                    for t in templates
                ]
                
                return (
                    dataset_choices,  # dataset_selector choices
                    dataset_info,     # dataset_info_display
                    status_msg,       # status_message
                    template_choices  # template_selector choices
                )
            
            def on_dataset_selection_change(dataset_selection):
                """Handle dataset selection change."""
                dataset_info, dataset_obj = controller.get_dataset_info(dataset_selection)
                return (
                    dataset_info,     # dataset_info_display
                    dataset_obj       # current_dataset_state
                )
            
            def on_load_dataset(current_dataset):
                """Handle load dataset for verification."""
                if not current_dataset:
                    return (
                        gr.Row(visible=False),  # verification_section
                        "❌ No dataset selected"  # status_message
                    )
                
                return (
                    gr.Row(visible=True),   # verification_section
                    f"βœ… Dataset '{current_dataset.name}' loaded for verification"  # status_message
                )
            
            def on_edit_dataset(current_dataset):
                """Handle edit dataset."""
                if not current_dataset:
                    return (
                        gr.Row(visible=False),  # dataset_editing_section
                        "",  # edit_dataset_name
                        "",  # edit_dataset_description
                        "",  # test_cases_display
                        "❌ No dataset selected"  # status_message
                    )
                
                test_cases_html = controller.render_test_cases_display(current_dataset)
                
                return (
                    gr.Row(visible=True),       # dataset_editing_section
                    current_dataset.name,       # edit_dataset_name
                    current_dataset.description, # edit_dataset_description
                    test_cases_html,            # test_cases_display
                    f"βœ… Editing dataset '{current_dataset.name}'"  # status_message
                )
            
            def on_create_new():
                """Handle create new dataset."""
                return (
                    gr.Row(visible=True),  # dataset_creation_section
                    "✨ Create a new dataset"  # status_message
                )
            
            def on_create_dataset(name, description, template_selection):
                """Handle dataset creation."""
                # Parse template type from selection
                template_type = None
                if template_selection:
                    # Extract template type from selection string
                    template_mapping = {
                        "πŸ“ Empty Dataset": "empty",
                        "🎯 Sample Mixed Dataset": "sample_mixed",
                        "🟒 Custom Green Messages": "custom_green",
                        "🟑 Custom Yellow Messages": "custom_yellow",
                        "πŸ”΄ Custom Red Messages": "custom_red"
                    }
                    
                    for key, value in template_mapping.items():
                        if template_selection.startswith(key):
                            template_type = value
                            break
                
                success, message, dataset = controller.create_new_dataset(name, description, template_type)
                
                if success:
                    # Refresh dataset list
                    dataset_choices, _, _, _ = controller.initialize_interface()
                    
                    return (
                        gr.Row(visible=False),  # dataset_creation_section
                        dataset_choices,        # dataset_selector choices
                        dataset,               # current_dataset_state
                        message                # status_message
                    )
                else:
                    return (
                        gr.Row(visible=True),   # dataset_creation_section (keep visible)
                        gr.Dropdown(choices=[]), # dataset_selector (no change)
                        None,                   # current_dataset_state
                        message                 # status_message
                    )
            
            def on_add_test_case(current_dataset, message_text, classification):
                """Handle adding new test case."""
                if not current_dataset:
                    return (
                        None,  # current_dataset_state
                        "",    # test_cases_display
                        "",    # new_message_text (clear)
                        "❌ No dataset selected"  # status_message
                    )
                
                success, message, updated_dataset = controller.add_test_case(
                    current_dataset, message_text, classification
                )
                
                if success:
                    test_cases_html = controller.render_test_cases_display(updated_dataset)
                    return (
                        updated_dataset,  # current_dataset_state
                        test_cases_html,  # test_cases_display
                        "",              # new_message_text (clear)
                        message          # status_message
                    )
                else:
                    return (
                        current_dataset,  # current_dataset_state (no change)
                        gr.HTML(value=""), # test_cases_display (no change)
                        message_text,     # new_message_text (keep)
                        message          # status_message
                    )
            
            def on_save_dataset(current_dataset):
                """Handle saving dataset."""
                if not current_dataset:
                    return "❌ No dataset to save"
                
                success, message = controller.save_dataset(current_dataset)
                return message
            
            def on_start_verification(current_dataset, verifier_name):
                """Handle starting verification session."""
                if not current_dataset:
                    return (
                        None,  # verification_session_state
                        gr.Row(visible=False),  # message_review_area
                        "❌ No dataset selected"  # status_message
                    )
                
                success, message, session = controller.start_verification_session(
                    current_dataset, verifier_name
                )
                
                if success:
                    # Load first message
                    current_message, classification_result = controller.get_current_message_for_verification()
                    
                    if current_message:
                        # Format classification results
                        decision_badge = f"🎯 {classification_result.get('decision', 'Unknown').upper()}"
                        confidence_text = f"πŸ“Š {classification_result.get('confidence', 0) * 100:.1f}% confident"
                        indicators_text = "πŸ” " + ", ".join(classification_result.get('indicators', ['No indicators']))
                        
                        return (
                            session,                    # verification_session_state
                            gr.Row(visible=True),       # message_review_area
                            current_message.text,       # current_message_display
                            decision_badge,             # classifier_decision_display
                            confidence_text,            # classifier_confidence_display
                            indicators_text,            # classifier_indicators_display
                            f"Progress: 1 of {len(current_dataset.messages)} messages",  # verification_progress
                            message                     # status_message
                        )
                    else:
                        return (
                            session,                    # verification_session_state
                            gr.Row(visible=False),      # message_review_area
                            "",                         # current_message_display
                            "",                         # classifier_decision_display
                            "",                         # classifier_confidence_display
                            "",                         # classifier_indicators_display
                            "No messages to verify",    # verification_progress
                            "❌ No messages in dataset"  # status_message
                        )
                else:
                    return (
                        None,                       # verification_session_state
                        gr.Row(visible=False),      # message_review_area
                        "",                         # current_message_display
                        "",                         # classifier_decision_display
                        "",                         # classifier_confidence_display
                        "",                         # classifier_indicators_display
                        "",                         # verification_progress
                        message                     # status_message
                    )
            
            def on_correct_classification():
                """Handle correct classification feedback."""
                success, message, stats = controller.submit_verification_feedback(True)
                
                if success and not stats.get('is_complete', False):
                    # Load next message
                    current_message, classification_result = controller.get_current_message_for_verification()
                    
                    if current_message:
                        decision_badge = f"🎯 {classification_result.get('decision', 'Unknown').upper()}"
                        confidence_text = f"πŸ“Š {classification_result.get('confidence', 0) * 100:.1f}% confident"
                        indicators_text = "πŸ” " + ", ".join(classification_result.get('indicators', ['No indicators']))
                        
                        stats_text = f"""
**Messages Processed:** {stats['processed']}
**Correct Classifications:** {stats['correct']}
**Incorrect Classifications:** {stats['incorrect']}
**Accuracy:** {stats['accuracy']:.1f}%
"""
                        
                        return (
                            current_message.text,       # current_message_display
                            decision_badge,             # classifier_decision_display
                            confidence_text,            # classifier_confidence_display
                            indicators_text,            # classifier_indicators_display
                            f"Progress: {stats['processed'] + 1} of {stats['total']} messages",  # verification_progress
                            stats_text,                 # session_stats_display
                            gr.Row(visible=False),      # correction_section
                            message                     # status_message
                        )
                    else:
                        # Session complete
                        stats_text = f"""
**Session Complete!**
**Messages Processed:** {stats['processed']}
**Correct Classifications:** {stats['correct']}
**Incorrect Classifications:** {stats['incorrect']}
**Final Accuracy:** {stats['accuracy']:.1f}%
"""
                        return (
                            "Session completed!",       # current_message_display
                            "βœ… All messages verified", # classifier_decision_display
                            "",                         # classifier_confidence_display
                            "",                         # classifier_indicators_display
                            "βœ… Verification complete", # verification_progress
                            stats_text,                 # session_stats_display
                            gr.Row(visible=False),      # correction_section
                            message                     # status_message
                        )
                else:
                    return (
                        gr.Textbox(value=""),       # current_message_display (no change)
                        gr.Markdown(value=""),      # classifier_decision_display (no change)
                        gr.Markdown(value=""),      # classifier_confidence_display (no change)
                        gr.Markdown(value=""),      # classifier_indicators_display (no change)
                        gr.Markdown(value=""),      # verification_progress (no change)
                        gr.Markdown(value=""),      # session_stats_display (no change)
                        gr.Row(visible=False),      # correction_section
                        message                     # status_message
                    )
            
            def on_incorrect_classification():
                """Handle incorrect classification - show correction options."""
                return (
                    gr.Row(visible=True),  # correction_section
                    "Please select the correct classification"  # status_message
                )
            
            def on_submit_correction(correction, notes):
                """Handle correction submission."""
                success, message, stats = controller.submit_verification_feedback(
                    False, correction, notes
                )
                
                if success and not stats.get('is_complete', False):
                    # Load next message
                    current_message, classification_result = controller.get_current_message_for_verification()
                    
                    if current_message:
                        decision_badge = f"🎯 {classification_result.get('decision', 'Unknown').upper()}"
                        confidence_text = f"πŸ“Š {classification_result.get('confidence', 0) * 100:.1f}% confident"
                        indicators_text = "πŸ” " + ", ".join(classification_result.get('indicators', ['No indicators']))
                        
                        stats_text = f"""
**Messages Processed:** {stats['processed']}
**Correct Classifications:** {stats['correct']}
**Incorrect Classifications:** {stats['incorrect']}
**Accuracy:** {stats['accuracy']:.1f}%
"""
                        
                        return (
                            current_message.text,       # current_message_display
                            decision_badge,             # classifier_decision_display
                            confidence_text,            # classifier_confidence_display
                            indicators_text,            # classifier_indicators_display
                            f"Progress: {stats['processed'] + 1} of {stats['total']} messages",  # verification_progress
                            stats_text,                 # session_stats_display
                            gr.Row(visible=False),      # correction_section
                            "",                         # correction_notes (clear)
                            message                     # status_message
                        )
                    else:
                        # Session complete
                        stats_text = f"""
**Session Complete!**
**Messages Processed:** {stats['processed']}
**Correct Classifications:** {stats['correct']}
**Incorrect Classifications:** {stats['incorrect']}
**Final Accuracy:** {stats['accuracy']:.1f}%
"""
                        return (
                            "Session completed!",       # current_message_display
                            "βœ… All messages verified", # classifier_decision_display
                            "",                         # classifier_confidence_display
                            "",                         # classifier_indicators_display
                            "βœ… Verification complete", # verification_progress
                            stats_text,                 # session_stats_display
                            gr.Row(visible=False),      # correction_section
                            "",                         # correction_notes (clear)
                            message                     # status_message
                        )
                else:
                    return (
                        gr.Textbox(value=""),       # current_message_display (no change)
                        gr.Markdown(value=""),      # classifier_decision_display (no change)
                        gr.Markdown(value=""),      # classifier_confidence_display (no change)
                        gr.Markdown(value=""),      # classifier_indicators_display (no change)
                        gr.Markdown(value=""),      # verification_progress (no change)
                        gr.Markdown(value=""),      # session_stats_display (no change)
                        gr.Row(visible=True),       # correction_section (keep visible)
                        notes,                      # correction_notes (keep)
                        message                     # status_message
                    )
            
            def on_export_results(format_type):
                """Handle results export."""
                success, message, file_path = controller.export_session_results(format_type)
                return message
            
            # Bind event handlers
            enhanced_dataset_interface.load(
                initialize_interface,
                outputs=[
                    dataset_selector,
                    dataset_info_display,
                    status_message,
                    template_selector
                ]
            )
            
            dataset_selector.change(
                on_dataset_selection_change,
                inputs=[dataset_selector],
                outputs=[dataset_info_display, current_dataset_state]
            )
            
            load_dataset_btn.click(
                on_load_dataset,
                inputs=[current_dataset_state],
                outputs=[verification_section, status_message]
            )
            
            edit_dataset_btn.click(
                on_edit_dataset,
                inputs=[current_dataset_state],
                outputs=[
                    dataset_editing_section,
                    edit_dataset_name,
                    edit_dataset_description,
                    test_cases_display,
                    status_message
                ]
            )
            
            create_new_btn.click(
                on_create_new,
                outputs=[dataset_creation_section, status_message]
            )
            
            create_dataset_btn.click(
                on_create_dataset,
                inputs=[new_dataset_name, new_dataset_description, template_selector],
                outputs=[
                    dataset_creation_section,
                    dataset_selector,
                    current_dataset_state,
                    status_message
                ]
            )
            
            cancel_create_btn.click(
                lambda: (gr.Row(visible=False), "❌ Dataset creation cancelled"),
                outputs=[dataset_creation_section, status_message]
            )
            
            add_test_case_btn.click(
                on_add_test_case,
                inputs=[current_dataset_state, new_message_text, new_classification],
                outputs=[
                    current_dataset_state,
                    test_cases_display,
                    new_message_text,
                    status_message
                ]
            )
            
            save_dataset_btn.click(
                on_save_dataset,
                inputs=[current_dataset_state],
                outputs=[status_message]
            )
            
            cancel_edit_btn.click(
                lambda: (gr.Row(visible=False), "❌ Dataset editing cancelled"),
                outputs=[dataset_editing_section, status_message]
            )
            
            start_verification_btn.click(
                on_start_verification,
                inputs=[current_dataset_state, verifier_name_input],
                outputs=[
                    verification_session_state,
                    message_review_area,
                    current_message_display,
                    classifier_decision_display,
                    classifier_confidence_display,
                    classifier_indicators_display,
                    verification_progress,
                    status_message
                ]
            )
            
            correct_classification_btn.click(
                on_correct_classification,
                outputs=[
                    current_message_display,
                    classifier_decision_display,
                    classifier_confidence_display,
                    classifier_indicators_display,
                    verification_progress,
                    session_stats_display,
                    correction_section,
                    status_message
                ]
            )
            
            incorrect_classification_btn.click(
                on_incorrect_classification,
                outputs=[correction_section, status_message]
            )
            
            submit_correction_btn.click(
                on_submit_correction,
                inputs=[correction_selector, correction_notes],
                outputs=[
                    current_message_display,
                    classifier_decision_display,
                    classifier_confidence_display,
                    classifier_indicators_display,
                    verification_progress,
                    session_stats_display,
                    correction_section,
                    correction_notes,
                    status_message
                ]
            )
            
            export_csv_btn.click(
                lambda: on_export_results("csv"),
                outputs=[status_message]
            )
            
            export_json_btn.click(
                lambda: on_export_results("json"),
                outputs=[status_message]
            )
            
            export_xlsx_btn.click(
                lambda: on_export_results("xlsx"),
                outputs=[status_message]
            )
        
        return enhanced_dataset_interface