File size: 78,296 Bytes
1618870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90da384
1618870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90da384
 
1618870
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Component Builder</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Open+Sans:wght@400;700&family=Lato:wght@400;700&family=Montserrat:wght@400;700&family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js"></script>
    <script src="https://cdn.ckeditor.com/ckeditor5/41.4.2/classic/ckeditor.js"></script>

    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-hover-color: #2563eb;
            --secondary-color: #10b981;
            --secondary-hover-color: #059669;
            --text-color: #374151;
            --heading-color: #111827;
            --background-color: #f9fafb;
            --font-family: 'Inter', sans-serif;
        }

        body {
            font-family: var(--font-family);
            color: var(--text-color);
            background-color: var(--background-color);
        }
        h1, h2, h3, h4, h5, h6 {
            color: var(--heading-color);
        }
        /* Custom scrollbar for webkit browsers */
        ::-webkit-scrollbar {
            width: 8px;
            height: 8px;
        }
        ::-webkit-scrollbar-track {
            background: #f1f1f1;
        }
        ::-webkit-scrollbar-thumb {
            background: #888;
            border-radius: 10px;
        }
        ::-webkit-scrollbar-thumb:hover {
            background: #555;
        }
        .preview-iframe {
            width: 100%;
            height: 100%;
            border: 0;
            transition: all 0.3s ease-in-out;
        }
        #preview-container.preview-desktop .preview-iframe { width: 100%; }
        #preview-container.preview-tablet .preview-iframe { width: 768px; margin: 0 auto; }
        #preview-container.preview-mobile .preview-iframe { width: 375px; margin: 0 auto; }

        .toast {
            visibility: hidden;
            min-width: 250px;
            background-color: #333;
            color: #fff;
            text-align: center;
            border-radius: 8px;
            padding: 16px;
            position: fixed;
            z-index: 100;
            left: 50%;
            bottom: 30px;
            transform: translateX(-50%);
            opacity: 0;
            transition: opacity 0.3s, visibility 0.3s;
        }
        .toast.show {
            visibility: visible;
            opacity: 1;
        }
        
        /* New Professional Controls UI Styles */
        #controls-layout {
            display: flex;
            height: 100%;
        }
        #controls-nav {
            width: 180px;
            flex-shrink: 0;
            background-color: #f8fafc;
            border-right: 1px solid #e5e7eb;
            padding: 0.5rem;
            overflow-y: auto;
        }
        .control-nav-button {
            display: flex;
            align-items: center;
            width: 100%;
            padding: 0.75rem;
            border-radius: 0.375rem;
            font-weight: 500;
            color: var(--text-color);
            transition: background-color 0.2s, color 0.2s;
            text-align: left;
        }
        .control-nav-button:hover {
            background-color: #e5e7eb;
        }
        .control-nav-button.active {
            background-color: var(--primary-color);
            color: white;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1), 0 1px 2px 0 rgba(0, 0, 0, 0.06);
        }
        .control-nav-button i {
            margin-right: 0.75rem;
            width: 20px;
            text-align: center;
        }
        #controls-panels {
            flex-grow: 1;
            padding: 1.5rem;
            overflow-y: auto;
        }
        .control-panel {
            display: none;
        }
        .control-panel.active {
            display: block;
        }
        .control-panel h3 {
            font-size: 1.25rem;
            font-weight: 600;
            margin-bottom: 1.5rem;
            border-bottom: 1px solid #e5e7eb;
            padding-bottom: 0.75rem;
        }
        .nested-builder {
             margin-left: 1rem;
            padding-left: 1rem;
            border-left: 2px solid #e5e7eb;
            margin-top: 1rem;
            padding-top: 1rem;
        }
        .item-toolbar {
            display: flex;
            justify-content: flex-end;
            gap: 0.25rem;
            margin-bottom: 0.5rem;
        }
        .layout-item {
            cursor: move;
        }
        .code-modal-pre {
            background-color: #2d3748;
            color: #e2e8f0;
            padding: 1rem;
            border-radius: 0.375rem;
            max-height: 200px;
            overflow-y: auto;
            position: relative;
        }

        /* CKEditor Styles */
        .ck-editor__editable_inline {
            min-height: 100px;
        }
    </style>
</head>
<body class="text-gray-800">

    <div id="app" class="flex flex-col h-screen">

        <header class="bg-white shadow-md p-4 flex justify-between items-center z-20">
            <h1 class="text-xl font-bold text-gray-700">Component Builder</h1>
            <div class="flex items-center space-x-4">
                
                <button id="import-btn" class="flex items-center space-x-2 bg-blue-600 text-white font-bold py-2 px-4 rounded-md hover:bg-blue-700 transition">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                        <path d="M10 2a1 1 0 00-1 1v5.586l-1.293-1.293a1 1 0 00-1.414 1.414l3 3a1 1 0 001.414 0l3-3a1 1 0 00-1.414-1.414L11 8.586V3a1 1 0 00-1-1z"></path>
                        <path d="M4 14a1 1 0 011 1v1a1 1 0 001 1h8a1 1 0 001-1v-1a1 1 0 112 0v1a3 3 0 01-3 3H6a3 3 0 01-3-3v-1a1 1 0 011-1z"></path>
                    </svg>
                    <span>Import</span>
                </button>
                <input type="file" id="import-file-input" class="hidden" accept=".html">
                
                <div id="export-menu-container" class="relative">
                    <button id="export-menu-btn" class="flex items-center space-x-2 bg-green-600 text-white font-bold py-2 px-4 rounded-md hover:bg-green-700 transition">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zM6.293 6.707a1 1 0 010-1.414l3-3a1 1 0 011.414 0l3 3a1 1 0 01-1.414 1.414L11 5.414V13a1 1 0 11-2 0V5.414L7.707 6.707a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg>
                        <span>Export Page</span>
                    </button>
                    <div id="export-dropdown" class="hidden absolute right-0 mt-2 w-64 rounded-md shadow-lg bg-white ring-1 ring-black ring-opacity-5 z-30">
                        <div class="py-1" role="menu" aria-orientation="vertical" aria-labelledby="export-menu-btn">
                            <a href="#" id="copy-combined-code" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-3 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                <span>Copy Combined Code</span>
                            </a>
                            <a href="#" id="copy-html" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-3 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path d="M5 5a2 2 0 012-2h10a2 2 0 012 2v1h- savaşmak-14V5zM3 8h18v10a2 2 0 01-2 2H5a2 2 0 01-2-2V8z"></path></svg>
                                <span>Copy Page HTML</span>
                            </a>
                             <a href="#" id="copy-css" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-3 text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01"></path></svg>
                                <span>Copy Page CSS</span>
                            </a>
                            <a href="#" id="copy-js" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-3 text-gray-500" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 2a1 1 0 011 1v1h1a1 1 0 010 2h-1v1a1 1 0 01-2 0V6H8a1 1 0 010-2h1V3a1 1 0 011-1zM5 5a3 3 0 013-3h4a3 3 0 013 3v1h-1V5a2 2 0 00-2-2H8a2 2 0 00-2 2v1H5V5zm2 5a1 1 0 011-1h4a1 1 0 110 2H8a1 1 0 01-1-1zm-1 4a1 1 0 100 2h8a1 1 0 100-2H6z" clip-rule="evenodd" /></svg>
                                <span>Copy Page JS</span>
                            </a>
                            <div class="border-t border-gray-100"></div>
                            <a href="#" id="download-zip-btn" class="flex items-center px-4 py-2 text-sm text-gray-700 hover:bg-gray-100" role="menuitem">
                                <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-3 text-gray-500" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M4 2a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V4a2 2 0 00-2-2H4zm1 3a1 1 0 000 2h10a1 1 0 100-2H5zM5 13a1 1 0 100 2h10a1 1 0 100-2H5z" clip-rule="evenodd"></path></svg>
                                <span>Download Page .zip</span>
                            </a>
                        </div>
                    </div>
                </div>

                <div class="flex items-center space-x-2">
                    <span class="text-sm font-medium text-gray-500">Preview:</span>
                    <button id="desktop-btn" class="p-2 rounded-md bg-blue-500 text-white shadow" title="Desktop View">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M10 2a2 2 0 00-2 2v1H6a2 2 0 00-2 2v7a2 2 0 002 2h8a2 2 0 002-2V7a2 2 0 00-2-2h-2V4a2 2 0 00-2-2zm-1 3V4a1 1 0 112 0v1h-2zM6 7v7h8V7H6z" clip-rule="evenodd"></path></svg>
                    </button>
                    <button id="tablet-btn" class="p-2 rounded-md bg-gray-200 text-gray-700" title="Tablet View">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path fill-rule="evenodd" d="M4 2a2 2 0 00-2 2v12a2 2 0 002 2h12a2 2 0 002-2V4a2 2 0 00-2-2H4zm1 2a1 1 0 00-1 1v10a1 1 0 001 1h10a1 1 0 001-1V5a1 1 0 00-1-1H5z" clip-rule="evenodd"></path></svg>
                    </button>
                    <button id="mobile-btn" class="p-2 rounded-md bg-gray-200 text-gray-700" title="Mobile View">
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor"><path d="M5 2a2 2 0 00-2 2v12a2 2 0 002 2h6a2 2 0 002-2V4a2 2 0 00-2-2H5z"></path></svg>
                    </button>
                </div>
            </div>
        </header>

        <div class="flex flex-1 overflow-hidden">
             <aside class="w-1/3 bg-white shadow-lg overflow-hidden">
                <div id="controls-layout">
                    <nav id="controls-nav" class="space-y-2">
                        <button class="control-nav-button" data-target="#panel-global-settings"><i class="fas fa-cog"></i>Global</button>
                        <button class="control-nav-button" data-target="#panel-layout"><i class="fas fa-layer-group"></i>Layout</button>
                        <button class="control-nav-button" data-target="#panel-product-ticker"><i class="fas fa-tags"></i>Product Ticker</button>
                        <button class="control-nav-button" data-target="#panel-custom-html"><i class="fas fa-code"></i>Custom HTML</button>
                    </nav>

                    <div id="controls-panels">
                        <div id="panel-global-settings" class="control-panel">
                            <h3>⚙️ Global Settings</h3>
                            <div class="space-y-4">
                                <div class="space-y-2 border-b pb-4">
                                     <label class="font-medium text-sm">Color Palette</label>
                                     <div class="grid grid-cols-2 gap-2 text-xs">
                                        <div>
                                            <label for="global-color-primary">Primary</label>
                                            <input type="color" id="global-color-primary" class="w-full p-0 h-8 border-none rounded-md">
                                        </div>
                                        <div>
                                            <label for="global-color-secondary">Secondary</label>
                                            <input type="color" id="global-color-secondary" class="w-full p-0 h-8 border-none rounded-md">
                                        </div>
                                        <div>
                                            <label for="global-color-text">Text</label>
                                            <input type="color" id="global-color-text" class="w-full p-0 h-8 border-none rounded-md">
                                        </div>
                                        <div>
                                            <label for="global-color-heading">Heading</label>
                                            <input type="color" id="global-color-heading" class="w-full p-0 h-8 border-none rounded-md">
                                        </div>
                                     </div>
                                </div>
                                <div class="space-y-2 border-b pb-4">
                                     <label class="font-medium text-sm">Typography</label>
                                     <div>
                                        <label for="global-font-family" class="text-xs">Font Family</label>
                                        <select id="global-font-family" class="w-full p-1 border rounded-md text-sm">
                                            <option value="'Inter', sans-serif">Inter</option>
                                            <option value="'Roboto', sans-serif">Roboto</option>
                                            <option value="'Open Sans', sans-serif">Open Sans</option>
                                            <option value="'Lato', sans-serif">Lato</option>
                                            <option value="'Montserrat', sans-serif">Montserrat</option>
                                            <option value="'Poppins', sans-serif">Poppins</option>
                                        </select>
                                    </div>
                                </div>
                                <button id="apply-global-settings" class="w-full bg-blue-600 text-white font-bold py-2 px-4 rounded-md hover:bg-blue-700 transition">Apply Global Styles</button>
                            </div>
                        </div>

                        <div id="panel-layout" class="control-panel">
                            <h3>↕️ Component Layout</h3>
                            <p class="text-xs text-gray-500 mb-4">Drag and drop to change the vertical order of the components on your page.</p>
                            <div id="layout-builder-container" class="space-y-2"></div>
                        </div>

                        <div id="panel-product-ticker" class="control-panel">
                            <div class="flex justify-between items-center mb-6">
                               <h3 class="mb-0 pb-0 border-b-0">🏷️ Product Ticker</h3>
                               <button class="get-component-code-btn text-sm bg-indigo-500 text-white py-1 px-3 rounded-md hover:bg-indigo-600" data-component-key="productTicker">
                                   <i class="fas fa-code mr-1"></i> Get Code
                               </button>
                           </div>

                            <div class="space-y-6">
                                <div class="flex items-center space-x-2">
                                    <input type="checkbox" id="product-ticker-toggle" class="h-4 w-4 rounded">
                                    <label for="product-ticker-toggle" class="font-medium">Enable Product Ticker</label>
                                </div>
                                
                                <div id="product-ticker-builder" class="space-y-6">
                                    <div class="space-y-4 p-4 border rounded-md">
                                         <h4 class="font-semibold text-md border-b pb-2">Horizontal Scrolling Behavior</h4>
                                         <div class="grid grid-cols-1 gap-4">
                                             <div>
                                                <label for="product-ticker-scroll-speed" class="text-sm font-medium">Scroll Speed: <span id="product-ticker-speed-value">50</span>px/s</label>
                                                <input type="range" id="product-ticker-scroll-speed" min="10" max="200" value="50" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer mt-1">
                                            </div>
                                            <div>
                                                <label for="product-ticker-scroll-direction" class="text-sm font-medium">Scroll Direction</label>
                                                <select id="product-ticker-scroll-direction" class="w-full p-1 border rounded-md text-sm mt-1">
                                                    <option value="ltr">Left to Right</option>
                                                    <option value="rtl">Right to Left</option>
                                                </select>
                                            </div>
                                         </div>
                                         <div class="grid grid-cols-2 gap-x-4 gap-y-2 text-sm pt-4 border-t mt-4">
                                            <label class="flex items-center space-x-2"><input type="checkbox" id="product-ticker-autoscroll" class="rounded"><span>Auto Scroll</span></label>
                                            <label class="flex items-center space-x-2"><input type="checkbox" id="product-ticker-loop" class="rounded"><span>Loop</span></label>
                                            <label class="flex items-center space-x-2"><input type="checkbox" id="product-ticker-pause-hover" class="rounded"><span>Pause on Hover</span></label>
                                            <label class="flex items-center space-x-2"><input type="checkbox" id="product-ticker-play-pause" class="rounded"><span>Show Play/Pause</span></label>
                                            <label class="flex items-center space-x-2"><input type="checkbox" id="product-ticker-new-tab" class="rounded"><span>Open Links in New Tab</span></label>
                                            <label class="flex items-center space-x-2"><input type="checkbox" id="product-ticker-edge-gradient" class="rounded"><span>Enable Fading Edges</span></label>
                                        </div>
                                    </div>

                                    <div class="space-y-4 p-4 border rounded-md">
                                         <h4 class="font-semibold text-md border-b pb-2">Ticker Items</h4>
                                         <div id="product-ticker-items-container" class="space-y-4"></div>
                                         <button id="add-product-ticker-item-btn" class="text-sm bg-blue-500 text-white py-2 px-4 rounded-md hover:bg-blue-600 w-full"><i class="fas fa-plus mr-1"></i> Add Item</button>
                                    </div>
                                    
                                     <div class="space-y-4 p-4 border rounded-md">
                                        <h4 class="font-semibold text-md border-b pb-2">Category Filtering</h4>
                                        <div>
                                            <label for="product-ticker-filter" class="text-sm font-medium">Show Category</label>
                                            <select id="product-ticker-filter" class="w-full p-1 border rounded-md text-sm mt-1"></select>
                                        </div>
                                    </div>

                                </div>
                            </div>
                        </div>
                        <div id="panel-custom-html" class="control-panel">
                             <div class="flex justify-between items-center mb-6">
                                <h3 class="mb-0 pb-0 border-b-0"> </> Custom HTML</h3>
                                <button class="get-component-code-btn text-sm bg-indigo-500 text-white py-1 px-3 rounded-md hover:bg-indigo-600" data-component-key="customHtml">
                                    <i class="fas fa-code mr-1"></i> Get Code
                                </button>
                            </div>
                             <div class="space-y-4">
                                <div class="flex items-center space-x-2 border-b pb-4">
                                    <input type="checkbox" id="custom-html-toggle" class="h-4 w-4 rounded">
                                    <label for="custom-html-toggle" class="font-medium">Enable Custom HTML Section</label>
                                </div>
                                <div id="custom-html-builder">
                                    <label for="custom-html-content" class="text-sm font-medium">HTML Content</label>
                                    <p class="text-xs text-gray-500 mb-2">Paste any valid HTML. Be cautious, as invalid code can break the page layout.</p>
                                    <textarea id="custom-html-content" rows="10" class="w-full p-2 border rounded-md font-mono text-sm"></textarea>
                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </aside>


            <main class="w-2/3 bg-gray-200 p-4 flex flex-col items-center justify-center overflow-hidden">
                <div id="preview-container" class="bg-white shadow-lg rounded-lg w-full h-full overflow-hidden">
                    <iframe id="preview-iframe" class="preview-iframe"></iframe>
                </div>
            </main>

        </div>
    </div>
    <div id="toast-notification" class="toast"></div>

    <div id="code-modal" class="hidden fixed inset-0 bg-gray-600 bg-opacity-75 overflow-y-auto h-full w-full z-50">
        <div class="relative top-10 mx-auto p-5 border w-11/12 md:w-2/3 shadow-lg rounded-md bg-white">
            <div class="flex justify-between items-center border-b pb-3">
                 <h3 id="code-modal-title" class="text-lg leading-6 font-medium text-gray-900">Component Code</h3>
                 <button id="close-code-modal-btn" class="text-gray-400 hover:text-gray-600">&times;</button>
            </div>
            <div class="mt-4 space-y-4">
                <div>
                    <label class="font-semibold text-gray-700">HTML</label>
                    <pre id="code-modal-html" class="code-modal-pre"><code></code></pre>
                </div>
                 <div>
                    <label class="font-semibold text-gray-700">CSS</label>
                    <pre id="code-modal-css" class="code-modal-pre"><code></code></pre>
                </div>
                 <div>
                    <label class="font-semibold text-gray-700">JavaScript</label>
                    <pre id="code-modal-js" class="code-modal-pre"><code></code></pre>
                </div>
            </div>
            <div class="items-center px-4 py-3 mt-4 text-right bg-gray-50 -mx-5 -mb-5 rounded-b-md">
                <button id="download-component-zip-btn" class="px-4 py-2 bg-green-600 text-white text-base font-medium rounded-md shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-300">
                    Download .zip
                </button>
                <button id="close-code-modal-btn-2" class="px-4 py-2 bg-gray-200 text-gray-800 text-base font-medium rounded-md shadow-sm hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-300 ml-2">
                    Close
                </button>
            </div>
        </div>
    </div>


    <script>
    document.addEventListener('DOMContentLoaded', () => {
        let cke_instances = {}; // To hold CKEditor instances

        // State object to hold all configurations
        const config = {
            globalSettings: {
                colors: {
                    primary: '#3b82f6',
                    secondary: '#10b981',
                    text: '#374151',
                    heading: '#111827',
                },
                typography: {
                    fontFamily: "'Inter', sans-serif",
                }
            },
            componentOrder: [
                'productTicker',
                'customHtml'
            ],
            productTicker: {
                enabled: true,
                settings: {
                    displayMode: 'horizontal-scroll',
                    scrollSpeed: 50,
                    autoScroll: true,
                    loop: true,
                    pauseOnHover: true,
                    showPlayPause: true,
                    openInNewTab: true,
                    useEdgeGradient: true,
                    scrollDirection: 'ltr',
                },
                items: [
                    { id: 1, title: 'New Mock Test Series', link: '#', image: 'https://via.placeholder.com/400x225/3b82f6/ffffff?text=Test', price: '$25', discountPrice: '$19', description: '<p>Prepare with the <b>latest exam pattern</b>. Includes 20 full-length mock tests and detailed performance analysis.</p>', category: 'Mock Tests', tags: 'New' },
                    { id: 2, title: 'Advanced React Course', link: '#', image: 'https://via.placeholder.com/400x225/10b981/ffffff?text=Course', price: '$99', discountPrice: '$79', description: '<p>Master React from fundamentals to advanced hooks, context API, and performance optimization.</p>', category: 'Courses', tags: 'Best Seller' },
                    { id: 3, title: 'Exam Date Alert: SBI PO', link: '#', image: 'https://via.placeholder.com/400x225/ef4444/ffffff?text=Alert', price: 'Free', discountPrice: '', description: '<p>The mains exam is scheduled for <b>December 25th</b>. Download your admit card now.</p>', category: 'Alerts', tags: 'Hot' },
                    { id: 4, title: 'Python for Data Science', link: '#', image: 'https://via.placeholder.com/400x225/f59e0b/ffffff?text=Course', price: '$79', discountPrice: '', description: '<p>A comprehensive course to master <i>Pandas, NumPy, Matplotlib, and Scikit-learn</i> for data analysis.</p>', category: 'Courses', tags: '' },
                ],
                filter: 'All'
            },
            customHtml: {
                enabled: false,
                content: ''
            }
        };

        const componentNames = {
            productTicker: 'Product Ticker',
            customHtml: 'Custom HTML'
        };

        // UI Element References
        const ui = {
            previewIframe: document.getElementById('preview-iframe'),
            controls: {
                nav: document.getElementById('controls-nav'),
                panels: document.getElementById('controls-panels'),
            },
            globalSettings: {
                primaryColor: document.getElementById('global-color-primary'),
                secondaryColor: document.getElementById('global-color-secondary'),
                textColor: document.getElementById('global-color-text'),
                headingColor: document.getElementById('global-color-heading'),
                fontFamily: document.getElementById('global-font-family'),
                applyBtn: document.getElementById('apply-global-settings'),
            },
            layout: {
                container: document.getElementById('layout-builder-container'),
                panel: document.getElementById('panel-layout')
            },
            productTicker: {
                panel: document.getElementById('panel-product-ticker'),
                toggle: document.getElementById('product-ticker-toggle'),
                builder: document.getElementById('product-ticker-builder'),
                scrollSpeed: document.getElementById('product-ticker-scroll-speed'),
                speedValue: document.getElementById('product-ticker-speed-value'),
                autoScroll: document.getElementById('product-ticker-autoscroll'),
                loop: document.getElementById('product-ticker-loop'),
                pauseOnHover: document.getElementById('product-ticker-pause-hover'),
                showPlayPause: document.getElementById('product-ticker-play-pause'),
                openInNewTab: document.getElementById('product-ticker-new-tab'),
                itemsContainer: document.getElementById('product-ticker-items-container'),
                addItemBtn: document.getElementById('add-product-ticker-item-btn'),
                filter: document.getElementById('product-ticker-filter'),
                edgeGradient: document.getElementById('product-ticker-edge-gradient'),
                scrollDirection: document.getElementById('product-ticker-scroll-direction'),
            },
            customHtml: {
                toggle: document.getElementById('custom-html-toggle'),
                content: document.getElementById('custom-html-content'),
            },
            buttons: {
                desktop: document.getElementById('desktop-btn'),
                tablet: document.getElementById('tablet-btn'),
                mobile: document.getElementById('mobile-btn'),
                import: document.getElementById('import-btn'),
                importFile: document.getElementById('import-file-input'),
            },
            exportMenu: {
                container: document.getElementById('export-menu-container'),
                button: document.getElementById('export-menu-btn'),
                dropdown: document.getElementById('export-dropdown'),
                copyCombined: document.getElementById('copy-combined-code'),
                copyHtml: document.getElementById('copy-html'),
                copyCss: document.getElementById('copy-css'),
                copyJs: document.getElementById('copy-js'),
                downloadZip: document.getElementById('download-zip-btn'),
            },
            codeModal: {
                modal: document.getElementById('code-modal'),
                title: document.getElementById('code-modal-title'),
                htmlContainer: document.getElementById('code-modal-html'),
                cssContainer: document.getElementById('code-modal-css'),
                jsContainer: document.getElementById('code-modal-js'),
                htmlCode: document.querySelector('#code-modal-html code'),
                cssCode: document.querySelector('#code-modal-css code'),
                jsCode: document.querySelector('#code-modal-js code'),
                downloadBtn: document.getElementById('download-component-zip-btn'),
                closeBtns: [document.getElementById('close-code-modal-btn'), document.getElementById('close-code-modal-btn-2')],
            },
            previewContainer: document.getElementById('preview-container'),
        };

        // --- Event Listeners ---
        function setupEventListeners() {
            ui.controls.nav.addEventListener('click', (e) => {
                const button = e.target.closest('.control-nav-button');
                if (!button) return;
                const targetPanelId = button.dataset.target;
                ui.controls.nav.querySelectorAll('.control-nav-button').forEach(btn => btn.classList.remove('active'));
                button.classList.add('active');
                ui.controls.panels.querySelectorAll('.control-panel').forEach(panel => {
                    panel.classList.toggle('active', `#${panel.id}` === targetPanelId);
                });
            });
            
            // Global Settings Listeners
            ui.globalSettings.primaryColor.addEventListener('input', e => config.globalSettings.colors.primary = e.target.value);
            ui.globalSettings.secondaryColor.addEventListener('input', e => config.globalSettings.colors.secondary = e.target.value);
            ui.globalSettings.textColor.addEventListener('input', e => config.globalSettings.colors.text = e.target.value);
            ui.globalSettings.headingColor.addEventListener('input', e => config.globalSettings.colors.heading = e.target.value);
            ui.globalSettings.fontFamily.addEventListener('change', e => config.globalSettings.typography.fontFamily = e.target.value);
            ui.globalSettings.applyBtn.addEventListener('click', () => {
                renderAll();
                showToast('Global styles applied!');
            });


            // Layout Controls
            ui.layout.panel.addEventListener('click', handleLayoutControlsClick);
            setupDragAndDrop();

            // Component Listeners
            setupProductTickerListeners();
            ui.customHtml.toggle.addEventListener('change', e => { config.customHtml.enabled = e.target.checked; renderAll(); });
            ui.customHtml.content.addEventListener('input', e => { config.customHtml.content = e.target.value; renderAll(); });

            // Preview & Export
            ui.buttons.desktop.addEventListener('click', () => setPreviewMode('desktop'));
            ui.buttons.tablet.addEventListener('click', () => setPreviewMode('tablet'));
            ui.buttons.mobile.addEventListener('click', () => setPreviewMode('mobile'));
            ui.exportMenu.button.addEventListener('click', (e) => { e.stopPropagation(); ui.exportMenu.dropdown.classList.toggle('hidden'); });
            window.addEventListener('click', (e) => { if (!ui.exportMenu.container.contains(e.target)) { ui.exportMenu.dropdown.classList.add('hidden'); } });
            
            const copyAction = (e, dataGetter, message) => {
                e.preventDefault();
                navigator.clipboard.writeText(dataGetter()).then(() => showToast(message));
                ui.exportMenu.dropdown.classList.add('hidden');
            };
            
            ui.exportMenu.copyCombined.addEventListener('click', (e) => copyAction(e, getCombinedCode, 'Combined code copied!'));
            ui.exportMenu.copyHtml.addEventListener('click', (e) => copyAction(e, getAllHtml, 'All HTML copied!'));
            ui.exportMenu.copyCss.addEventListener('click', (e) => copyAction(e, getFullCSS, 'All CSS copied!'));
            ui.exportMenu.copyJs.addEventListener('click', (e) => copyAction(e, getFullJS, 'All JS copied!'));
            ui.exportMenu.downloadZip.addEventListener('click', (e) => { e.preventDefault(); generatePageZip(); ui.exportMenu.dropdown.classList.add('hidden'); });
            
            // Import
            ui.buttons.import.addEventListener('click', () => ui.buttons.importFile.click());
            ui.buttons.importFile.addEventListener('change', handleFileImport);

            // Code Modal Listeners
            ui.controls.panels.addEventListener('click', handleGetCodeClick);
            ui.codeModal.closeBtns.forEach(btn => btn.addEventListener('click', () => ui.codeModal.modal.classList.add('hidden')));
            ui.codeModal.modal.addEventListener('click', (e) => {
                if (e.target.id === 'code-modal-html' || e.target.id === 'code-modal-css' || e.target.id === 'code-modal-js') {
                    const code = e.target.querySelector('code').innerText;
                    navigator.clipboard.writeText(code).then(() => showToast('Copied to clipboard!'));
                }
            });
        }
        
        // --- LAYOUT CONTROLS ---
        function renderLayoutControls() {
            ui.layout.container.innerHTML = config.componentOrder.map((key, index) => {
                const total = config.componentOrder.length;
                return `
                <div class="layout-item p-3 border rounded-md bg-white flex items-center justify-between" draggable="true" data-key="${key}">
                    <span class="font-medium text-sm"><i class="fas fa-grip-vertical mr-3 text-gray-400"></i> ${componentNames[key]}</span>
                    <div class="item-toolbar mb-0">
                        <button class="reorder-layout-up-btn text-xs bg-gray-200 text-gray-700 p-1 rounded-md hover:bg-gray-300" data-index="${index}" ${index === 0 ? 'disabled' : ''}><i class="fas fa-arrow-up fa-fw"></i></button>
                        <button class="reorder-layout-down-btn text-xs bg-gray-200 text-gray-700 p-1 rounded-md hover:bg-gray-300" data-index="${index}" ${index === total - 1 ? 'disabled' : ''}><i class="fas fa-arrow-down fa-fw"></i></button>
                    </div>
                </div>`;
            }).join('');
        }

        function handleLayoutControlsClick(e) {
            const button = e.target.closest('button');
            if (!button) return;
            
            const index = parseInt(button.dataset.index, 10);
            const order = config.componentOrder;
            let changed = false;

            if (button.classList.contains('reorder-layout-up-btn') && index > 0) {
                [order[index], order[index - 1]] = [order[index - 1], order[index]];
                changed = true;
            } else if (button.classList.contains('reorder-layout-down-btn') && index < order.length - 1) {
                [order[index], order[index + 1]] = [order[index + 1], order[index]];
                changed = true;
            }

            if(changed) {
                renderLayoutControls();
                renderAll();
            }
        }
        
        function setupDragAndDrop() {
            let draggedItem = null;

            ui.layout.container.addEventListener('dragstart', e => {
                draggedItem = e.target;
                setTimeout(() => {
                    e.target.style.display = 'none';
                }, 0);
            });

            ui.layout.container.addEventListener('dragend', e => {
                setTimeout(() => {
                    draggedItem.style.display = 'flex';
                    draggedItem = null;
                }, 0);
            });
            
            ui.layout.container.addEventListener('dragover', e => {
                e.preventDefault();
                const afterElement = getDragAfterElement(ui.layout.container, e.clientY);
                if (afterElement == null) {
                    ui.layout.container.appendChild(draggedItem);
                } else {
                    ui.layout.container.insertBefore(draggedItem, afterElement);
                }
            });

            ui.layout.container.addEventListener('drop', e => {
                 e.preventDefault();
                 const newOrderKeys = [...ui.layout.container.querySelectorAll('.layout-item')].map(item => item.dataset.key);
                 config.componentOrder = newOrderKeys;
                 renderLayoutControls();
                 renderAll();
            });
        }

        function getDragAfterElement(container, y) {
            const draggableElements = [...container.querySelectorAll('.layout-item:not(.dragging)')];

            return draggableElements.reduce((closest, child) => {
                const box = child.getBoundingClientRect();
                const offset = y - box.top - box.height / 2;
                if (offset < 0 && offset > closest.offset) {
                    return { offset: offset, element: child };
                } else {
                    return closest;
                }
            }, { offset: Number.NEGATIVE_INFINITY }).element;
        }


        // --- HTML Generation Logic ---
        const componentGenerators = {
            productTicker: generateProductTickerHTML,
            customHtml: generateCustomHtmlHTML
        };
        
        function getAllHtml() {
            return config.componentOrder
                .map(key => componentGenerators[key] ? componentGenerators[key]() : '')
                .filter(Boolean)
                .join('\n\n');
        }

        function generateProductTickerHTML() {
            if (!config.productTicker.enabled) return '';
            const { settings, filter } = config.productTicker;
            const items = config.productTicker.items.filter(item => filter === 'All' || item.category === filter);
            
            if (items.length === 0) return '';
            
            // Sanitize and escape the items array for data attribute
            const sanitizedItems = items.map(item => ({...item, description: item.description.replace(/'/g, '&apos;')}));


            const itemsHtml = items.map((item, index) => {
                const hasDiscount = item.discountPrice && item.discountPrice.trim() !== '';
                const priceHtml = hasDiscount
                    ? `<span class="ticker-item-discount-price">${item.discountPrice}</span><s class="ticker-item-original-price">${item.price}</s>`
                    : `<span class="ticker-item-price">${item.price}</span>`;

                // For the ticker itself, strip HTML from description for a clean look
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = item.description || '';
                const plainTextDescription = tempDiv.textContent || tempDiv.innerText || '';

                return `
                <a href="${item.link || '#'}" class="ticker-item" ${settings.openInNewTab ? 'target="_blank"' : ''} data-item-index="${index}">
                    ${item.image ? `<img src="${item.image}" alt="${item.title}" class="ticker-item-image">` : ''}
                    <div class="ticker-item-content">
                        <h4 class="ticker-item-title">${item.title}</h4>
                        <p class="ticker-item-desc">${plainTextDescription}</p>
                    </div>
                    <div class="ticker-item-price-wrapper">${priceHtml}</div>
                    ${item.tags ? `<div class="ticker-item-tag">${item.tags}</div>` : ''}
                </a>
            `}).join('');

            return `
            <div id="product-ticker-wrapper">
                <div id="product-ticker-component" 
                    class="product-ticker-container ${settings.useEdgeGradient ? 'has-edge-gradient' : ''}" 
                    data-settings='${JSON.stringify(settings)}' 
                    data-direction="${settings.scrollDirection}"
                    data-items='${JSON.stringify(sanitizedItems)}'>
                    <div class="ticker-wrap">
                        <div class="ticker-move">${itemsHtml}</div>
                        ${settings.loop ? `<div class="ticker-move" aria-hidden="true">${itemsHtml}</div>` : ''}
                    </div>
                    ${settings.showPlayPause ? `
                    <button class="ticker-play-pause" aria-label="Play/Pause Ticker">
                        <span class="play-icon">&#9658;</span><span class="pause-icon" style="display:none;">&#10074;&#10074;</span>
                    </button>
                    ` : ''}
                </div>
            </div>
            <div id="product-ticker-details-container"></div>
            `;
        }
        
        function generateCustomHtmlHTML() {
            if (!config.customHtml.enabled) return '';
            return `<div class="custom-html-section">${config.customHtml.content}</div>`;
        }

        function generateComponentCSS(targetKey = null) {
            const { colors, typography } = config.globalSettings;
            const css = {};

            css.global = `
/* --- Global --- */
:root {
    --primary-color: ${colors.primary};
    --primary-hover-color: ${colors.primary}; /* Use same color, adjust opacity on hover */
    --secondary-color: ${colors.secondary};
    --text-color: ${colors.text};
    --heading-color: ${colors.heading};
    --font-family: ${typography.fontFamily};
}
body { 
    font-family: var(--font-family); 
    color: var(--text-color);
    margin: 0; 
    background-color: #f0f2f5;
    overflow-x: hidden; /* Prevent horizontal scroll from full-width element */
}
h1,h2,h3,h4,h5,h6 {
    color: var(--heading-color);
}
.container { max-width: 1280px; }
a { text-decoration: none; transition: color 0.2s; color: var(--primary-color); }
`;

            if(config.productTicker.enabled) css.productTicker = `
/* --- Product Ticker --- */
@keyframes scroll-horizontal-ltr {
  from { transform: translateX(0%); }
  to { transform: translateX(-100%); }
}
@keyframes scroll-horizontal-rtl {
  from { transform: translateX(-100%); }
  to { transform: translateX(0%); }
}
#product-ticker-wrapper {
    width: 100vw;
    position: relative;
    left: 50%;
    transform: translateX(-50%);
}
.product-ticker-container {
    position: relative;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0,0,0,0.08);
    display: flex;
    align-items: center;
    overflow: hidden;
    padding: 0.25rem 0;
}
.ticker-wrap {
    flex-grow: 1;
    overflow: hidden;
    display: flex;
}
.ticker-move {
    display: flex;
    white-space: nowrap;
    animation-name: scroll-horizontal-ltr;
    animation-timing-function: linear;
    animation-iteration-count: infinite;
}
[data-direction="rtl"] .ticker-move {
    animation-name: scroll-horizontal-rtl;
}
.product-ticker-container.paused .ticker-move {
    animation-play-state: paused;
}
.ticker-item {
    display: flex;
    align-items: center;
    padding: 0.5rem 1.5rem;
    gap: 1rem;
    color: var(--text-color);
    flex-shrink: 0;
    transition: background-color 0.3s;
    border-right: 1px solid #e5e7eb;
    position: relative;
}
.ticker-item-image {
    height: 40px;
    aspect-ratio: 16 / 9;
    object-fit: cover;
    border-radius: 0.25rem;
    flex-shrink: 0;
}
.ticker-item-content {
    display: flex;
    flex-direction: column;
    min-width: 0;
    white-space: normal;
    flex-grow: 1;
    max-width: 250px;
}
.ticker-item-title {
    font-weight: 600;
    font-size: 0.9rem;
    color: var(--heading-color);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.ticker-item-desc {
    font-size: 0.8rem;
    color: var(--text-color);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.ticker-item-price-wrapper {
    display: flex;
    align-items: center;
    gap: 0.5rem;
    margin-left: auto;
    padding-left: 1rem;
    white-space: nowrap;
}
.ticker-item-price {
    font-weight: 700;
    color: var(--primary-color);
}
.ticker-item-discount-price {
    font-weight: 700;
    font-size: 1rem;
    color: var(--primary-color);
}
.ticker-item-original-price {
    text-decoration: line-through;
    color: #9ca3af;
    font-size: 0.8rem;
}
.ticker-item-tag {
    background-color: var(--secondary-color);
    color: white;
    font-size: 0.7rem;
    font-weight: 700;
    padding: 2px 6px;
    border-radius: 1rem;
    margin-left: 1rem;
    white-space: nowrap;
}
.ticker-play-pause {
    background: rgba(255,255,255,0.8);
    border: 1px solid #e5e7eb;
    border-radius: 50%;
    width: 32px;
    height: 32px;
    cursor: pointer;
    flex-shrink: 0;
    margin: 0 0.5rem;
    transition: all 0.2s;
    z-index: 10;
}
.ticker-play-pause:hover {
    background-color: var(--primary-color);
    color: white;
    border-color: var(--primary-color);
}
/* --- Details View Below Ticker (Modified for Popup Behavior) --- */
#product-ticker-details-container {
    position: fixed; /* Changed from relative to fixed for overlay */
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.6); /* Added semi-transparent background */
    display: flex; /* Using flexbox to center the card */
    align-items: center;
    justify-content: center;
    z-index: 1000; /* Ensure it's on top of other content */
    
    /* Transition opacity and visibility instead of height */
    opacity: 0;
    visibility: hidden;
    transition: opacity 0.3s ease-in-out, visibility 0.3s ease-in-out;
}
#product-ticker-details-container.visible {
    opacity: 1;
    visibility: visible;
    
    /* Remove properties related to the old slide-down effect */
    max-height: none; 
    padding-top: 0;
    padding-bottom: 0;
    border-top: none;
}
.details-card {
    display: flex;
    flex-wrap: wrap;
    gap: 1.5rem;
    max-width: 680px; 
    width: 90%; /* Added responsive width */
    margin: 0; /* Removed auto margin */
    background: #ffffff;
    padding: 1.5rem;
    border-radius: 0.5rem;
    box-shadow: 0 4px 20px rgba(0,0,0,0.15);
    transform: scale(0.95); /* Add a subtle scale effect */
    transition: transform 0.3s ease-in-out;
}
#product-ticker-details-container.visible .details-card {
    transform: scale(1); /* Scale to full size when visible */
}
.details-card-image-wrapper {
    flex-shrink: 0;
    width: 100%;
    max-width: 250px;
}
.details-card-image {
    width: 100%;
    height: auto;
    aspect-ratio: 16 / 9;
    object-fit: cover;
    border-radius: 0.375rem;
}
.details-card-content {
    flex: 1;
    min-width: 280px;
    display: flex;
    flex-direction: column;
}
.details-card-content h3 {
    font-size: 1.5rem;
    font-weight: 700;
    color: var(--heading-color);
    margin-top: 0;
}
.details-card-tag {
    display: inline-block;
    background-color: var(--secondary-color);
    color: white;
    font-size: 0.75rem;
    font-weight: 700;
    padding: 4px 10px;
    border-radius: 99px;
    margin-top: 0.5rem;
}
.details-card-description {
    font-size: 0.9rem;
    line-height: 1.6;
    color: var(--text-color);
    margin: 1rem 0;
    flex-grow: 1; /* Pushes footer to bottom */
}
.details-card-footer {
    border-top: 1px solid #f3f4f6;
    padding-top: 1rem;
    display: flex;
    justify-content: space-between;
    align-items: center;
    gap: 1rem;
}
.details-card-price-wrapper {
    display: flex;
    align-items: center;
    gap: 0.75rem;
    font-size: 1.1rem;
}
.details-card-button {
    display: inline-block;
    width: auto;
    text-align: center;
    background-color: var(--primary-color);
    color: white !important;
    padding: 0.5rem 1rem;
    border-radius: 0.375rem;
    text-decoration: none;
    font-weight: 600;
    transition: opacity 0.2s;
    flex-shrink: 0;
}
.details-card-button:hover {
    opacity: 0.85;
}
/* Edge Gradients */
.product-ticker-container.has-edge-gradient::before,
.product-ticker-container.has-edge-gradient::after {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    width: 60px;
    z-index: 2;
    pointer-events: none;
}
.product-ticker-container.has-edge-gradient::before {
    left: 0;
    background: linear-gradient(to right, #fff, transparent);
}
.product-ticker-container.has-edge-gradient::after {
    right: 0;
    background: linear-gradient(to left, #fff, transparent);
}
`;

            if(config.customHtml.enabled) css.customHtml = `
/* --- Custom HTML Section --- */
.custom-html-section { padding: 1rem 0; }`;

            if (targetKey) {
                return {
                    global: css.global,
                    component: css[targetKey] || ''
                }
            }
            return css;
        }

        function getFullCSS() {
            const cssObject = generateComponentCSS();
            const orderedCSS = config.componentOrder.map(key => cssObject[key]).filter(Boolean);
            return [cssObject.global, ...orderedCSS].join('\n\n');
        }
        
        function generateComponentJavaScript(targetKey = null) {
            const js = {};
            
            if (config.productTicker.enabled) {
                js.productTicker = `
// --- Product Ticker Logic ---
const tickerComponent = document.getElementById('product-ticker-component');
if (tickerComponent) {
    // --- Scrolling Logic ---
    const settings = JSON.parse(tickerComponent.dataset.settings);
    const tickerMove = tickerComponent.querySelector('.ticker-move');
    const playPauseBtn = tickerComponent.querySelector('.ticker-play-pause');
    const playIcon = playPauseBtn ? playPauseBtn.querySelector('.play-icon') : null;
    const pauseIcon = playPauseBtn ? playPauseBtn.querySelector('.pause-icon') : null;

    const togglePlayState = (paused) => {
        tickerComponent.classList.toggle('paused', paused);
        if (playIcon && pauseIcon) {
            playIcon.style.display = paused ? 'inline' : 'none';
            pauseIcon.style.display = paused ? 'none' : 'inline';
        }
    };
    if (tickerMove && tickerMove.scrollWidth > 0) {
        const contentWidth = tickerMove.scrollWidth / (settings.loop ? 2 : 1);
        const duration = contentWidth / settings.scrollSpeed;
        tickerComponent.querySelectorAll('.ticker-move').forEach(el => {
            el.style.animationDuration = duration + 's';
        });
        togglePlayState(!settings.autoScroll);
    }
    if (settings.pauseOnHover) {
        tickerComponent.addEventListener('mouseenter', () => !tickerComponent.classList.contains('manual-pause') && togglePlayState(true));
        tickerComponent.addEventListener('mouseleave', () => !tickerComponent.classList.contains('manual-pause') && togglePlayState(false));
    }
    if (playPauseBtn) {
        if (pauseIcon && settings.autoScroll) {
            pauseIcon.style.display = 'inline';
            playIcon.style.display = 'none';
        }
        playPauseBtn.addEventListener('click', () => {
            const isPaused = tickerComponent.classList.contains('paused');
            tickerComponent.classList.toggle('manual-pause', isPaused);
            togglePlayState(!isPaused);
        });
    }

    // --- Details View Logic (MODIFIED FOR CLICK) ---
    const detailsContainer = document.getElementById('product-ticker-details-container');
    const itemsData = JSON.parse(tickerComponent.dataset.items.replace(/&apos;/g, "'"));
    const tickerItems = tickerComponent.querySelectorAll('.ticker-item');

    const showDetails = (item) => {
        if (!item || !detailsContainer) return;
        const hasDiscount = item.discountPrice && item.discountPrice.trim() !== '';
        const priceHtml = hasDiscount
            ? \`<span class="ticker-item-discount-price">\${item.discountPrice}</span><s class="ticker-item-original-price">\${item.price}</s>\`
            : \`<span class="ticker-item-price">\${item.price}</span>\`;

        const cardHtml = \`
            <div class="details-card">
                \${item.image ? \`
                <div class="details-card-image-wrapper">
                    <img src="\${item.image}" alt="\${item.title}" class="details-card-image">
                </div>
                \` : ''}
                <div class="details-card-content">
                    <div>
                        <h3>\${item.title}</h3>
                        \${item.tags ? \`<div class="details-card-tag">\${item.tags}</div>\` : ''}
                        <div class="details-card-description">\${item.description}</div>
                    </div>
                    <div class="details-card-footer">
                        <div class="details-card-price-wrapper">\${priceHtml}</div>
                        <a href="\${item.link || '#'}" class="details-card-button" \${settings.openInNewTab ? 'target="_blank" rel="noopener"' : ''}>Enroll Now</a>
                    </div>
                </div>
            </div>
        \`;
        detailsContainer.innerHTML = cardHtml;
        detailsContainer.classList.add('visible');
    };

    const hideDetails = () => {
        if (detailsContainer) detailsContainer.classList.remove('visible');
    };

    tickerItems.forEach(tickerItem => {
        tickerItem.addEventListener('click', (e) => {
            e.preventDefault(); // Prevent the link from being followed immediately
            const index = e.currentTarget.dataset.itemIndex;
            showDetails(itemsData[index]);
        });
    });

    if (detailsContainer) {
        // Add a click listener to the container (the overlay)
        detailsContainer.addEventListener('click', (e) => {
            // If the click is on the background (the container itself) and not the card, hide immediately.
            if (!e.target.closest('.details-card')) {
                hideDetails();
            }
        });
    }
}`;
            }
             
             if (targetKey) {
                return js[targetKey] || '';
            }
            return js;
        }

        function getFullJS() {
             const jsObject = generateComponentJavaScript();
             return config.componentOrder.map(key => {
                let script = jsObject[key] || '';
                return script;
             }).filter(Boolean).join('\n\n');
        }

        function getCombinedCode() {
            const htmlBody = getAllHtml();
            const css = getFullCSS();
            let js = getFullJS();
            if (js.trim()) {
                js = `document.addEventListener('DOMContentLoaded', () => { \n${js.trim()} \n});`;
            }

            return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exported Page</title>
    <script src="https://cdn.tailwindcss.com"><\/script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Open+Sans:wght@400;700&family=Lato:wght@400;700&family=Montserrat:wght@400;700&family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <style>
        ${css}
    </style>
</head>
<body class="bg-gray-100">
    ${htmlBody}
    ${js ? `<script>${js}<\/script>` : ''}
</body>
</html>`;
        }
        
        // --- Rendering ---
        const debouncedRenderAll = debounce(renderAll, 500);
        function renderAll() {
            const fullJs = getFullJS();
            const previewContent = `<!DOCTYPE html><html><head><title>Preview</title>
            <script src="https://cdn.tailwindcss.com"><\/script>
            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
            <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
            <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Open+Sans:wght@400;700&family=Lato:wght@400;700&family=Montserrat:wght@400;700&family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
            <style>${getFullCSS()}</style></head><body>
            <div class="site-wrapper">
                ${getAllHtml()}
                <div style="min-height: 400px; padding: 40px; text-align: center; color: #6b7280; font-family: 'Inter', sans-serif;"></div>
            </div>
            <script>
                ${fullJs ? `document.addEventListener('DOMContentLoaded', () => { \n${fullJs} \n});` : ''}
            <\/script></body></html>`;
            
            ui.previewIframe.srcdoc = previewContent;
        }

        // --- PRODUCT TICKER CONTROLS ---
        function setupProductTickerListeners() {
            const pt = ui.productTicker;
            const ptc = config.productTicker;

            pt.toggle.addEventListener('change', e => { ptc.enabled = e.target.checked; pt.builder.style.display = e.target.checked ? 'block' : 'none'; renderAll(); });
            
            pt.scrollSpeed.addEventListener('input', e => { 
                ptc.settings.scrollSpeed = e.target.value;
                pt.speedValue.textContent = e.target.value;
            });
            pt.scrollSpeed.addEventListener('change', () => renderAll());
            pt.autoScroll.addEventListener('change', e => { ptc.settings.autoScroll = e.target.checked; renderAll(); });
            pt.loop.addEventListener('change', e => { ptc.settings.loop = e.target.checked; renderAll(); });
            pt.pauseOnHover.addEventListener('change', e => { ptc.settings.pauseOnHover = e.target.checked; renderAll(); });
            pt.showPlayPause.addEventListener('change', e => { ptc.settings.showPlayPause = e.target.checked; renderAll(); });
            pt.openInNewTab.addEventListener('change', e => { ptc.settings.openInNewTab = e.target.checked; renderAll(); });
            pt.filter.addEventListener('change', e => { ptc.filter = e.target.value; renderAll(); });
            pt.edgeGradient.addEventListener('change', e => { ptc.settings.useEdgeGradient = e.target.checked; renderAll(); });
            pt.scrollDirection.addEventListener('change', e => { ptc.settings.scrollDirection = e.target.value; renderAll(); });


            pt.addItemBtn.addEventListener('click', () => {
                ptc.items.push({ id: Date.now(), title: 'New Item', link: '#', image: 'https://via.placeholder.com/400x225', price: '$0', discountPrice: '', description: '<p>New item description.</p>', category: 'Courses', tags: '' });
                renderProductTickerItemsEditor();
            });

            pt.itemsContainer.addEventListener('input', e => {
                const target = e.target;
                if(target.matches('input[type="text"]')) { // Only handle standard inputs here
                    const itemDiv = target.closest('.product-ticker-item-editor');
                    if (!itemDiv) return;
                    const itemId = parseInt(itemDiv.dataset.id, 10);
                    const item = ptc.items.find(i => i.id === itemId);
                    if (!item) return;

                    const property = target.dataset.property;
                    if (property) {
                        item[property] = target.value;
                        if(property === 'category') renderProductTickerFilterOptions();
                        debouncedRenderAll();
                    }
                }
            });
            
            pt.itemsContainer.addEventListener('click', e => {
                const button = e.target.closest('button');
                if (!button) return;

                const itemDiv = button.closest('.product-ticker-item-editor');
                if (!itemDiv) return;

                const itemId = parseInt(itemDiv.dataset.id, 10);
                if (button.classList.contains('remove-pt-item-btn')) {
                    // Destroy CKEditor instance before removing
                    if (cke_instances[itemId]) {
                        cke_instances[itemId].destroy().catch(error => console.error(error));
                        delete cke_instances[itemId];
                    }
                    ptc.items = ptc.items.filter(i => i.id !== itemId);
                    renderProductTickerItemsEditor();
                    renderProductTickerFilterOptions();
                    renderAll();
                }
            });
        }
        
        function renderProductTickerItemsEditor() {
            ui.productTicker.itemsContainer.innerHTML = config.productTicker.items.map(item => `
                <div class="product-ticker-item-editor border p-3 rounded-md space-y-2 bg-gray-50" data-id="${item.id}">
                    <div class="flex justify-between items-center">
                        <span class="font-semibold text-sm">Item #${item.id}</span>
                        <button class="remove-pt-item-btn text-red-500 hover:text-red-700 text-xs font-bold">REMOVE</button>
                    </div>
                    <div class="grid grid-cols-2 gap-x-2 gap-y-3 text-xs">
                        <div><label>Title</label><input type="text" data-property="title" value="${item.title}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div><label>Link URL</label><input type="text" data-property="link" value="${item.link}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div class="col-span-2"><label>Image URL</label><input type="text" data-property="image" value="${item.image}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div><label>Original Price</label><input type="text" data-property="price" value="${item.price}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div><label>Discount Price</label><input type="text" data-property="discountPrice" value="${item.discountPrice || ''}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div><label>Category</label><input type="text" data-property="category" value="${item.category}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div><label>Tag (e.g., New)</label><input type="text" data-property="tags" value="${item.tags}" class="w-full p-1 border rounded-md mt-1"></div>
                        <div class="col-span-2">
                            <label>Description (Rich Text)</label>
                            <div class="mt-1">
                                <textarea id="description-editor-${item.id}" data-property="description">${item.description}</textarea>
                            </div>
                        </div>
                    </div>
                </div>
            `).join('');
            
            // After rendering HTML, initialize CKEditor instances
            initializeCKEditors();
        }

        function initializeCKEditors() {
            const ptc = config.productTicker;
            ptc.items.forEach(item => {
                const itemId = item.id;
                const editorElement = document.getElementById(`description-editor-${itemId}`);
                
                if (editorElement && !cke_instances[itemId]) {
                    ClassicEditor
                        .create(editorElement, {
                            toolbar: ['heading', '|', 'bold', 'italic', 'link', 'bulletedList', 'numberedList', 'blockQuote'],
                        })
                        .then(editor => {
                            cke_instances[itemId] = editor; // Store the instance
                            editor.model.document.on('change:data', () => {
                                const data = editor.getData();
                                const currentItem = ptc.items.find(i => i.id === itemId);
                                if (currentItem) {
                                    currentItem.description = data;
                                    debouncedRenderAll();
                                }
                            });
                        })
                        .catch(error => {
                            console.error(`CKEditor initialization error for item ${itemId}:`, error);
                        });
                }
            });
        }
        
        function renderProductTickerFilterOptions() {
            const categories = ['All', ...new Set(config.productTicker.items.map(i => i.category).filter(Boolean))];
            ui.productTicker.filter.innerHTML = categories.map(cat => `<option value="${cat}" ${config.productTicker.filter === cat ? 'selected' : ''}>${cat}</option>`).join('');
        }

        // --- Utility Functions ---
        function debounce(func, timeout = 500){
            let timer;
            return (...args) => {
                clearTimeout(timer);
                timer = setTimeout(() => { func.apply(this, args); }, timeout);
            };
        }

        function setPreviewMode(mode) {
            ui.previewContainer.className = `bg-white shadow-lg rounded-lg w-full h-full overflow-hidden transition-all duration-300 preview-${mode}`;
            ['desktop', 'tablet', 'mobile'].forEach(m => {
                const btn = ui.buttons[m];
                btn.classList.toggle('bg-blue-500', m === mode);
                btn.classList.toggle('text-white', m === mode);
                btn.classList.toggle('shadow', m === mode);
                btn.classList.toggle('bg-gray-200', m !== mode);
                btn.classList.toggle('text-gray-700', m !== mode);
            });
        }

        function showToast(message) {
            const toast = document.getElementById('toast-notification');
            toast.textContent = message;
            toast.classList.add('show');
            setTimeout(() => { toast.classList.remove('show'); }, 3000);
        }
        
        function generatePageZip() {
            const zip = new JSZip();
            const html = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Exported Page</title>
    <script src="https://cdn.tailwindcss.com"><\/script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Open+Sans:wght@400;700&family=Lato:wght@400;700&family=Montserrat:wght@400;700&family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    ${getAllHtml()}
    <script src="script.js"><\/script>
</body>
</html>`;
            const css = getFullCSS();
            const js = getFullJS();

            zip.file("index.html", html);
            zip.file("style.css", css);
            if (js.trim()) {
                zip.file("script.js", `document.addEventListener('DOMContentLoaded', () => { \n${js} \n});`);
            }
            
            zip.generateAsync({type:"blob"}).then(function(content) {
                saveAs(content, "exported-page.zip");
                showToast("ZIP file generated!");
            });
        }
        
        function handleFileImport(event) {
            const file = event.target.files[0];
            if (!file) return;

            const reader = new FileReader();
            reader.onload = function(e) {
                const content = e.target.result;
                try {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(content, 'text/html');
                    parseImportedDocument(doc);
                    showToast('Import successful!');
                } catch (error) {
                    console.error('Error parsing imported file:', error);
                    showToast('Error: Could not parse file.');
                }
                event.target.value = null; // Reset file input
            };
            reader.readAsText(file);
        }

        function parseImportedDocument(doc) {
           console.log("Parsing imported document...");
        }

        function handleGetCodeClick(e) {
            const button = e.target.closest('.get-component-code-btn');
            if (!button) return;

            const key = button.dataset.componentKey;
            if (!key) return;

            const html = componentGenerators[key] ? componentGenerators[key]() : 'Not available';
            const { global, component: css } = generateComponentCSS(key);
            const js = generateComponentJavaScript(key);
            
            ui.codeModal.title.textContent = `${componentNames[key]} Component Code`;
            
            ui.codeModal.htmlCode.textContent = html;
            ui.codeModal.cssCode.textContent = (global + '\n\n' + css).trim();
            
            let jsWithWrapper = js.trim();
            if (jsWithWrapper) {
                 jsWithWrapper = `document.addEventListener('DOMContentLoaded', () => { \n${jsWithWrapper}\n });`;
            }
            ui.codeModal.jsCode.textContent = jsWithWrapper || '// No JavaScript for this component';


            [ui.codeModal.htmlContainer, ui.codeModal.cssContainer, ui.codeModal.jsContainer].forEach(el => {
                if (el.querySelector('code').textContent.trim() === '' || el.querySelector('code').textContent.startsWith('//')) {
                    el.style.display = 'none';
                } else {
                    el.style.display = 'block';
                }
            });

            ui.codeModal.downloadBtn.onclick = () => generateComponentZip(key);
            ui.codeModal.modal.classList.remove('hidden');
        }
        
        function generateComponentZip(key) {
             const zip = new JSZip();
            const { global, component: css } = generateComponentCSS(key);
            const js = generateComponentJavaScript(key);
            const htmlBody = componentGenerators[key] ? componentGenerators[key]() : '';
            
            const html = `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>${componentNames[key]} Component</title>
    <script src="https://cdn.tailwindcss.com"><\/script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&family=Open+Sans:wght@400;700&family=Lato:wght@400;700&family=Montserrat:wght@400;700&family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    ${htmlBody}
    ${js.trim() ? '<script src="script.js"><\/script>' : ''}
</body>
</html>`;
            zip.file("index.html", html);
            zip.file("style.css", (global + '\n\n' + css).trim());
            if (js.trim()) {
                let jsWithWrapper = `document.addEventListener('DOMContentLoaded', () => { \n${js} \n});`;
                zip.file("script.js", jsWithWrapper);
            }
            zip.generateAsync({type:"blob"}).then(function(content) {
                saveAs(content, `${key}-component.zip`);
                showToast("Component ZIP generated!");
            });
        }

        // Initial Load
        function init() {
            const { customHtml, globalSettings, productTicker } = config;
            
            // Init Global Settings
            ui.globalSettings.primaryColor.value = globalSettings.colors.primary;
            ui.globalSettings.secondaryColor.value = globalSettings.colors.secondary;
            ui.globalSettings.textColor.value = globalSettings.colors.text;
            ui.globalSettings.headingColor.value = globalSettings.colors.heading;
            ui.globalSettings.fontFamily.value = globalSettings.typography.fontFamily;

            // Init Product Ticker
            ui.productTicker.toggle.checked = productTicker.enabled;
            ui.productTicker.builder.style.display = productTicker.enabled ? 'block' : 'none';
            ui.productTicker.scrollSpeed.value = productTicker.settings.scrollSpeed;
            ui.productTicker.speedValue.textContent = productTicker.settings.scrollSpeed;
            ui.productTicker.autoScroll.checked = productTicker.settings.autoScroll;
            ui.productTicker.loop.checked = productTicker.settings.loop;
            ui.productTicker.pauseOnHover.checked = productTicker.settings.pauseOnHover;
            ui.productTicker.showPlayPause.checked = productTicker.settings.showPlayPause;
            ui.productTicker.openInNewTab.checked = productTicker.settings.openInNewTab;
            ui.productTicker.edgeGradient.checked = productTicker.settings.useEdgeGradient;
            ui.productTicker.scrollDirection.value = productTicker.settings.scrollDirection;
            renderProductTickerItemsEditor();
            renderProductTickerFilterOptions();
            
            // Init Custom HTML
            ui.customHtml.toggle.checked = customHtml.enabled;
            ui.customHtml.content.value = customHtml.content;

            setupEventListeners();
            
            renderLayoutControls();
            renderAll();
            if(!document.querySelector('.control-nav-button.active')){
                ui.controls.nav.querySelector('.control-nav-button').click();
            }
        }

        init();
    });
    </script>
</body>
</html>