File size: 59,244 Bytes
05d6b4f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CLT Lesson Idea Analyzer</title>
    
    <style>
        /* CSS Custom Properties */
        :root {
            /* Color System - Educational theme */
            --color-primary: #007acc;
            --color-primary-hover: #005fa3;
            --color-secondary: #4a90e2;
            --color-accent: #f39c12;
            --color-success: #27ae60;
            --color-warning: #f39c12;
            --color-error: #e74c3c;
            
            /* Neutral Colors - Light Mode */
            --color-background: #f9f9f9;
            --color-surface: #ffffff;
            --color-surface-elevated: #ffffff;
            --color-border: #cccccc;
            --color-border-focus: #007acc;
            --color-text-primary: #333333;
            --color-text-secondary: #666666;
            --color-text-muted: #999999;
            
            /* Typography */
            --font-family-primary: Arial, sans-serif;
            
            /* Spacing System */
            --spacing-xs: 0.25rem;
            --spacing-sm: 0.5rem;
            --spacing-md: 0.75rem;
            --spacing-lg: 1rem;
            --spacing-xl: 1.25rem;
            --spacing-2xl: 1.5rem;
            --spacing-3xl: 2rem;
            
            /* Border Radius */
            --radius-sm: 4px;
            --radius-md: 6px;
            --radius-lg: 8px;
            --radius-xl: 12px;
            
            /* Shadows */
            --shadow-sm: 0 1px 3px rgba(0,0,0,0.1);
            --shadow-md: 0 4px 6px rgba(0,0,0,0.1);
            --shadow-lg: 0 10px 25px rgba(0,0,0,0.1);
            
            /* Transitions */
            --transition-fast: 150ms ease-in-out;
            --transition-normal: 250ms ease-in-out;
            --transition-slow: 350ms ease-in-out;
        }

        /* RTL Support */
        [dir="rtl"] {
            text-align: right;
        }

        [dir="rtl"] .language-switcher {
            right: auto;
            left: var(--spacing-lg);
        }

        /* Base Styles */
        html {
            font-size: 16px;
            line-height: 1.6;
            scroll-behavior: smooth;
        }

        body {
            font-family: var(--font-family-primary);
            background: var(--color-background);
            color: var(--color-text-primary);
            line-height: 1.6;
            margin: 0;
            padding: 0;
            min-height: 100vh;
            transition: all 0.3s ease;
        }

        /* Language Selection Landing */
        .language-landing {
            display: block;
            max-width: 600px;
            margin: 50px auto;
            background: var(--color-surface);
            border-radius: var(--radius-xl);
            box-shadow: var(--shadow-lg);
            padding: 40px;
            text-align: center;
        }

        .language-landing h1 {
            font-size: 2.5rem;
            font-weight: bold;
            background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            margin-bottom: 15px;
        }

        .language-landing p {
            font-size: 1.1rem;
            color: var(--color-text-secondary);
            margin-bottom: 30px;
        }

        .language-selector {
            margin-bottom: 25px;
        }

        .language-selector label {
            display: block;
            margin-bottom: 10px;
            font-weight: bold;
            color: var(--color-text-primary);
            font-size: 1.1rem;
        }

        .language-selector select {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid var(--color-border);
            border-radius: var(--radius-lg);
            font-size: 1.1rem;
            font-family: inherit;
            background: var(--color-surface);
            transition: all 0.2s ease;
            margin-bottom: 20px;
            color: var(--color-text-primary);
        }

        .language-selector select:focus {
            outline: none;
            border-color: var(--color-border-focus);
            box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.1);
        }

        .api-key-landing {
            margin-bottom: 25px;
        }

        .api-key-landing label {
            display: block;
            margin-bottom: 10px;
            font-weight: bold;
            color: var(--color-text-primary);
            font-size: 1.1rem;
        }

        .api-key-landing input {
            width: 100%;
            padding: 15px 20px;
            border: 2px solid var(--color-border);
            border-radius: var(--radius-lg);
            font-size: 1.1rem;
            background: var(--color-surface);
            transition: all 0.2s ease;
            font-family: 'Courier New', monospace;
            color: var(--color-text-primary);
            box-sizing: border-box;
        }

        .api-key-landing input:focus {
            outline: none;
            border-color: var(--color-border-focus);
            box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.1);
        }

        .start-btn {
            background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%);
            color: white;
            padding: 18px 40px;
            border: none;
            border-radius: var(--radius-lg);
            font-size: 1.2rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
            width: 100%;
        }

        .start-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 24px -8px rgba(0, 122, 204, 0.4);
        }

        .start-btn:disabled {
            opacity: 0.7;
            cursor: not-allowed;
            transform: none;
        }

        /* Cache Management Section */
        .cache-management {
            background: rgba(0, 122, 204, 0.05);
            border: 1px solid rgba(0, 122, 204, 0.1);
            border-radius: var(--radius-lg);
            padding: 20px;
            margin-bottom: 25px;
            text-align: center;
        }

        .cache-management h3 {
            color: var(--color-primary);
            margin-bottom: 15px;
            font-size: 1.1rem;
            font-weight: bold;
        }

        .cache-status-display {
            background: rgba(39, 174, 96, 0.1);
            border: 1px solid rgba(39, 174, 96, 0.2);
            color: var(--color-success);
            padding: 12px 16px;
            border-radius: var(--radius-md);
            margin-bottom: 15px;
            font-size: 0.9rem;
            font-weight: 500;
        }

        .cache-status-display.no-cache {
            background: rgba(153, 153, 153, 0.1);
            border-color: rgba(153, 153, 153, 0.2);
            color: var(--color-text-secondary);
        }

        .clear-cache-btn {
            background: linear-gradient(135deg, var(--color-warning) 0%, #e67e22 100%);
            color: white;
            padding: 12px 24px;
            border: none;
            border-radius: var(--radius-md);
            font-size: 0.9rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .clear-cache-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 12px -4px rgba(243, 156, 18, 0.4);
        }

        .clear-cache-btn:disabled {
            opacity: 0.5;
            cursor: not-allowed;
            transform: none;
        }

        /* Cache Status Indicator */
        .cache-status {
            background: rgba(39, 174, 96, 0.1);
            border: 1px solid rgba(39, 174, 96, 0.2);
            color: var(--color-success);
            padding: 8px 12px;
            border-radius: var(--radius-sm);
            margin-bottom: 15px;
            font-size: 0.85rem;
            text-align: center;
            font-weight: 500;
            display: none;
        }

        .cache-status.cached {
            display: block;
        }

        .cache-status.translating {
            background: rgba(0, 122, 204, 0.1);
            border-color: rgba(0, 122, 204, 0.2);
            color: var(--color-primary);
        }

        /* Translation Loading Overlay */
        .translation-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 122, 204, 0.9);
            display: none;
            justify-content: center;
            align-items: center;
            z-index: 10000;
            color: white;
            text-align: center;
        }

        .translation-content {
            background: rgba(255, 255, 255, 0.1);
            padding: 40px;
            border-radius: var(--radius-xl);
            backdrop-filter: blur(10px);
        }

        .translation-spinner {
            width: 50px;
            height: 50px;
            border: 4px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: white;
            animation: spin 1s ease-in-out infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }

        /* Main Application (Hidden Initially) */
        .main-app {
            display: none;
            margin: var(--spacing-3xl);
            background: var(--color-background);
        }

        /* Language Switcher in Main App */
        .language-switcher {
            position: absolute;
            top: var(--spacing-lg);
            right: var(--spacing-lg);
            display: flex;
            gap: 10px;
            align-items: center;
            z-index: 10;
        }

        .language-switch-btn {
            background: rgba(0, 122, 204, 0.05);
            border: 1px solid rgba(0, 122, 204, 0.1);
            border-radius: var(--radius-md);
            padding: 8px 12px;
            font-size: 12px;
            cursor: pointer;
            transition: all 0.2s ease;
            color: var(--color-primary);
            font-weight: 500;
        }

        .language-switch-btn:hover {
            background: rgba(0, 122, 204, 0.1);
        }

        .mini-clear-cache {
            background: rgba(243, 156, 18, 0.1);
            border: 1px solid rgba(243, 156, 18, 0.2);
            color: var(--color-warning);
            padding: 6px 10px;
            border-radius: var(--radius-sm);
            font-size: 11px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-weight: 500;
        }

        .mini-clear-cache:hover {
            background: rgba(243, 156, 18, 0.2);
        }

        /* Main Container */
        .container {
            max-width: 800px;
            margin: 0 auto;
            padding: var(--spacing-3xl);
            background-color: var(--color-surface);
            box-shadow: var(--shadow-lg);
            border-radius: var(--radius-lg);
            position: relative;
        }

        h1, h2 {
            color: var(--color-text-primary);
        }

        h1 {
            font-size: 2rem;
            margin-bottom: var(--spacing-xl);
            text-align: center;
            background: linear-gradient(135deg, var(--color-primary) 0%, var(--color-secondary) 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        label {
            display: block;
            font-weight: bold;
            margin-top: var(--spacing-lg);
            color: var(--color-text-primary);
        }

        input[type="text"],
        textarea {
            width: 100%;
            padding: 0.75rem;
            margin-top: 0.5rem;
            border: 1px solid var(--color-border);
            border-radius: var(--radius-sm);
            font-family: inherit;
            font-size: 1rem;
            transition: border-color 0.2s ease;
            box-sizing: border-box;
        }

        input[type="text"]:focus,
        textarea:focus {
            outline: none;
            border-color: var(--color-border-focus);
            box-shadow: 0 0 0 3px rgba(0, 122, 204, 0.1);
        }

        textarea {
            min-height: 150px;
            resize: vertical;
        }

        button {
            margin-top: var(--spacing-lg);
            padding: 0.75rem 1.5rem;
            font-size: 1rem;
            color: white;
            background-color: var(--color-primary);
            border: none;
            border-radius: var(--radius-sm);
            cursor: pointer;
            transition: background-color 0.2s ease;
        }

        button:hover {
            background-color: var(--color-primary-hover);
        }

        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }

        #result {
            margin-top: var(--spacing-3xl);
            padding: 1.5rem;
            background-color: #eef;
            border-radius: var(--radius-sm);
            white-space: pre-wrap;
            border: 1px solid #dde;
        }

        /* Responsive Design */
        @media (max-width: 768px) {
            .language-landing {
                margin: 20px auto;
                padding: 30px 20px;
            }

            .language-switcher {
                position: relative;
                top: auto;
                right: auto;
                margin-bottom: var(--spacing-xl);
                justify-content: center;
            }

            .main-app {
                margin: var(--spacing-lg);
            }

            .container {
                padding: var(--spacing-xl);
            }
        }

        /* Accessibility */
        .sr-only {
            position: absolute;
            width: 1px;
            height: 1px;
            padding: 0;
            margin: -1px;
            overflow: hidden;
            clip: rect(0, 0, 0, 0);
            white-space: nowrap;
            border: 0;
        }

        /* Focus styles */
        button:focus,
        input:focus,
        select:focus,
        textarea:focus {
            outline: 2px solid var(--color-primary);
            outline-offset: 2px;
        }
    </style>
</head>

<body>
    <!-- Translation Loading Overlay -->
    <div class="translation-overlay" id="translationOverlay">
        <div class="translation-content">
            <div class="translation-spinner"></div>
            <h2 id="translationTitle" data-translate="translating_interface">Translating Interface...</h2>
            <p id="translationMessage" data-translate="translation_wait_message">Please wait while we translate the interface to your selected language.</p>
        </div>
    </div>

    <!-- Language Selection Landing Page -->
    <div class="language-landing" id="languageLanding">
        <h1 data-translate="app_title">CLT Lesson Idea Analyzer</h1>
        <p data-translate="welcome_message">Welcome! Please select your preferred language and enter your API key to get started with Cognitive Load Theory lesson analysis.</p>
        
        <!-- Cache Status Indicator -->
        <div class="cache-status" id="cacheStatus">
            <span data-translate="cache_status_cached">💾 Translations cached - instant loading!</span>
        </div>

        <!-- Cache Management Section -->
        <div class="cache-management" id="cacheManagement">
            <h3 data-translate="cache_management_title">🗂️ Translation Cache Management</h3>
            <div class="cache-status-display" id="cacheStatusDisplay">
                <span data-translate="cache_status_checking">Checking cache status...</span>
            </div>
            <button class="clear-cache-btn" id="clearCacheBtn" data-translate="clear_cache_button">
                🗑️ Clear All Cached Translations
            </button>
        </div>
        
        <div class="language-selector">
            <label for="languageSelect" data-translate="select_language">🌐 Select Language</label>
            <select id="languageSelect">
                <option value="en">🇺🇸 English</option>
                <option value="es">🇪🇸 Español (Spanish)</option>
                <option value="fr">🇫🇷 Français (French)</option>
                <option value="de">🇩🇪 Deutsch (German)</option>
                <option value="zh">🇨🇳 中文 (Chinese)</option>
                <option value="ja">🇯🇵 日本語 (Japanese)</option>
                <option value="ko">🇰🇷 한국어 (Korean)</option>
                <option value="pt">🇵🇹 Português (Portuguese)</option>
                <option value="it">🇮🇹 Italiano (Italian)</option>
                <option value="ar">🇸🇦 العربية (Arabic)</option>
                <option value="ru">🇷🇺 Русский (Russian)</option>
                <option value="hi">🇮🇳 हिन्दी (Hindi)</option>
                <option value="bn">🇧🇩 বাংলা (Bengali)</option>
                <option value="ur">🇵🇰 اردو (Urdu)</option>
                <option value="tr">🇹🇷 Türkçe (Turkish)</option>
                <option value="pl">🇵🇱 Polski (Polish)</option>
                <option value="nl">🇳🇱 Nederlands (Dutch)</option>
                <option value="sv">🇸🇪 Svenska (Swedish)</option>
                <option value="da">🇩🇰 Dansk (Danish)</option>
                <option value="no">🇳🇴 Norsk (Norwegian)</option>
                <option value="fi">🇫🇮 Suomi (Finnish)</option>
                <option value="is">🇮🇸 Íslenska (Icelandic)</option>
                <option value="cs">🇨🇿 Čeština (Czech)</option>
                <option value="sk">🇸🇰 Slovenčina (Slovak)</option>
                <option value="hu">🇭🇺 Magyar (Hungarian)</option>
                <option value="ro">🇷🇴 Română (Romanian)</option>
                <option value="bg">🇧🇬 Български (Bulgarian)</option>
                <option value="hr">🇭🇷 Hrvatski (Croatian)</option>
                <option value="sr">🇷🇸 Српски (Serbian)</option>
                <option value="sl">🇸🇮 Slovenščina (Slovenian)</option>
                <option value="mk">🇲🇰 Македонски (Macedonian)</option>
                <option value="sq">🇦🇱 Shqip (Albanian)</option>
                <option value="lv">🇱🇻 Latviešu (Latvian)</option>
                <option value="lt">🇱🇹 Lietuvių (Lithuanian)</option>
                <option value="et">🇪🇪 Eesti (Estonian)</option>
                <option value="mt">🇲🇹 Malti (Maltese)</option>
                <option value="ga">🇮🇪 Gaeilge (Irish)</option>
                <option value="cy">🏴󠁧󠁢󠁷󠁬󠁳󠁿 Cymraeg (Welsh)</option>
                <option value="eu">🏴󠁥󠁳󠁰󠁶󠁿 Euskera (Basque)</option>
                <option value="ca">🏴󠁥󠁳󠁣󠁴󠁿 Català (Catalan)</option>
                <option value="gl">🏴󠁥󠁳󠁧󠁡󠁿 Galego (Galician)</option>
                <option value="el">🇬🇷 Ελληνικά (Greek)</option>
                <option value="he">🇮🇱 עברית (Hebrew)</option>
                <option value="fa">🇮🇷 فارسی (Persian)</option>
                <option value="ps">🇦🇫 پښتو (Pashto)</option>
                <option value="ku">🏴󠁩󠁱󠁫󠁲󠁿 کوردی (Kurdish)</option>
                <option value="az">🇦🇿 Azərbaycan (Azerbaijani)</option>
                <option value="kk">🇰🇿 Қазақша (Kazakh)</option>
                <option value="ky">🇰🇬 Кыргызча (Kyrgyz)</option>
                <option value="uz">🇺🇿 O'zbek (Uzbek)</option>
                <option value="tk">🇹🇲 Türkmen (Turkmen)</option>
                <option value="tg">🇹🇯 Тоҷикӣ (Tajik)</option>
                <option value="mn">🇲🇳 Монгол (Mongolian)</option>
                <option value="ka">🇬🇪 ქართული (Georgian)</option>
                <option value="hy">🇦🇲 Հայերեն (Armenian)</option>
                <option value="th">🇹🇭 ไทย (Thai)</option>
                <option value="vi">🇻🇳 Tiếng Việt (Vietnamese)</option>
                <option value="lo">🇱🇦 ລາວ (Lao)</option>
                <option value="km">🇰🇭 ខ្មែរ (Khmer)</option>
                <option value="my">🇲🇲 မြန်မာ (Myanmar)</option>
                <option value="si">🇱🇰 සිංහල (Sinhala)</option>
                <option value="ta">🇱🇰 தமிழ் (Tamil)</option>
                <option value="te">🇮🇳 తెలుగు (Telugu)</option>
                <option value="kn">🇮🇳 ಕನ್ನಡ (Kannada)</option>
                <option value="ml">🇮🇳 മലയാളം (Malayalam)</option>
                <option value="gu">🇮🇳 ગુજરાતી (Gujarati)</option>
                <option value="pa">🇮🇳 ਪੰਜਾਬੀ (Punjabi)</option>
                <option value="or">🇮🇳 ଓଡ଼ିଆ (Odia)</option>
                <option value="as">🇮🇳 অসমীয়া (Assamese)</option>
                <option value="ne">🇳🇵 नेपाली (Nepali)</option>
                <option value="dz">🇧🇹 རྫོང་ཁ (Dzongkha)</option>
                <option value="bo">🏔️ བོད་ཡིག (Tibetan)</option>
                <option value="id">🇮🇩 Bahasa Indonesia</option>
                <option value="ms">🇲🇾 Bahasa Melayu (Malay)</option>
                <option value="tl">🇵🇭 Filipino (Tagalog)</option>
                <option value="ceb">🇵🇭 Cebuano</option>
                <option value="haw">🏝️ ʻŌlelo Hawaiʻi (Hawaiian)</option>
                <option value="mi">🇳🇿 Te Reo Māori (Maori)</option>
                <option value="sm">🇼🇸 Gagana Samoa (Samoan)</option>
                <option value="to">🇹🇴 Lea Fakatonga (Tongan)</option>
                <option value="fj">🇫🇯 Na Vosa Vakaviti (Fijian)</option>
                <option value="mg">🇲🇬 Malagasy</option>
                <option value="sw">🇰🇪 Kiswahili (Swahili)</option>
                <option value="zu">🇿🇦 isiZulu (Zulu)</option>
                <option value="xh">🇿🇦 isiXhosa (Xhosa)</option>
                <option value="af">🇿🇦 Afrikaans</option>
                <option value="st">🇱🇸 Sesotho (Southern Sotho)</option>
                <option value="tn">🇧🇼 Setswana (Tswana)</option>
                <option value="ss">🇸🇿 siSwati (Swati)</option>
                <option value="ve">🇿🇦 Tshivenḓa (Venda)</option>
                <option value="ts">🇿🇦 Xitsonga (Tsonga)</option>
                <option value="nr">🇿🇦 isiNdebele (Southern Ndebele)</option>
                <option value="am">🇪🇹 አማርኛ (Amharic)</option>
                <option value="ti">🇪🇷 ትግርኛ (Tigrinya)</option>
                <option value="om">🇪🇹 Afaan Oromoo (Oromo)</option>
                <option value="so">🇸🇴 Soomaali (Somali)</option>
                <option value="ha">🇳🇬 Hausa</option>
                <option value="yo">🇳🇬 Yorùbá (Yoruba)</option>
                <option value="ig">🇳🇬 Igbo</option>
                <option value="ff">🇸🇳 Fulfulde (Fulani)</option>
                <option value="wo">🇸🇳 Wolof</option>
                <option value="bm">🇲🇱 Bamanankan (Bambara)</option>
                <option value="rn">🇧🇮 Kirundi (Rundi)</option>
                <option value="rw">🇷🇼 Kinyarwanda (Rwanda)</option>
                <option value="lg">🇺🇬 Luganda</option>
                <option value="ny">🇲🇼 Chichewa (Nyanja)</option>
                <option value="sn">🇿🇼 chiShona (Shona)</option>
                <option value="nd">🇿🇼 isiNdebele (Northern Ndebele)</option>
            </select>
        </div>

        <div class="api-key-landing">
            <label for="apiKeyLanding" data-translate="api_key_label">🔑 OpenAI API Key</label>
            <input type="password" id="apiKeyLanding" placeholder="Enter your OpenAI API key" data-translate-placeholder="api_key_placeholder">
        </div>

        <button class="start-btn" id="startBtn" data-translate="start_button">🚀 Start CLT Analyzer</button>
    </div>

    <!-- Main Application -->
    <div class="main-app" id="mainApp">
        <!-- Language Switcher -->
        <div class="language-switcher" id="languageSwitcher">
            <div class="language-switch-btn" onclick="showLanguageLanding()">
                <span data-translate="change_language">🌐 Change Language</span>
            </div>
            <div class="mini-clear-cache" onclick="clearAllTranslationCache()" title="Clear translation cache">
                <span data-translate="clear_cache_mini">🗑️ Clear Cache</span>
            </div>
        </div>

        <div class="container">
            <h1 data-translate="app_title">CLT Lesson Idea Analyzer</h1>
            
            <!-- Application Description -->
            <div class="app-description" style="background: rgba(0, 122, 204, 0.05); border: 1px solid rgba(0, 122, 204, 0.1); border-radius: var(--radius-lg); padding: 20px; margin-bottom: 30px; text-align: center;">
                <p data-translate="app_description" style="margin: 0; color: var(--color-text-secondary); font-size: 1.1rem; line-height: 1.6;">
                    🧠 Transform your teaching with science-backed lesson analysis! This AI-powered tool evaluates your lesson ideas through the lens of <strong>Cognitive Load Theory (CLT)</strong>, providing detailed insights on intrinsic, extraneous, and germane cognitive loads. Get professional recommendations to optimize student learning, reduce cognitive overload, and enhance educational effectiveness with evidence-based pedagogical strategies.
                </p>
            </div>
            
            <form id="lessonForm">
                <label for="lessonIdea" data-translate="lesson_idea_label">Lesson or Activity Idea</label>
                <textarea id="lessonIdea" name="lessonIdea" placeholder="Enter your lesson or activity idea" data-translate-placeholder="lesson_idea_placeholder" required></textarea>
                
                <button type="submit" data-translate="submit_button">Submit</button>
            </form>
            
            <div id="result"></div>
        </div>
    </div>

    <script>
        // RTL languages list
        const rtlLanguages = ['ar', 'he', 'fa', 'ur', 'ps', 'ku'];

        // Current language and API key
        let currentLanguage = 'en';
        let currentApiKey = '';

        // Language names mapping
        const languageNames = {
            en: 'English', es: 'Spanish', fr: 'French', de: 'German', zh: 'Chinese',
            ja: 'Japanese', ko: 'Korean', pt: 'Portuguese', it: 'Italian', ar: 'Arabic',
            ru: 'Russian', hi: 'Hindi', bn: 'Bengali', ur: 'Urdu', tr: 'Turkish',
            pl: 'Polish', nl: 'Dutch', sv: 'Swedish', da: 'Danish', no: 'Norwegian',
            fi: 'Finnish', is: 'Icelandic', cs: 'Czech', sk: 'Slovak', hu: 'Hungarian',
            ro: 'Romanian', bg: 'Bulgarian', hr: 'Croatian', sr: 'Serbian', sl: 'Slovenian',
            mk: 'Macedonian', sq: 'Albanian', lv: 'Latvian', lt: 'Lithuanian', et: 'Estonian',
            mt: 'Maltese', ga: 'Irish', cy: 'Welsh', eu: 'Basque', ca: 'Catalan',
            gl: 'Galician', el: 'Greek', he: 'Hebrew', fa: 'Persian', ps: 'Pashto',
            ku: 'Kurdish', az: 'Azerbaijani', kk: 'Kazakh', ky: 'Kyrgyz', uz: 'Uzbek',
            tk: 'Turkmen', tg: 'Tajik', mn: 'Mongolian', ka: 'Georgian', hy: 'Armenian',
            th: 'Thai', vi: 'Vietnamese', lo: 'Lao', km: 'Khmer', my: 'Myanmar',
            si: 'Sinhala', ta: 'Tamil', te: 'Telugu', kn: 'Kannada', ml: 'Malayalam',
            gu: 'Gujarati', pa: 'Punjabi', or: 'Odia', as: 'Assamese', ne: 'Nepali',
            dz: 'Dzongkha', bo: 'Tibetan', id: 'Indonesian', ms: 'Malay', tl: 'Filipino',
            ceb: 'Cebuano', haw: 'Hawaiian', mi: 'Maori', sm: 'Samoan', to: 'Tongan',
            fj: 'Fijian', mg: 'Malagasy', sw: 'Swahili', zu: 'Zulu', xh: 'Xhosa',
            af: 'Afrikaans', st: 'Southern Sotho', tn: 'Tswana', ss: 'Swati', ve: 'Venda',
            ts: 'Tsonga', nr: 'Southern Ndebele', am: 'Amharic', ti: 'Tigrinya', om: 'Oromo',
            so: 'Somali', ha: 'Hausa', yo: 'Yoruba', ig: 'Igbo', ff: 'Fulani',
            wo: 'Wolof', bm: 'Bambara', rn: 'Rundi', rw: 'Rwanda', lg: 'Luganda',
            ny: 'Chichewa', sn: 'Shona', nd: 'Northern Ndebele'
        };

        // Translation cache management
        const CACHE_PREFIX = 'clt_translations_';
        const CACHE_VERSION = '1.0';

        // Check if translations are cached for a language
        function isLanguageCached(language) {
            const cacheKey = CACHE_PREFIX + language;
            const cached = localStorage.getItem(cacheKey);
            return cached !== null;
        }

        // Save translations to cache
        function saveTranslationsToCache(language, translations) {
            const cacheKey = CACHE_PREFIX + language;
            const cacheData = {
                version: CACHE_VERSION,
                timestamp: Date.now(),
                translations: translations
            };
            localStorage.setItem(cacheKey, JSON.stringify(cacheData));
            console.log(`Translations cached for ${language}`);
        }

        // Load translations from cache
        function loadTranslationsFromCache(language) {
            const cacheKey = CACHE_PREFIX + language;
            const cached = localStorage.getItem(cacheKey);
            
            if (cached) {
                try {
                    const cacheData = JSON.parse(cached);
                    if (cacheData.version === CACHE_VERSION) {
                        console.log(`Translations loaded from cache for ${language}`);
                        return cacheData.translations;
                    }
                } catch (error) {
                    console.error('Error parsing cached translations:', error);
                }
            }
            return null;
        }

        // Get all cached languages
        function getCachedLanguages() {
            const cachedLanguages = [];
            for (let i = 0; i < localStorage.length; i++) {
                const key = localStorage.key(i);
                if (key && key.startsWith(CACHE_PREFIX)) {
                    const language = key.replace(CACHE_PREFIX, '');
                    cachedLanguages.push(language);
                }
            }
            return cachedLanguages;
        }

        // Clear all translation cache
        function clearAllTranslationCache() {
            const cachedLanguages = getCachedLanguages();
            
            if (cachedLanguages.length === 0) {
                alert('No cached translations to clear.');
                return;
            }

            const languageList = cachedLanguages.map(lang => languageNames[lang] || lang).join(', ');
            const confirmMessage = `Are you sure you want to clear all cached translations?\n\nCached languages: ${languageList}\n\nThis will require re-downloading translations when switching languages.`;
            
            if (confirm(confirmMessage)) {
                // Clear all translation caches
                cachedLanguages.forEach(language => {
                    const cacheKey = CACHE_PREFIX + language;
                    localStorage.removeItem(cacheKey);
                });
                
                // Update cache status
                updateCacheStatus(currentLanguage);
                updateCacheStatusDisplay();
                
                alert(`Cache cleared successfully!\n\n${cachedLanguages.length} language(s) removed from cache.`);
                
                // Ask if user wants to reload current language translations
                if (currentLanguage !== 'en' && cachedLanguages.includes(currentLanguage)) {
                    if (confirm('Would you like to reload the current language translations?')) {
                        applyLanguage(currentLanguage);
                    }
                }
            }
        }

        // Update cache status indicator
        function updateCacheStatus(language) {
            const cacheStatus = document.getElementById('cacheStatus');
            const isCached = isLanguageCached(language);
            
            if (language === 'en') {
                cacheStatus.classList.remove('cached', 'translating');
                return;
            }
            
            if (isCached) {
                cacheStatus.querySelector('[data-translate="cache_status_cached"]').textContent = '💾 Translations cached - instant loading!';
                cacheStatus.classList.add('cached');
                cacheStatus.classList.remove('translating');
            } else {
                cacheStatus.querySelector('[data-translate="cache_status_cached"]').textContent = '🔄 First time translation - will be cached for future use';
                cacheStatus.classList.add('translating');
                cacheStatus.classList.remove('cached');
            }
        }

        // Update cache status display in management section
        function updateCacheStatusDisplay() {
            const cacheStatusDisplay = document.getElementById('cacheStatusDisplay');
            const clearCacheBtn = document.getElementById('clearCacheBtn');
            const cachedLanguages = getCachedLanguages();
            
            if (cachedLanguages.length === 0) {
                cacheStatusDisplay.querySelector('[data-translate="cache_status_checking"]').textContent = '📭 No cached translations';
                cacheStatusDisplay.className = 'cache-status-display no-cache';
                clearCacheBtn.disabled = true;
            } else {
                const languageList = cachedLanguages.map(lang => languageNames[lang] || lang).join(', ');
                cacheStatusDisplay.querySelector('[data-translate="cache_status_checking"]').textContent = `💾 ${cachedLanguages.length} language(s) cached: ${languageList}`;
                cacheStatusDisplay.className = 'cache-status-display';
                clearCacheBtn.disabled = false;
            }
        }

        // API call function for translation
        async function translateText(text, targetLanguage) {
            if (!currentApiKey) {
                throw new Error('API key is required for translation');
            }

            const languageName = languageNames[targetLanguage] || 'English';
            
            const prompt = `Translate the following text to ${languageName}. Provide ONLY the exact translation without any explanations, additional information, or formatting:

"${text}"`;

            const payload = {
                model: "gpt-4o-mini",
                messages: [{ role: "user", content: prompt }],
                max_tokens: 500,
                temperature: 0.1
            };

            const response = await fetch("https://api.openai.com/v1/chat/completions", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "Authorization": `Bearer ${currentApiKey}`
                },
                body: JSON.stringify(payload)
            });

            if (!response.ok) {
                const errorData = await response.json();
                throw new Error(errorData.error?.message || "Translation API request failed");
            }

            const data = await response.json();
            return data.choices[0].message.content.trim();
        }

        // Apply cached translations to UI
        function applyCachedTranslations(translations) {
            // Apply text translations
            Object.keys(translations.texts).forEach(originalText => {
                const translation = translations.texts[originalText];
                const elements = document.querySelectorAll(`[data-translate]`);
                
                elements.forEach(element => {
                    const originalElementText = element.getAttribute('data-original-text') || element.textContent;
                    if (originalElementText === originalText) {
                        element.textContent = translation;
                    }
                });
            });

            // Apply placeholder translations
            Object.keys(translations.placeholders).forEach(originalPlaceholder => {
                const translation = translations.placeholders[originalPlaceholder];
                const elements = document.querySelectorAll(`[data-translate-placeholder]`);
                
                elements.forEach(element => {
                    const originalElementPlaceholder = element.getAttribute('data-original-placeholder') || element.placeholder;
                    if (originalElementPlaceholder === originalPlaceholder) {
                        element.placeholder = translation;
                    }
                });
            });
        }

        // Translate all UI elements
        async function translateInterface(targetLanguage) {
            if (targetLanguage === 'en') {
                // Reset to English - no translation needed
                return;
            }

            // Check if translations are cached
            const cachedTranslations = loadTranslationsFromCache(targetLanguage);
            if (cachedTranslations) {
                // Use cached translations
                console.log('Using cached translations for', targetLanguage);
                applyCachedTranslations(cachedTranslations);
                return;
            }

            // Need to translate via API
            showTranslationOverlay();

            try {
                // Get all elements with data-translate attribute
                const elements = document.querySelectorAll('[data-translate]');
                const placeholderElements = document.querySelectorAll('[data-translate-placeholder]');
                
                // Collect all texts to translate
                const textsToTranslate = [];
                const placeholdersToTranslate = [];
                const elementMap = new Map();
                
                elements.forEach(element => {
                    const originalText = element.getAttribute('data-original-text') || element.textContent;
                    if (!element.getAttribute('data-original-text')) {
                        element.setAttribute('data-original-text', originalText);
                    }
                    textsToTranslate.push(originalText);
                    elementMap.set(originalText, element);
                });

                placeholderElements.forEach(element => {
                    const originalPlaceholder = element.getAttribute('data-original-placeholder') || element.placeholder;
                    if (!element.getAttribute('data-original-placeholder')) {
                        element.setAttribute('data-original-placeholder', originalPlaceholder);
                    }
                    placeholdersToTranslate.push(originalPlaceholder);
                    elementMap.set(originalPlaceholder, element);
                });

                // Prepare cache structure
                const translationsCache = {
                    texts: {},
                    placeholders: {}
                };

                // Translate texts in batches
                const batchSize = 8;
                const allTexts = [...textsToTranslate, ...placeholdersToTranslate];
                
                for (let i = 0; i < allTexts.length; i += batchSize) {
                    const batch = allTexts.slice(i, i + batchSize);
                    
                    // Update progress
                    updateTranslationProgress(i, allTexts.length);
                    
                    // Translate batch
                    const translations = await Promise.all(
                        batch.map(text => translateText(text, targetLanguage))
                    );
                    
                    // Apply translations and cache them
                    batch.forEach((originalText, index) => {
                        const translation = translations[index];
                        
                        if (textsToTranslate.includes(originalText)) {
                            const element = elementMap.get(originalText);
                            element.textContent = translation;
                            translationsCache.texts[originalText] = translation;
                        } else if (placeholdersToTranslate.includes(originalText)) {
                            const element = elementMap.get(originalText);
                            element.placeholder = translation;
                            translationsCache.placeholders[originalText] = translation;
                        }
                    });
                }

                // Save translations to cache
                saveTranslationsToCache(targetLanguage, translationsCache);
                
                // Update cache status
                updateCacheStatus(targetLanguage);
                updateCacheStatusDisplay();

            } catch (error) {
                console.error('Translation error:', error);
                alert('Translation failed: ' + error.message);
            } finally {
                hideTranslationOverlay();
            }
        }

        // Show translation overlay
        function showTranslationOverlay() {
            document.getElementById('translationOverlay').style.display = 'flex';
        }

        // Hide translation overlay
        function hideTranslationOverlay() {
            document.getElementById('translationOverlay').style.display = 'none';
        }

        // Update translation progress
        function updateTranslationProgress(current, total) {
            const percentage = Math.round((current / total) * 100);
            document.getElementById('translationMessage').textContent = 
                `Translating interface... ${percentage}% complete (will be cached for future use)`;
        }

        // Apply language direction
        function applyDirection(language) {
            currentLanguage = language;
            
            // Set document language and direction
            document.documentElement.lang = language;
            document.documentElement.dir = rtlLanguages.includes(language) ? 'rtl' : 'ltr';
            
            // Save language preference
            localStorage.setItem('clt_language', language);
            
            // Update cache status
            updateCacheStatus(language);
        }

        // Apply language with API translation or cache
        async function applyLanguage(language) {
            applyDirection(language);
            
            if (language !== 'en') {
                await translateInterface(language);
            }
        }

        // Show language landing page
        function showLanguageLanding() {
            document.getElementById('languageLanding').style.display = 'block';
            document.getElementById('mainApp').style.display = 'none';
        }

        // Show main application
        function showMainApp() {
            document.getElementById('languageLanding').style.display = 'none';
            document.getElementById('mainApp').style.display = 'block';
        }

        // Get language name for AI prompts
        function getLanguageName() {
            return languageNames[currentLanguage] || 'English';
        }

        // Initialize the application
        function initializeApp() {
            // Load saved language and API key
            const savedLanguage = localStorage.getItem('clt_language') || 'en';
            const savedApiKey = localStorage.getItem('clt_api_key') || '';
            
            currentLanguage = savedLanguage;
            currentApiKey = savedApiKey;
            
            // Set language selector
            document.getElementById('languageSelect').value = currentLanguage;
            document.getElementById('apiKeyLanding').value = currentApiKey;
            
            // Apply direction for current language
            applyDirection(currentLanguage);
            
            // Update cache status
            updateCacheStatus(currentLanguage);
            updateCacheStatusDisplay();
            
            // ALWAYS show language landing page first
            showLanguageLanding();
        }

        // Initialize the application
        document.addEventListener('DOMContentLoaded', function() {
            initializeApp();
            initializeEventListeners();
        });

        // Initialize event listeners
        function initializeEventListeners() {
            // Start button
            document.getElementById('startBtn').addEventListener('click', async function() {
                const selectedLanguage = document.getElementById('languageSelect').value;
                const apiKey = document.getElementById('apiKeyLanding').value.trim();
                
                if (!apiKey) {
                    alert('Please enter your OpenAI API key');
                    return;
                }
                
                currentLanguage = selectedLanguage;
                currentApiKey = apiKey;
                
                // Save API key
                localStorage.setItem('clt_api_key', apiKey);
                
                // Apply language with translation (cached or API)
                await applyLanguage(selectedLanguage);
                
                // Show main app
                showMainApp();
            });
            
            // Language selector change
            document.getElementById('languageSelect').addEventListener('change', async function() {
                const selectedLanguage = this.value;
                updateCacheStatus(selectedLanguage);
                
                if (currentApiKey) {
                    await applyLanguage(selectedLanguage);
                } else {
                    applyDirection(selectedLanguage);
                }
            });
            
            // Clear cache button
            document.getElementById('clearCacheBtn').addEventListener('click', clearAllTranslationCache);
            
            // API key sync
            document.getElementById('apiKeyLanding').addEventListener('input', function() {
                currentApiKey = this.value;
                localStorage.setItem('clt_api_key', this.value);
            });
            
            // Form submission
            document.getElementById('lessonForm').addEventListener('submit', handleFormSubmission);
        }

        // Handle form submission
        async function handleFormSubmission(e) {
            e.preventDefault();
            
            // Retrieve input values
            const lessonIdea = document.getElementById("lessonIdea").value.trim();
            
            if (!lessonIdea) {
                alert('Please enter your lesson or activity idea');
                return;
            }

            if (!currentApiKey) {
                alert('API key is required');
                return;
            }

            // Get the selected language name for the AI response
            const languageName = getLanguageName();
            
            // Construct the agent prompt using CLT guidelines
            const promptText = 
`You are an AI educational design consultant with deep expertise in Cognitive Load Theory (CLT). Your task is to assist educators by providing a detailed, insightful, and actionable analysis of their lesson or activity ideas based on CLT principles. Your response must be professional, comprehensive, and solution-oriented. Follow the detailed structure below precisely, ensuring that each section is thoroughly addressed with practical insights, specific recommendations, and evidence-based practices.

**CRITICAL: Generate the ENTIRE response in ${languageName}. Every single word, phrase, sentence, analysis, recommendation, and insight MUST be written in ${languageName}. Do not mix languages.**

### 1. Lesson Overview
- **Lesson Title & Summary:**  
  Provide a succinct summary of the teacher's lesson idea, including subject matter, teaching context, core objectives, key content areas, and intended learning outcomes. This should encapsulate the essence of the lesson in a way that makes it clear what the teacher aims to achieve and what students will learn.

- **Learning Objectives:**  
  Clearly enumerate measurable objectives or skills the lesson is designed to achieve. Use action verbs from Bloom's Taxonomy to ensure that objectives are specific and assessable (e.g., "Students will analyze...", "Students will create...").

- **Target Audience:**  
  Specify the intended student demographic (e.g., grade level, learning needs, background) to tailor recommendations appropriately. This context will help in customizing the analysis to better fit the unique characteristics of the learners.

### 2. Cognitive Load Analysis
A. **Intrinsic Load**
- **Content Complexity Assessment:**  
  Analyze the inherent complexity of the lesson content, highlighting key concepts and their difficulty, referencing credible research when applicable. For example, if teaching a complex concept like photosynthesis, consider how many steps or processes are involved and their difficulty.

- **Recommendations:**  
  Advise on strategies such as chunking, scaffolding, or dividing the content into smaller segments. For instance, introduce photosynthesis in stages: start with the basic definitions, then move to the role of sunlight, followed by the chemical processes involved. Include ideas for prerequisite activation, such as reviewing prior knowledge on plant biology. Research indicates that chunking information can significantly reduce cognitive overload (Sweller, 1988).

- **Reflective Questions:**  
  Ask whether the current sequencing of content logically builds on prior knowledge and if additional background information is necessary. Questions might include, "Have students had sufficient exposure to related concepts?" or "Is the lesson scaffolded appropriately for student understanding?"

B. **Extraneous Load**
- **Presentation Analysis:**  
  Examine how the material is currently presented, noting potential sources of unnecessary cognitive strain (e.g., overly dense text, confusing visuals). For example, if the lesson uses a PowerPoint presentation with too much text per slide, it could hinder comprehension.

- **Recommendations:**  
  Provide concrete suggestions for streamlining content—such as simplifying language, organizing information with clear headings, integrating informative visuals or diagrams, and removing non-essential elements. An example could be using infographics to summarize photosynthesis visually, making it easier for students to digest.

- **Reflective Questions:**  
  Consider if the design elements could be overwhelming learners and if redesigning the layout could enhance clarity. Ask, "Are there areas in the presentation that could be simplified?" or "Is the visual content aiding or hindering understanding?"

C. **Germane Load**
- **Cognitive Engagement Evaluation:**  
  Assess how well the lesson encourages active processing, schema construction, and deep understanding, referencing relevant practices. For instance, does the lesson include opportunities for students to apply their knowledge through hands-on experiments?

- **Recommendations:**  
  Propose interactive activities such as problem-solving tasks, collaborative group discussions, concept mapping, or reflective writing exercises that engage students in connecting new information with existing knowledge. For example, students can create a concept map on photosynthesis linking different components together, facilitating deeper cognitive processing.

- **Reflective Questions:**  
  Ask if there are opportunities to incorporate formative assessments or knowledge-checks that encourage students to integrate and reflect on new concepts. Consider, "How can students demonstrate their understanding throughout the lesson?" or "Are there checkpoints to assess understanding before moving on?"

### 3. Enhanced Scenario-Based Applications
- **Real-World Application Scenarios:**  
  Propose detailed scenarios where the lesson can be applied in practice, discussing implementations in various learning environments. For instance, students could conduct a project on local plants and their photosynthetic processes, fostering collaborative learning and practical application of concepts.

- **Differentiation Strategies:**  
  Recommend adaptations and tailored approaches for learners with varying skill levels or learning preferences, including ideas for supporting diverse learning needs. For example, provide visual aids for English language learners or hands-on activities for kinesthetic learners, ensuring that all students can engage with the material effectively.

- **Additional Insights:**  
  Explain how these scenarios improve student engagement, promote active learning, and maximize retention by aligning with CLT principles. Discuss the role of context in enhancing motivation and the effectiveness of learning experiences.

### 4. Specific Feedback & Areas for Enhancement
- **Strengths:**  
  Summarize the effective aspects of the lesson idea, highlighting clear objectives, well-structured content, and any innovative practices already in place. Recognizing strengths can help in building confidence and motivation for the teacher.

- **Areas for Improvement:**  
  Identify specific areas for enhancement related to intrinsic, extraneous, and germane load, noting if sections of the lesson are too complex, if the presentation distracts learners, or if engagement activities could be deepened.

- **Actionable Recommendations:**  
  Provide a detailed list of step-by-step solutions or alternative approaches, offering examples or tips for reorganizing the lesson, clarifying complex points, or integrating more interactive components that promote deeper learning.

### 5. Action Plan & Implementation Suggestions
- **Revision Roadmap:**  
  Offer a prioritized, step-by-step plan for revising the lesson, suggesting a timeline or checkpoints for evaluating progress. This could include a phased approach to implementing changes, such as starting with the most critical areas first.

- **Technology & Multimedia Integration:**  
  Recommend digital tools or resources (e.g., interactive whiteboards, educational videos, simulation software, online quizzes) that can support lesson revisions and enhance content delivery. Highlight how these tools can enrich the learning experience and provide additional support for diverse learners.

- **Assessment Strategies:**  
  Propose methods for formative and summative assessments that allow the teacher to gauge learner understanding and gather feedback for continuous improvement. This could include strategies like peer assessments, self-reflections, or exit tickets that provide insights into student comprehension.

### 6. Summary & Next Steps
- **Recap of Key Findings:**  
  Concisely summarize the main strengths and critical areas for improvement discovered during the analysis, ensuring the teacher has a clear understanding of the feedback provided.

- **Final Action Points:**  
  List the essential next steps for the teacher to optimize the lesson plan according to CLT principles. This could involve specific actions to take before the next lesson or priorities for longer-term revisions.

- **Follow-Up Considerations:**  
  Provide reflective questions or suggestions for further professional development, encouraging the teacher to monitor results and adjust the lesson plan iteratively. Consider recommending relevant workshops, online courses, or professional learning communities focused on CLT and instructional design.

**Teacher's Lesson Idea:** ${lessonIdea}

**IMPORTANT: Generate the ENTIRE analysis in ${languageName}. All sections, recommendations, insights, and feedback must be written in ${languageName}.**`;
            
            // Prepare the payload for the API request
            const payload = {
                model: 'gpt-4o-mini',
                messages: [
                    { role: 'system', content: `You are a helpful assistant. Please respond in ${languageName}. **CRITICAL: Generate the ENTIRE response in ${languageName}. Every single word, phrase, sentence, analysis, recommendation, and insight MUST be written in ${languageName}.**` },
                    { role: 'user', content: promptText }
                ],
                temperature: 0.7,
                max_tokens: 5000
            };

            // Show loading state
            const submitButton = document.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.textContent;
            submitButton.textContent = 'Analyzing...';
            submitButton.disabled = true;

            // Make a POST request to OpenAI's chat completions endpoint
            try {
                const response = await fetch('https://api.openai.com/v1/chat/completions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${currentApiKey}`
                    },
                    body: JSON.stringify(payload)
                });

                if (!response.ok) {
                    throw new Error(`API request failed with status ${response.status}`);
                }
                
                const data = await response.json();
                // Display the generated analysis
                document.getElementById("result").innerHTML = 
                    `<h2>CLT Analysis Results</h2><div>${data.choices[0].message.content.replace(/\n/g, '<br>')}</div>`;
            } catch (error) {
                document.getElementById("result").innerHTML = 
                    `<p style="color: red;">Error: ${error.message}</p>`;
            } finally {
                // Reset button state
                submitButton.textContent = originalButtonText;
                submitButton.disabled = false;
            }
        }
    </script>
</body>
</html>