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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
"""
๐ŸŽจ Gradio Application for Course Creator AI

Main Gradio interface for course generation.
"""

import gradio as gr
from typing import Dict, Any, Optional, Tuple
import asyncio
import json
import markdown
import re

from ..agents.simple_course_agent import SimpleCourseAgent
from ..types import DifficultyLevel, GenerationOptions, LearningStyle
from .components import CoursePreview
from .styling import get_custom_css


def format_lessons(lessons: list) -> str:
    """Format lessons from JSON data into HTML with dark theme and markdown support"""
    if not lessons:
        return "<div class='info'>๐Ÿ“š No lessons generated yet.</div>"

    # Add CSS for lesson styling
    css = """
    <style>
    /* Force dark theme for all lesson elements */
    .lessons-container * {
        background: transparent !important;
        color: inherit !important;
    }

    .lessons-container {
        padding: 1rem !important;
        background: #1a1a2e !important;
        border-radius: 12px !important;
        margin: 1rem 0 !important;
        max-height: none !important;
        overflow: visible !important;
    }

    .lesson-card {
        background: #2d2d54 !important;
        border: 1px solid #4a4a7a !important;
        border-radius: 12px !important;
        padding: 2rem !important;
        margin: 1.5rem 0 !important;
        box-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;
        color: #e0e7ff !important;
    }

    .lesson-card h3 {
        color: #667eea !important;
        margin-bottom: 1rem !important;
        font-size: 1.5rem !important;
        border-bottom: 2px solid #667eea !important;
        padding-bottom: 0.5rem !important;
        background: transparent !important;
    }

    .lesson-card h4 {
        color: #8b9dc3 !important;
        margin: 1.5rem 0 0.75rem 0 !important;
        font-size: 1.2rem !important;
        background: transparent !important;
    }

    .lesson-card p {
        color: #b8c5d6 !important;
        line-height: 1.6 !important;
        margin: 0.75rem 0 !important;
        font-size: 1rem !important;
        background: transparent !important;
    }

    .lesson-card ul {
        color: #e0e7ff !important;
        margin: 0.75rem 0 !important;
        padding-left: 1.5rem !important;
        background: transparent !important;
    }

    .lesson-card li {
        color: #e0e7ff !important;
        margin: 0.5rem 0 !important;
        line-height: 1.5 !important;
        background: transparent !important;
    }

    .lesson-content {
        background: #3a3a6b !important;
        border-radius: 8px !important;
        padding: 1.5rem !important;
        margin: 1rem 0 !important;
        border-left: 4px solid #667eea !important;
    }

    .lesson-content h1, .lesson-content h2, .lesson-content h3,
    .lesson-content h4, .lesson-content h5, .lesson-content h6 {
        color: #667eea !important;
        margin: 1rem 0 0.5rem 0 !important;
        background: transparent !important;
    }

    .lesson-content p {
        color: #e0e7ff !important;
        margin: 0.75rem 0 !important;
        line-height: 1.6 !important;
        background: transparent !important;
    }

    .lesson-content ul, .lesson-content ol {
        color: #e0e7ff !important;
        margin: 0.75rem 0 !important;
        padding-left: 1.5rem !important;
        background: transparent !important;
    }

    .lesson-content li {
        color: #e0e7ff !important;
        margin: 0.5rem 0 !important;
        background: transparent !important;
    }

    .lesson-content strong {
        color: #8b9dc3 !important;
    }

    .lesson-content em {
        color: #b8c5d6 !important;
    }

    .lesson-content code {
        background: #4a4a7a !important;
        color: #e0e7ff !important;
        padding: 0.2rem 0.4rem;
        border-radius: 4px;
        font-family: monospace;
    }

    .lesson-content pre {
        background: #4a4a7a !important;
        color: #e0e7ff !important;
        padding: 1rem;
        border-radius: 8px;
        overflow-x: auto;
        margin: 1rem 0;
    }

    .lesson-card ul {
        color: #e0e7ff !important;
        margin: 0.75rem 0;
        padding-left: 1.5rem;
    }

    .lesson-card li {
        color: #e0e7ff !important;
        margin: 0.5rem 0;
        line-height: 1.5;
    }

    .lesson-image {
        margin: 1.5rem 0;
        text-align: center;
    }

    .image-placeholder {
        background: #4a4a7a;
        border: 2px dashed #667eea;
        border-radius: 8px;
        padding: 2rem;
        text-align: center;
        color: #b8c5d6;
    }

    .image-icon {
        font-size: 3rem;
        margin-bottom: 1rem;
    }

    .image-description {
        font-size: 1.1rem;
        margin-bottom: 0.5rem;
        color: #e0e7ff;
    }

    .image-note {
        font-size: 0.9rem;
        font-style: italic;
        opacity: 0.7;
    }

    .duration-info {
        background: #4a4a7a !important;
        color: #e0e7ff !important;
        padding: 0.5rem 1rem !important;
        border-radius: 20px !important;
        display: inline-block !important;
        margin-bottom: 1rem !important;
        font-size: 0.9rem !important;
    }

    /* Ultimate override for any stubborn white backgrounds */
    .lessons-container .lesson-card,
    .lessons-container .lesson-card *,
    .lessons-container .lesson-content,
    .lessons-container .lesson-content * {
        background-color: transparent !important;
    }

    .lessons-container .lesson-card {
        background: #2d2d54 !important;
    }

    .lessons-container .lesson-content {
        background: #3a3a6b !important;
    }
    </style>
    """

    html = css + "<div class='lessons-container'>"
    for i, lesson in enumerate(lessons, 1):
        title = lesson.get("title", f"Lesson {i}")
        content = lesson.get("content", "")
        duration = lesson.get("duration", "")
        objectives = lesson.get("objectives", [])
        key_takeaways = lesson.get("key_takeaways", [])
        image_description = lesson.get("image_description", "")

        # Convert markdown content to HTML
        if content:
            try:
                # Create markdown instance with extensions
                import markdown
                md = markdown.Markdown(extensions=['extra', 'codehilite'])
                content_html = md.convert(content)
            except ImportError:
                # Fallback if markdown is not available
                content_html = content.replace('\n\n', '</p><p>').replace('\n', '<br>')
                if content_html and not content_html.startswith('<p>'):
                    content_html = f'<p>{content_html}</p>'
        else:
            content_html = "<p>No content available.</p>"

        # Generate image placeholder or actual image
        image_html = ""
        if image_description:
            # Check if we have actual image data
            images = lesson.get("images", [])
            if images and len(images) > 0:
                # Display actual generated images
                image_html = "<div class='lesson-images'>"
                for img in images:
                    if isinstance(img, dict) and img.get("url"):
                        img_url = img.get("url", "")
                        img_caption = img.get("description", image_description)
                        image_html += f"""
                        <div class='lesson-image'>
                            <img src='{img_url}' alt='{img_caption}' loading='lazy' style='max-width: 100%; border-radius: 8px; box-shadow: 0 4px 8px rgba(0,0,0,0.3); border: 2px solid #4a4a7a;'>
                            <p class='image-caption'>{img_caption}</p>
                        </div>
                        """
                image_html += "</div>"
            else:
                # Fallback to placeholder
                image_html = f"""
                <div class='lesson-image'>
                    <div class='image-placeholder'>
                        <div class='image-icon'>๐Ÿ–ผ๏ธ</div>
                        <div class='image-description'>{image_description}</div>
                        <div class='image-note'>(Image generation in progress...)</div>
                    </div>
                </div>
                """

        html += f"""
        <div class='lesson-card'>
            <h3>๐Ÿ“– {title}</h3>
            {f"<div class='duration-info'>โฑ๏ธ Duration: {duration} minutes</div>" if duration else ""}

            {f"<h4>๐ŸŽฏ Learning Objectives:</h4><ul>{''.join([f'<li>{obj}</li>' for obj in objectives])}</ul>" if objectives else ""}

            {image_html}

            <div class='lesson-content'>
                {content_html}
            </div>

            {f"<h4>๐Ÿ’ก Key Takeaways:</h4><ul>{''.join([f'<li>{takeaway}</li>' for takeaway in key_takeaways])}</ul>" if key_takeaways else ""}
        </div>
        """
    html += "</div>"
    return html


def format_flashcards(flashcards: list) -> str:
    """Format flashcards from JSON data into interactive HTML with CSS-only flip"""
    if not flashcards:
        return "<div class='info'>๐Ÿƒ No flashcards generated yet.</div>"

    # Add the CSS for flashcard flip functionality
    css = """
    <style>
    .flashcards-container {
        padding: 1rem;
        background: #1a1a2e;
        border-radius: 12px;
        margin: 1rem 0;
        max-height: none !important;
        overflow: visible !important;
    }

    .flashcard-wrapper {
        perspective: 1000px;
        margin: 1rem 0;
        height: 200px;
    }

    .flip-checkbox {
        display: none;
    }

    .flashcard {
        position: relative;
        width: 100%;
        height: 100%;
        cursor: pointer;
        transform-style: preserve-3d;
        transition: transform 0.6s;
        display: block;
    }

    .flip-checkbox:checked + .flashcard {
        transform: rotateY(180deg);
    }

    .flashcard-inner {
        position: relative;
        width: 100%;
        height: 100%;
        transform-style: preserve-3d;
    }

    .flashcard-front, .flashcard-back {
        position: absolute;
        width: 100%;
        height: 100%;
        backface-visibility: hidden;
        border-radius: 12px;
        padding: 1.5rem;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        text-align: center;
        box-shadow: 0 4px 8px rgba(0,0,0,0.3);
    }

    .flashcard-front {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .flashcard-back {
        background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
        color: white;
        transform: rotateY(180deg);
    }

    .flashcard-category {
        position: absolute;
        top: 10px;
        right: 15px;
        background: rgba(255,255,255,0.2);
        padding: 0.25rem 0.5rem;
        border-radius: 12px;
        font-size: 0.8rem;
        font-weight: bold;
    }

    .flashcard-content {
        font-size: 1.2rem;
        font-weight: 500;
        line-height: 1.4;
        margin: 1rem 0;
        color: white;
    }

    .flashcard-hint {
        position: absolute;
        bottom: 10px;
        left: 50%;
        transform: translateX(-50%);
        font-size: 0.8rem;
        opacity: 0.8;
        font-style: italic;
    }

    .flashcard:hover {
        box-shadow: 0 6px 12px rgba(0,0,0,0.4);
    }
    </style>
    """

    html = css + "<div class='flashcards-container'>"
    html += "<p style='color: #e0e7ff; text-align: center; margin-bottom: 1rem;'><strong>๐Ÿƒ Click on any flashcard to flip it and see the answer!</strong></p>"

    for i, card in enumerate(flashcards):
        question = card.get("question", "")
        answer = card.get("answer", "")
        category = card.get("category", "General")

        # Use CSS-only flip with checkbox hack
        html += f"""
        <div class='flashcard-wrapper'>
            <input type='checkbox' id='flip-{i}' class='flip-checkbox'>
            <label for='flip-{i}' class='flashcard'>
                <div class='flashcard-inner'>
                    <div class='flashcard-front'>
                        <div class='flashcard-category'>{category}</div>
                        <div class='flashcard-content'>{question}</div>
                        <div class='flashcard-hint'>Click to flip</div>
                    </div>
                    <div class='flashcard-back'>
                        <div class='flashcard-category'>{category}</div>
                        <div class='flashcard-content'>{answer}</div>
                        <div class='flashcard-hint'>Click to flip back</div>
                    </div>
                </div>
            </label>
        </div>
        """

    html += "</div>"
    return html


def format_quiz(quiz: dict) -> str:
    """Format quiz from JSON data into interactive HTML with working JavaScript."""
    if not quiz or not quiz.get("questions"):
        return "<div class='info'>๐Ÿ“ No quiz generated yet.</div>"

    title = quiz.get("title", "Course Quiz")
    instructions = quiz.get("instructions", "Choose the best answer for each question.")
    questions = quiz.get("questions", [])
    
    if not questions:
        return "<div class='info'>๐Ÿ“ No quiz questions available.</div>"

    # Generate unique quiz ID
    quiz_id = f"quiz_{abs(hash(str(questions)))%10000}"

    # CSS and JavaScript for quiz functionality
    quiz_html = f"""
    <style>
      .quiz-container {{ 
        background: #1a1a2e; 
        border-radius: 12px; 
        padding: 2rem; 
        color: #e0e7ff; 
        max-height: none !important; 
        overflow: visible !important; 
      }}
      .quiz-container h3 {{ 
        color: #667eea; 
        text-align: center; 
        margin-bottom: 1rem;
      }}
      .quiz-question {{ 
        background: #2d2d54; 
        border-radius: 8px; 
        padding: 1.5rem; 
        margin: 1.5rem 0; 
        border-left: 4px solid #667eea;
      }}
      .quiz-question h4 {{ 
        color: #e0e7ff; 
        margin-bottom: 1rem; 
        font-size: 1.1rem;
      }}
      .quiz-options {{ 
        margin: 1rem 0; 
      }}
      .quiz-option-label {{ 
        display: flex; 
        align-items: center; 
        padding: 0.75rem 1rem;
        background: #3a3a6b; 
        border: 2px solid #4a4a7a; 
        border-radius: 8px;
        margin: 0.5rem 0;
        cursor: pointer; 
        color: #e0e7ff; 
        transition: all 0.2s;
      }}
      .quiz-option-label:hover {{ 
        background: #4a4a7a; 
        border-color: #667eea;
      }}
      .quiz-radio {{ 
        display: none; 
      }}
      .quiz-radio:checked + .quiz-option-label {{ 
        background: #667eea; 
        color: white; 
        border-color: #667eea;
      }}
      .radio-custom {{ 
        width: 20px; 
        height: 20px; 
        border: 2px solid #667eea; 
        border-radius: 50%; 
        margin-right: 0.75rem;
        position: relative;
      }}
      .quiz-radio:checked + .quiz-option-label .radio-custom::after {{
        content: '';
        width: 10px;
        height: 10px;
        border-radius: 50%;
        background: white;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
      }}
      .quiz-feedback {{ 
        margin-top: 1rem; 
        padding: 1rem; 
        border-radius: 6px; 
        font-weight: 500;
        display: none;
      }}
      .feedback-correct {{ 
        background: #d4edda; 
        color: #155724; 
        border: 1px solid #c3e6cb;
      }}
      .feedback-incorrect {{ 
        background: #f8d7da; 
        color: #721c24; 
        border: 1px solid #f5c6cb;
      }}
      .feedback-unanswered {{ 
        background: #fff3cd; 
        color: #856404; 
        border: 1px solid #ffeaa7;
      }}
      .quiz-results {{ 
        margin-top: 2rem; 
        padding: 1.5rem; 
        background: linear-gradient(135deg, #667eea, #764ba2); 
        color: white; 
        border-radius: 8px; 
        text-align: center;
        font-size: 1.1rem;
        display: none;
      }}
      .quiz-score {{ 
        font-size: 1.5rem; 
        font-weight: bold; 
        margin-bottom: 0.5rem;
      }}
    </style>

    <div class="quiz-container" id="{quiz_id}">
      <h3>๐Ÿ“ {title}</h3>
      <p style="text-align:center; color:#b8c5d6; margin-bottom: 2rem;"><em>{instructions}</em></p>
      <form id="quiz-form-{quiz_id}">
    """

    # Display each question
    for idx, q in enumerate(questions):
        question_text = q.get("question", "")
        options = q.get("options", [])
        correct_answer = q.get("correct_answer", "A")
        explanation = q.get("explanation", "")

        quiz_html += f"""
        <div class="quiz-question" data-correct="{correct_answer}" data-explanation="{explanation}">
          <h4>Q{idx+1}: {question_text}</h4>
          <div class="quiz-options">
        """
        
        # Display options
        for j, option in enumerate(options):
            option_letter = option[0] if option and len(option) > 0 else chr(65 + j)
            option_text = option[3:] if option.startswith(f"{option_letter}. ") else option
            
            quiz_html += f"""
            <div>
              <input type="radio" id="q{idx}_o{j}_{quiz_id}" name="q{idx}" value="{option_letter}" class="quiz-radio">
              <label for="q{idx}_o{j}_{quiz_id}" class="quiz-option-label">
                <span class="radio-custom"></span>
                <strong>{option_letter}.</strong>&nbsp;&nbsp;{option_text}
              </label>
            </div>
            """
        
        quiz_html += f"""
          </div>
          <div class="quiz-feedback" id="feedback-{idx}-{quiz_id}"></div>
        </div>
        """
    
    # Close form and add results container
    quiz_html += f"""
      </form>
    </div>


    """
    
    return quiz_html


def create_coursecrafter_interface() -> gr.Blocks:
    """Create the main Course Creator Gradio interface"""

    with gr.Blocks(
        title="Course Creator AI - Intelligent Course Generator",
        css=get_custom_css(),
        theme=gr.themes.Soft()
    ) as interface:

        # Header
        gr.HTML("""
        <div class="header-container">
            <h1>๐ŸŽ“ Course Creator AI</h1>
            <p>Generate comprehensive mini-courses with AI-powered content, flashcards, and quizzes</p>
        </div>
        """)

        # LLM Provider Configuration
        with gr.Row():
            with gr.Column():
                gr.HTML("<h3>๐Ÿค– LLM Provider Configuration</h3>")
                with gr.Row():
                    llm_provider = gr.Dropdown(
                        label="LLM Provider",
                        choices=["openai", "anthropic", "google", "openai_compatible"],
                        value="google",
                        info="Choose your preferred LLM provider"
                    )
                    api_key_input = gr.Textbox(
                        label="API Key",
                        placeholder="Enter your API key here...",
                        type="password",
                        info="Your API key for the selected provider (optional for OpenAI-compatible)"
                    )
                
                # OpenAI-Compatible endpoint configuration (initially hidden)
                with gr.Row(visible=False) as openai_compatible_row:
                    endpoint_url_input = gr.Textbox(
                        label="Endpoint URL",
                        placeholder="https://your-endpoint.com/v1",
                        info="Base URL for OpenAI-compatible API"
                    )
                    model_name_input = gr.Textbox(
                        label="Model Name",
                        placeholder="your-model-name",
                        info="Model name to use with the endpoint"
                    )

        # Main interface
        with gr.Row():
            with gr.Column(scale=1):
                # Course generation form
                topic_input = gr.Textbox(
                    label="Course Topic",
                    placeholder="e.g., Introduction to Python Programming",
                    lines=1
                )

                difficulty_input = gr.Dropdown(
                    label="Difficulty Level",
                    choices=["beginner", "intermediate", "advanced"],
                    value="beginner"
                )

                lesson_count = gr.Slider(
                    label="Number of Lessons",
                    minimum=1,
                    maximum=10,
                    value=5,
                    step=1
                )

                generate_btn = gr.Button(
                    "๐Ÿš€ Generate Course",
                    variant="primary",
                    size="lg"
                )

                # Chat interface for course refinement
                gr.HTML("<hr><h3>๐Ÿ’ฌ Course Assistant</h3>")

                # Chat window with proper styling
                with gr.Column():
                    chat_display = gr.HTML(
                        value="""
                        <div class='chat-window'>
                            <div class='chat-messages' id='chat-messages'>
                                <div class='chat-message assistant-message'>
                                    <div class='message-avatar'>๐Ÿค–</div>
                                    <div class='message-content'>
                                        <div class='message-text'>Hi! I'm your Course Assistant. Generate a course first, then ask me questions about the lessons, concepts, or content!</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        """,
                        elem_id="chat-display"
                    )

                    with gr.Row():
                        chat_input = gr.Textbox(
                            placeholder="Ask me to modify the course...",
                            lines=1,
                            scale=4,
                            container=False
                        )
                        chat_btn = gr.Button("Send", variant="secondary", scale=1)

            with gr.Column(scale=2):
                # Course preview tabs with enhanced components
                course_preview = CoursePreview()

                with gr.Tabs():
                    with gr.Tab("๐Ÿ“– Lessons"):
                        lessons_output = gr.HTML(
                            value="""
                            <div class='lessons-container' style='padding: 2rem; text-align: center; background: #1a1a2e; border-radius: 12px; color: #e0e7ff;'>
                                <h3 style='color: #667eea; margin-bottom: 1rem;'>๐ŸŽ“ Ready to Generate Your Course!</h3>
                                <p style='color: #b8c5d6; font-size: 1.1rem; margin-bottom: 1.5rem;'>Enter a topic and click "Generate Course" to create comprehensive lessons with AI-powered content.</p>
                                <div style='background: #2d2d54; padding: 1.5rem; border-radius: 8px; border-left: 4px solid #667eea;'>
                                    <p style='color: #e0e7ff; margin: 0;'>๐Ÿ’ก <strong>Tip:</strong> Try topics like "Introduction to Python Programming", "Digital Marketing Basics", or "Climate Change Science"</p>
                                </div>
                            </div>
                            """
                        )

                    with gr.Tab("๐Ÿƒ Flashcards"):
                        flashcards_output = gr.HTML(
                            value="""
                            <div class='flashcards-container' style='padding: 2rem; text-align: center; background: #1a1a2e; border-radius: 12px; color: #e0e7ff;'>
                                <h3 style='color: #667eea; margin-bottom: 1rem;'>๐Ÿƒ Interactive Flashcards</h3>
                                <p style='color: #b8c5d6;'>Flashcards will appear here after course generation. They'll help reinforce key concepts with spaced repetition learning!</p>
                            </div>
                            """
                        )

                    with gr.Tab("๐Ÿ“ Quizzes"):
                        # Quiz functionality with HTML content and state management
                        quiz_state = gr.State({})  # Store quiz data
                        quizzes_output = gr.HTML(
                            value="""
                            <div class='quiz-container' style='padding: 2rem; text-align: center; background: #1a1a2e; border-radius: 12px; color: #e0e7ff;'>
                                <h3 style='color: #667eea; margin-bottom: 1rem;'>๐Ÿ“ Knowledge Assessment</h3>
                                <p style='color: #b8c5d6;'>Interactive quizzes will appear here to test your understanding of the course material!</p>
                            </div>
                            """
                        )
                        quiz_results = gr.HTML(visible=False)
                        quiz_submit_btn = gr.Button("Submit Quiz", variant="primary", visible=False)

                    with gr.Tab("๐ŸŽจ Images"):
                        images_section = course_preview._create_images_section()
                        image_gallery = images_section["image_gallery"]
                        image_details = images_section["image_details"]

        # Store generated course content for chat context
        course_context = {"content": "", "topic": "", "agent": None}

        # Provider change handler to show/hide OpenAI-compatible fields
        def on_provider_change(provider):
            if provider == "openai_compatible":
                return gr.update(visible=True)
            else:
                return gr.update(visible=False)

        # Event handlers
        async def generate_course_wrapper(topic: str, difficulty: str, lessons: int, provider: str, api_key: str, endpoint_url: str, model_name: str, progress=gr.Progress()):
            """Wrapper for course generation with progress tracking"""
            if not topic.strip():
                return (
                    "<div class='error'>โŒ Please enter a topic for your course.</div>",
                    "", "", 
                    gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                )

            if not api_key.strip() and provider != "openai_compatible":
                return (
                    "<div class='error'>โŒ Please enter your API key for the selected LLM provider.</div>",
                    "", "", 
                    gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                )
            
            if provider == "openai_compatible" and not endpoint_url.strip():
                return (
                    "<div class='error'>โŒ Please enter the endpoint URL for OpenAI-compatible provider.</div>",
                    "", "", 
                    gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                )
            
            if provider == "openai_compatible" and not model_name.strip():
                return (
                    "<div class='error'>โŒ Please enter the model name for OpenAI-compatible provider.</div>",
                    "", "", 
                    gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                )

            try:
                # Initialize progress
                progress(0, desc="๐Ÿš€ Initializing Course Generator...")
                
                # Set the API key and configuration for the selected provider
                import os
                if provider == "openai":
                    os.environ["OPENAI_API_KEY"] = api_key
                elif provider == "anthropic":
                    os.environ["ANTHROPIC_API_KEY"] = api_key
                elif provider == "google":
                    os.environ["GOOGLE_API_KEY"] = api_key
                elif provider == "openai_compatible":
                    if api_key.strip():
                        os.environ["OPENAI_COMPATIBLE_API_KEY"] = api_key
                    os.environ["OPENAI_COMPATIBLE_BASE_URL"] = endpoint_url
                    os.environ["OPENAI_COMPATIBLE_MODEL"] = model_name
                
                # IMPORTANT: Create a fresh agent instance to pick up the new environment variables
                # This ensures the LlmClient reinitializes with the updated API keys
                agent = SimpleCourseAgent()
                
                # Use the new dynamic configuration method to update provider settings
                config_kwargs = {}
                if provider == "openai_compatible":
                    config_kwargs["base_url"] = endpoint_url
                    config_kwargs["model"] = model_name
                
                # Update provider configuration dynamically
                config_success = agent.update_provider_config(provider, api_key, **config_kwargs)
                if not config_success:
                    return (
                        f"<div class='error'>โŒ Failed to configure provider '{provider}'. Please check your API key and settings.</div>",
                        "", "", 
                        gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                    )
                
                course_context["agent"] = agent
                course_context["topic"] = topic

                # Verify the provider is available with the new configuration
                available_providers = agent.get_available_providers()
                if provider not in available_providers:
                    return (
                        f"<div class='error'>โŒ Provider '{provider}' is not available after configuration. Please check your API key and configuration.</div>",
                        "", "", 
                        gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                    )

                progress(0.1, desc="โš™๏ธ Setting up generation options...")

                # Create generation options
                options = GenerationOptions(
                    difficulty=DifficultyLevel(difficulty),
                    lesson_count=lessons,
                    include_images=True,
                    include_flashcards=True,
                    include_quizzes=True
                )

                progress(0.15, desc="๐Ÿ” Checking available providers...")

                # Get available providers
                available_providers = agent.get_available_providers()
                if not available_providers:
                    return (
                        "<div class='error'>โŒ No LLM providers available. Please check your API keys.</div>",
                        "", "", 
                        gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                    )

                progress(0.2, desc="๐ŸŽ“ Starting course generation...")

                # Use the default provider from config (no need to override)
                # The agent will automatically use the configured default provider

                # Start course generation
                lessons_html = ""
                flashcards_html = ""
                quizzes_html = ""

                # Stream the generation process
                course_data = None
                current_progress = 0.2
                
                # Add a simple counter for fallback progress
                chunk_count = 0
                max_expected_chunks = 10  # Rough estimate

                async for chunk in agent.generate_course(topic, options):
                    chunk_count += 1
                    print(f"๐Ÿ“Š Progress Debug: Received chunk type='{chunk.type}', content='{chunk.content}'")
                    
                    # Update progress based on chunk content
                    if chunk.type == "progress":
                        # Check if the progress message matches our known steps (handle emojis)
                        step_found = False
                        progress_message = chunk.content.lower()
                        print(f"๐Ÿ” Checking progress message: '{progress_message}'")
                        
                        if "research completed" in progress_message:
                            current_progress = 0.3
                            step_found = True
                            print(f"โœ… Matched: Research completed -> {current_progress}")
                            progress(current_progress, desc="๐Ÿ“š Research completed, planning course structure...")
                        elif "course structure planned" in progress_message:
                            current_progress = 0.4
                            step_found = True
                            print(f"โœ… Matched: Course structure planned -> {current_progress}")
                            progress(current_progress, desc="๐Ÿ“ Course structure planned, generating content...")
                        elif "lessons created" in progress_message:
                            current_progress = 0.6
                            step_found = True
                            print(f"โœ… Matched: Lessons created -> {current_progress}")
                            progress(current_progress, desc="โœ๏ธ Lessons created, generating flashcards...")
                        elif "flashcards created" in progress_message:
                            current_progress = 0.75
                            step_found = True
                            print(f"โœ… Matched: Flashcards created -> {current_progress}")
                            progress(current_progress, desc="๐Ÿƒ Flashcards created, creating quiz...")
                        elif "quiz created" in progress_message:
                            current_progress = 0.8
                            step_found = True
                            print(f"โœ… Matched: Quiz created -> {current_progress}")
                            progress(current_progress, desc="โ“ Quiz created, generating images...")
                        elif "images generated" in progress_message:
                            current_progress = 0.9
                            step_found = True
                            print(f"โœ… Matched: Images generated -> {current_progress}")
                            progress(current_progress, desc="๐ŸŽจ Images generated, finalizing course...")
                        elif "finalizing course" in progress_message:
                            current_progress = 0.95
                            step_found = True
                            print(f"โœ… Matched: Finalizing course -> {current_progress}")
                            progress(current_progress, desc="๐Ÿ“ฆ Assembling final course data...")
                        
                        if not step_found:
                            # Fallback: increment progress based on chunk count
                            fallback_progress = min(0.2 + (chunk_count / max_expected_chunks) * 0.6, 0.85)
                            current_progress = max(current_progress, fallback_progress)
                            print(f"โš ๏ธ No match found, using fallback: {fallback_progress}")
                            progress(current_progress, desc=f"๏ฟฝ๏ฟฝ {chunk.content}")
                    
                    elif chunk.type == "course_complete":
                        current_progress = 0.95
                        progress(current_progress, desc="๐Ÿ“ฆ Finalizing course data...")
                        # Parse the complete course data
                        try:
                            course_data = json.loads(chunk.content)
                        except:
                            course_data = None

                progress(0.97, desc="๐ŸŽจ Processing course content...")

                # If we got course data, format it nicely
                if course_data:
                    course_context["content"] = course_data

                    # Format lessons
                    lessons_html = format_lessons(course_data.get("lessons", []))

                    # Format flashcards
                    flashcards_html = format_flashcards(course_data.get("flashcards", []))

                    # Format quiz
                    quiz_data = course_data.get("quiz", {})
                    quizzes_html = format_quiz(quiz_data)

                    # Show quiz button if quiz exists - be more permissive to ensure it shows
                    quiz_btn_visible = bool(quiz_data and (quiz_data.get("questions") or len(str(quiz_data)) > 50))
                    print(f"๐ŸŽฏ Quiz button visibility: {quiz_btn_visible} (quiz_data: {bool(quiz_data)}, questions: {bool(quiz_data.get('questions') if quiz_data else False)})")
                    
                    # Force quiz button to be visible if we have any quiz content
                    if quiz_data and not quiz_btn_visible:
                        print("โš ๏ธ Forcing quiz button to be visible due to quiz data presence")
                        quiz_btn_visible = True

                    progress(0.98, desc="๐Ÿ–ผ๏ธ Processing images for gallery...")

                    # Prepare image gallery data - fix the format for Gradio Gallery
                    images = []
                    image_details_list = []
                    
                    # Process images from lessons
                    for lesson in course_data.get("lessons", []):
                        lesson_images = lesson.get("images", [])
                        for i, img in enumerate(lesson_images):
                            try:
                                if isinstance(img, dict):
                                    # Handle different image data formats
                                    image_url = img.get("url") or img.get("data_url")
                                    if image_url:
                                        alt_text = img.get("caption", img.get("description", "Educational image"))
                                        
                                        # Handle base64 data URLs by converting to temp files
                                        if image_url.startswith('data:image/'):
                                            import base64
                                            import tempfile
                                            import os
                                            
                                            # Extract base64 data
                                            header, data = image_url.split(',', 1)
                                            image_data = base64.b64decode(data)
                                            
                                            # Determine file extension from header
                                            if 'jpeg' in header or 'jpg' in header:
                                                ext = '.jpg'
                                            elif 'png' in header:
                                                ext = '.png'
                                            elif 'gif' in header:
                                                ext = '.gif'
                                            elif 'webp' in header:
                                                ext = '.webp'
                                            else:
                                                ext = '.jpg'  # Default
                                            
                                            # Create temp file
                                            temp_fd, temp_path = tempfile.mkstemp(suffix=ext, prefix=f'course_img_{i}_')
                                            try:
                                                with os.fdopen(temp_fd, 'wb') as f:
                                                    f.write(image_data)
                                                images.append(temp_path)
                                                image_details_list.append({
                                                    "url": temp_path,
                                                    "caption": alt_text,
                                                    "lesson": lesson.get("title", "Unknown lesson")
                                                })
                                            except Exception as e:
                                                print(f"โš ๏ธ Failed to save temp image {i}: {e}")
                                                os.close(temp_fd)  # Close if write failed
                                                continue
                                                
                                        elif image_url.startswith('http'):
                                            # Regular URL - Gradio can handle these directly
                                            images.append(image_url)
                                            image_details_list.append({
                                                "url": image_url,
                                                "caption": alt_text,
                                                "lesson": lesson.get("title", "Unknown lesson")
                                            })
                                        else:
                                            # Assume it's a file path
                                            if len(image_url) <= 260:  # Windows path limit
                                                images.append(image_url)
                                                image_details_list.append({
                                                    "url": image_url,
                                                    "caption": alt_text,
                                                    "lesson": lesson.get("title", "Unknown lesson")
                                                })
                                            else:
                                                print(f"โš ๏ธ Skipping image {i}: path too long ({len(image_url)} chars)")
                                elif isinstance(img, str):
                                    # Handle case where image is just a URL string
                                    if img.startswith('data:image/'):
                                        # Handle base64 data URLs
                                        import base64
                                        import tempfile
                                        import os
                                        
                                        try:
                                            header, data = img.split(',', 1)
                                            image_data = base64.b64decode(data)
                                            
                                            # Determine file extension from header
                                            if 'jpeg' in header or 'jpg' in header:
                                                ext = '.jpg'
                                            elif 'png' in header:
                                                ext = '.png'
                                            elif 'gif' in header:
                                                ext = '.gif'
                                            elif 'webp' in header:
                                                ext = '.webp'
                                            else:
                                                ext = '.jpg'  # Default
                                            
                                            # Create temp file
                                            temp_fd, temp_path = tempfile.mkstemp(suffix=ext, prefix=f'course_img_{i}_')
                                            try:
                                                with os.fdopen(temp_fd, 'wb') as f:
                                                    f.write(image_data)
                                                images.append(temp_path)
                                                image_details_list.append({
                                                    "url": temp_path,
                                                    "caption": "Educational image",
                                                    "lesson": lesson.get("title", "Unknown lesson")
                                                })
                                            except Exception as e:
                                                print(f"โš ๏ธ Failed to save temp image {i}: {e}")
                                                os.close(temp_fd)  # Close if write failed
                                                continue
                                        except Exception as e:
                                            print(f"โš ๏ธ Error processing base64 image {i}: {e}")
                                            continue
                                    else:
                                        # Regular URL or file path
                                        images.append(img)
                                        image_details_list.append({
                                            "url": img,
                                            "caption": "Educational image",
                                            "lesson": lesson.get("title", "Unknown lesson")
                                        })
                            except Exception as e:
                                print(f"โš ๏ธ Error processing image {i}: {e}")
                                continue
                    
                    # Also check for standalone images in course data
                    standalone_images = course_data.get("images", [])
                    for i, img in enumerate(standalone_images):
                        try:
                            if isinstance(img, dict):
                                image_url = img.get("url") or img.get("data_url")
                                if image_url:
                                    alt_text = img.get("caption", img.get("description", "Course image"))
                                    
                                    # Handle base64 data URLs
                                    if image_url.startswith('data:image/'):
                                        import base64
                                        import tempfile
                                        import os
                                        
                                        try:
                                            header, data = image_url.split(',', 1)
                                            image_data = base64.b64decode(data)
                                            
                                            # Determine file extension from header
                                            if 'jpeg' in header or 'jpg' in header:
                                                ext = '.jpg'
                                            elif 'png' in header:
                                                ext = '.png'
                                            elif 'gif' in header:
                                                ext = '.gif'
                                            elif 'webp' in header:
                                                ext = '.webp'
                                            else:
                                                ext = '.jpg'  # Default
                                            
                                            # Create temp file
                                            temp_fd, temp_path = tempfile.mkstemp(suffix=ext, prefix=f'standalone_img_{i}_')
                                            try:
                                                with os.fdopen(temp_fd, 'wb') as f:
                                                    f.write(image_data)
                                                images.append(temp_path)
                                                image_details_list.append({
                                                    "url": temp_path,
                                                    "caption": alt_text,
                                                    "lesson": "Course Overview"
                                                })
                                            except Exception as e:
                                                print(f"โš ๏ธ Failed to save temp standalone image {i}: {e}")
                                                os.close(temp_fd)  # Close if write failed
                                                continue
                                        except Exception as e:
                                            print(f"โš ๏ธ Error processing base64 standalone image {i}: {e}")
                                            continue
                                    else:
                                        images.append(image_url)
                                        image_details_list.append({
                                            "url": image_url,
                                            "caption": alt_text,
                                            "lesson": "Course Overview"
                                        })
                            elif isinstance(img, str):
                                if img.startswith('data:image/'):
                                    # Handle base64 data URLs
                                    import base64
                                    import tempfile
                                    import os
                                    
                                    try:
                                        header, data = img.split(',', 1)
                                        image_data = base64.b64decode(data)
                                        
                                        # Determine file extension from header
                                        if 'jpeg' in header or 'jpg' in header:
                                            ext = '.jpg'
                                        elif 'png' in header:
                                            ext = '.png'
                                        elif 'gif' in header:
                                            ext = '.gif'
                                        elif 'webp' in header:
                                            ext = '.webp'
                                        else:
                                            ext = '.jpg'  # Default
                                        
                                        # Create temp file
                                        temp_fd, temp_path = tempfile.mkstemp(suffix=ext, prefix=f'standalone_img_{i}_')
                                        try:
                                            with os.fdopen(temp_fd, 'wb') as f:
                                                f.write(image_data)
                                            images.append(temp_path)
                                            image_details_list.append({
                                                "url": temp_path,
                                                "caption": "Course image",
                                                "lesson": "Course Overview"
                                            })
                                        except Exception as e:
                                            print(f"โš ๏ธ Failed to save temp standalone image {i}: {e}")
                                            os.close(temp_fd)  # Close if write failed
                                            continue
                                    except Exception as e:
                                        print(f"โš ๏ธ Error processing base64 standalone image {i}: {e}")
                                        continue
                                else:
                                    images.append(img)
                                    image_details_list.append({
                                        "url": img,
                                        "caption": "Course image",
                                        "lesson": "Course Overview"
                                    })
                        except Exception as e:
                            print(f"โš ๏ธ Error processing standalone image {i}: {e}")
                            continue
                    
                    print(f"๐Ÿ“ธ Prepared {len(images)} images for gallery display")
                    
                    # Create image details HTML for display
                    if image_details_list:
                        image_details_html = "<div class='image-details-container'>"
                        image_details_html += "<h4>๐Ÿ–ผ๏ธ Image Gallery</h4>"
                        image_details_html += f"<p>Total images: {len(image_details_list)}</p>"
                        image_details_html += "<ul>"
                        for i, img_detail in enumerate(image_details_list, 1):
                            image_details_html += f"<li><strong>Image {i}:</strong> {img_detail['caption']} (from {img_detail['lesson']})</li>"
                        image_details_html += "</ul></div>"
                    else:
                        image_details_html = "<div class='image-details'>No images available</div>"

                    progress(1.0, desc="โœ… Course generation complete!")

                    return (
                        lessons_html, flashcards_html, quizzes_html,
                        gr.update(visible=quiz_btn_visible), images, image_details_html
                    )
                else:
                    quiz_btn_visible = False
                    progress(1.0, desc="โš ๏ธ Course generation completed with issues")

                    return (
                        "", "", "",
                        gr.update(visible=quiz_btn_visible), [], "<div class='image-details'>No images available</div>"
                    )

            except Exception as e:
                import traceback
                error_details = traceback.format_exc()
                print(f"Error in course generation: {error_details}")
                return (
                    "", "", "",
                    gr.update(visible=False), [], "<div class='image-details'>Error loading images</div>"
                )

        def handle_quiz_submit():
            """Handle quiz submission using client-side processing"""
            # This function will be replaced by client-side JavaScript
            return gr.update()

        async def handle_chat(message: str, current_chat: str):
            """Handle chat messages for answering questions about the course content"""
            if not message.strip():
                return current_chat, ""

            if not course_context["content"] or not course_context["agent"]:
                assistant_response = "Please generate a course first before asking questions about it."
            else:
                try:
                    # Get the agent and course content
                    agent = course_context["agent"]
                    course_data = course_context["content"]
                    topic = course_context["topic"]
                    
                    # Create context from the course content
                    course_context_text = f"Course Topic: {topic}\n\n"
                    
                    # Add lessons content
                    lessons = course_data.get("lessons", [])
                    for i, lesson in enumerate(lessons, 1):
                        course_context_text += f"Lesson {i}: {lesson.get('title', '')}\n"
                        course_context_text += f"Content: {lesson.get('content', '')[:1000]}...\n"
                        if lesson.get('key_takeaways'):
                            course_context_text += f"Key Takeaways: {', '.join(lesson.get('key_takeaways', []))}\n"
                        course_context_text += "\n"
                    
                    # Add flashcards context
                    flashcards = course_data.get("flashcards", [])
                    if flashcards:
                        course_context_text += "Flashcards:\n"
                        for card in flashcards[:5]:  # Limit to first 5
                            course_context_text += f"Q: {card.get('question', '')} A: {card.get('answer', '')}\n"
                        course_context_text += "\n"
                    
                    # Create a focused prompt for answering questions
                    prompt = f"""You are a helpful course assistant. Answer the user's question about the course content below.

Course Content:
{course_context_text}

User Question: {message}

Instructions:
- Answer based ONLY on the course content provided above
- Be helpful, clear, and educational
- If the question is about something not covered in the course, say so politely
- Keep responses concise but informative
- Use a friendly, teaching tone

Answer:"""

                    # Use the default provider (same as course generation)
                    provider = agent.default_provider
                    available_providers = agent.get_available_providers()
                    if provider not in available_providers:
                        # Fallback to first available if default isn't available
                        provider = available_providers[0] if available_providers else None
                        
                    if provider:
                        # Use the agent's LLM to get a response
                        from ..agents.simple_course_agent import Message
                        messages = [
                            Message(role="system", content="You are a helpful course assistant that answers questions about course content."),
                            Message(role="user", content=prompt)
                        ]
                        
                        print(f"๐Ÿค– Chat using LLM provider: {provider}")
                        assistant_response = await agent._get_llm_response(provider, messages)
                        
                        # Clean up the response
                        assistant_response = assistant_response.strip()
                        if assistant_response.startswith("Answer:"):
                            assistant_response = assistant_response[7:].strip()
                            
                    else:
                        assistant_response = "Sorry, no LLM providers are available to answer your question."
                        
                except Exception as e:
                    print(f"Error in chat: {e}")
                    assistant_response = "Sorry, I encountered an error while trying to answer your question. Please try again."

            # Extract existing messages from current chat HTML
            existing_messages = ""
            if current_chat and "chat-message" in current_chat:
                # Keep existing messages
                start = current_chat.find('<div class="chat-messages"')
                if start != -1:
                    end = current_chat.find('</div>', start)
                    if end != -1:
                        existing_content = current_chat[start:end]
                        # Extract just the message divs
                        import re
                        messages_match = re.findall(r'<div class="chat-message.*?</div>\s*</div>', existing_content, re.DOTALL)
                        existing_messages = ''.join(messages_match)

            # Create new chat HTML with existing messages plus new ones
            new_chat = f"""
            <div class='chat-window'>
                <div class='chat-messages' id='chat-messages'>
                    {existing_messages}
                    <div class='chat-message user-message'>
                        <div class='message-avatar'>๐Ÿ‘ค</div>
                        <div class='message-content'>
                            <div class='message-text'>{message}</div>
                        </div>
                    </div>
                    <div class='chat-message assistant-message'>
                        <div class='message-avatar'>๐Ÿค–</div>
                        <div class='message-content'>
                            <div class='message-text'>{assistant_response}</div>
                        </div>
                    </div>
                </div>
            </div>
            """

            return new_chat, ""



        # Connect provider change event
        llm_provider.change(
            fn=on_provider_change,
            inputs=[llm_provider],
            outputs=[openai_compatible_row]
        )

        generate_btn.click(
            fn=generate_course_wrapper,
            inputs=[topic_input, difficulty_input, lesson_count, llm_provider, api_key_input, endpoint_url_input, model_name_input],
            outputs=[
                lessons_output, flashcards_output, quizzes_output, quiz_submit_btn, image_gallery, image_details
            ]
        )

        chat_btn.click(
            fn=handle_chat,
            inputs=[chat_input, chat_display],
            outputs=[chat_display, chat_input]
        )

        # Use a much simpler approach with direct JavaScript execution
        quiz_submit_btn.click(
            fn=None,  # No Python function needed
            js="""
            function() {
                // Find all quiz questions and process them
                const questions = document.querySelectorAll('.quiz-question');
                if (questions.length === 0) {
                    alert('No quiz questions found!');
                    return;
                }
                
                let score = 0;
                let total = questions.length;
                let hasAnswers = false;
                
                questions.forEach((question, idx) => {
                    const radios = question.querySelectorAll('input[type="radio"]');
                    const correctAnswer = question.dataset.correct;
                    const explanation = question.dataset.explanation || '';
                    
                    let selectedRadio = null;
                    radios.forEach(radio => {
                        if (radio.checked) {
                            selectedRadio = radio;
                            hasAnswers = true;
                        }
                    });
                    
                    // Create or find feedback element
                    let feedback = question.querySelector('.quiz-feedback');
                    if (!feedback) {
                        feedback = document.createElement('div');
                        feedback.className = 'quiz-feedback';
                        question.appendChild(feedback);
                    }
                    
                    if (selectedRadio) {
                        const userAnswer = selectedRadio.value;
                        if (userAnswer === correctAnswer) {
                            score++;
                            feedback.innerHTML = `<div style="background: #d4edda; color: #155724; padding: 1rem; border-radius: 6px; margin-top: 1rem;">โœ… <strong>Correct!</strong> ${explanation}</div>`;
                        } else {
                            feedback.innerHTML = `<div style="background: #f8d7da; color: #721c24; padding: 1rem; border-radius: 6px; margin-top: 1rem;">โŒ <strong>Incorrect.</strong> The correct answer is <strong>${correctAnswer}</strong>. ${explanation}</div>`;
                        }
                    } else {
                        feedback.innerHTML = `<div style="background: #fff3cd; color: #856404; padding: 1rem; border-radius: 6px; margin-top: 1rem;">โš ๏ธ <strong>No answer selected.</strong> The correct answer is <strong>${correctAnswer}</strong>. ${explanation}</div>`;
                    }
                    
                    feedback.style.display = 'block';
                });
                
                if (hasAnswers) {
                    const percentage = Math.round((score / total) * 100);
                    
                    // Create or find results container
                    let resultsContainer = document.querySelector('.quiz-results');
                    if (!resultsContainer) {
                        resultsContainer = document.createElement('div');
                        resultsContainer.className = 'quiz-results';
                        resultsContainer.style.cssText = 'margin-top: 2rem; padding: 1.5rem; background: linear-gradient(135deg, #667eea, #764ba2); color: white; border-radius: 8px; text-align: center; font-size: 1.1rem;';
                        document.querySelector('.quiz-container').appendChild(resultsContainer);
                    }
                    
                    let message = '';
                    if (percentage >= 80) {
                        message = '๐ŸŽ‰ Excellent work!';
                    } else if (percentage >= 60) {
                        message = '๐Ÿ‘ Good job!';
                    } else {
                        message = '๐Ÿ“š Keep studying!';
                    }
                    
                    resultsContainer.innerHTML = `
                        <div style="font-size: 1.5rem; font-weight: bold; margin-bottom: 0.5rem;">๐Ÿ“Š Final Score: ${score}/${total} (${percentage}%)</div>
                        <p>${message}</p>
                    `;
                    
                    resultsContainer.style.display = 'block';
                    resultsContainer.scrollIntoView({ behavior: 'smooth', block: 'center' });
                } else {
                    alert('Please answer at least one question before submitting!');
                }
            }
            """
        )

    return interface


def launch_app(share: bool = False, debug: bool = False) -> None:
    """Launch the Course Creator application"""
    interface = create_coursecrafter_interface()
    interface.launch(
        share=share,
        debug=debug,
        server_name="0.0.0.0",
        server_port=7862
    )


if __name__ == "__main__":
    launch_app(debug=True)