File size: 113,971 Bytes
84e1dd3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6138a2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
<title>Create HTML — AI Pro Suite</title>

<link rel="stylesheet" href="style.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700;800;900&family=JetBrains+Mono:wght@400;500;600;700&display=swap" rel="stylesheet">

<!-- Persistent storage -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/localforage/1.10.0/localforage.min.js"></script>

<!-- Code editor (CodeMirror 5) -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/theme/dracula.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/dialog/dialog.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/codemirror.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/xml/xml.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/javascript/javascript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/css/css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/mode/htmlmixed/htmlmixed.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/edit/matchbrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/edit/closebrackets.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/edit/closetag.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/search/searchcursor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/search/search.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.65.16/addon/dialog/dialog.min.js"></script>

<!-- Code beautifier -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.1/beautify.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.1/beautify-css.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-beautify/1.15.1/beautify-html.min.js"></script>

<!-- Markdown rendering for AI chat -->
<script src="https://cdn.jsdelivr.net/npm/marked@4.3.0/marked.min.js"></script>

<style>

:root{

    --rh-bg: var(--bg-base, #f1f5f9);

    --rh-surface: var(--bg-surface, #ffffff);

    --rh-primary: var(--primary, #8b5cf6);

    --rh-primary-glow: var(--primary-glow, rgba(139,92,246,0.4));

    --rh-secondary: var(--secondary, #3b82f6);

    --rh-secondary-glow: var(--secondary-glow, rgba(59,130,246,0.4));

    --rh-accent: var(--accent, #f43f5e);

    --rh-text: var(--text-main, #0f172a);

    --rh-muted: var(--text-muted, #64748b);

    --rh-border: var(--border-light, rgba(0,0,0,0.1));

    --rh-input: var(--input-bg, #f8fafc);

    --rh-success: #10b981;

    --rh-warn: #f59e0b;

    --rh-danger: #ef4444;

    --rh-code-bg: #1e1f29;

    --rh-radius: 18px;

}

@media (prefers-color-scheme: dark){

    :root{ --rh-code-bg:#15161f; }

}

*{box-sizing:border-box; margin:0; padding:0; font-family:'Poppins','Inter',sans-serif; -webkit-tap-highlight-color:transparent;}

html,body{height:100dvh; width:100vw; overflow:hidden; background:var(--rh-bg); color:var(--rh-text);}

button{font-family:inherit; cursor:pointer; background:none; border:none; color:inherit;}

input,textarea{font-family:inherit; color:inherit;}

::-webkit-scrollbar{width:6px; height:6px;}

::-webkit-scrollbar-thumb{background:var(--rh-primary); border-radius:10px;}

svg{width:20px; height:20px; display:block;}



#rhApp{position:fixed; inset:0; overflow:hidden;}



/* ===== Shared: views ===== */

.rh-view{position:absolute; inset:0; display:none; flex-direction:column; opacity:0; transform:translateY(8px); transition:opacity .28s ease, transform .28s ease;}

.rh-view.active{display:flex; opacity:1; transform:translateY(0);}



/* ===== Buttons ===== */

.rh-icon-btn{width:38px; height:38px; border-radius:12px; display:flex; align-items:center; justify-content:center; background:var(--rh-input); border:1px solid var(--rh-border); color:var(--rh-text); transition:.18s; flex-shrink:0;}

.rh-icon-btn:hover{background:var(--rh-primary); color:#fff; border-color:var(--rh-primary); transform:translateY(-1px);}

.rh-icon-btn.active{background:var(--rh-primary); color:#fff; border-color:var(--rh-primary); box-shadow:0 0 0 3px var(--rh-primary-glow);}

.rh-icon-btn:disabled{opacity:.35; pointer-events:none;}

.rh-icon-btn.sm{width:32px; height:32px; border-radius:10px;}

.rh-icon-btn.sm svg{width:16px;height:16px;}



.rh-btn{display:inline-flex; align-items:center; gap:8px; padding:12px 20px; border-radius:14px; font-weight:700; font-size:14px; transition:.18s; border:1px solid transparent;}

.rh-btn svg{width:18px; height:18px;}

.rh-btn-primary{background:linear-gradient(135deg, var(--rh-secondary), var(--rh-primary)); color:#fff; box-shadow:0 6px 18px var(--rh-primary-glow);}

.rh-btn-primary:hover{transform:translateY(-2px); box-shadow:0 10px 24px var(--rh-primary-glow);}

.rh-btn-primary:disabled{opacity:.5; pointer-events:none; transform:none;}

.rh-btn-ghost{background:var(--rh-input); color:var(--rh-text); border-color:var(--rh-border);}

.rh-btn-ghost:hover{border-color:var(--rh-primary); color:var(--rh-primary);}

.rh-btn-danger{background:rgba(239,68,68,0.12); color:var(--rh-danger); border-color:rgba(239,68,68,0.3);}

.rh-btn-danger:hover{background:var(--rh-danger); color:#fff;}

.rh-btn-block{width:100%; justify-content:center;}

.rh-btn.loading{pointer-events:none; opacity:.75;}



.rh-spinner{width:16px; height:16px; border-radius:50%; border:2.5px solid rgba(255,255,255,.35); border-top-color:#fff; animation:rh-spin .7s linear infinite;}

@keyframes rh-spin{to{transform:rotate(360deg);}}



/* ===== HOME ===== */

#view-home{padding:0;}

.rh-home-scroll{flex:1; overflow-y:auto; padding:26px 20px 40px;}

.rh-hero{text-align:center; padding:18px 0 30px; animation:rh-fadeUp .5s cubic-bezier(.175,.885,.32,1.275);}

.rh-logo{width:64px; height:64px; border-radius:20px; margin:0 auto 16px; background:linear-gradient(135deg, var(--rh-secondary), var(--rh-primary), var(--rh-accent)); background-size:200% auto; display:flex; align-items:center; justify-content:center; box-shadow:0 12px 30px var(--rh-primary-glow); animation:rh-shine 3s linear infinite;}

.rh-logo svg{width:32px; height:32px; color:#fff;}

.rh-title{font-size:26px; font-weight:900; letter-spacing:.3px; background:linear-gradient(90deg, var(--rh-secondary), var(--rh-primary), var(--rh-accent)); background-size:200% auto; -webkit-background-clip:text; -webkit-text-fill-color:transparent; animation:rh-shine 3s linear infinite;}

.rh-subtitle{margin-top:6px; color:var(--rh-muted); font-size:13.5px; font-weight:500;}

@keyframes rh-shine{to{background-position:200% center;}}

@keyframes rh-fadeUp{from{opacity:0; transform:translateY(16px);} to{opacity:1; transform:translateY(0);}}



.rh-draft-banner{display:none; align-items:center; gap:12px; background:var(--rh-surface); border:1px solid var(--rh-primary); border-radius:14px; padding:12px 14px; margin-bottom:18px; box-shadow:0 6px 18px rgba(0,0,0,.06); animation:rh-slideIn .35s ease;}

.rh-draft-banner .rh-draft-txt{flex:1; font-size:12.5px; color:var(--rh-text); font-weight:600;}

.rh-draft-banner .rh-draft-txt small{display:block; color:var(--rh-muted); font-weight:500; margin-top:2px;}



.rh-card-row{display:flex; flex-direction:column; gap:16px;}

.rh-card{position:relative; overflow:hidden; display:flex; align-items:center; gap:16px; padding:22px; border-radius:var(--rh-radius); background:var(--rh-surface); border:1px solid var(--rh-border); box-shadow:0 10px 25px rgba(0,0,0,.05); transition:.25s;}

.rh-card:active{transform:scale(.98);}

.rh-card:hover{transform:translateY(-3px); box-shadow:0 16px 34px rgba(0,0,0,.09);}

.rh-card-ic{width:54px; height:54px; border-radius:16px; display:flex; align-items:center; justify-content:center; flex-shrink:0; color:#fff;}

.rh-card-ic svg{width:26px; height:26px;}

.rh-card.create .rh-card-ic{background:linear-gradient(135deg, var(--rh-secondary), var(--rh-primary));}

.rh-card.history .rh-card-ic{background:linear-gradient(135deg, var(--rh-primary), var(--rh-accent));}

.rh-card-body{flex:1; min-width:0;}

.rh-card-title{font-size:16.5px; font-weight:800;}

.rh-card-desc{font-size:12.5px; color:var(--rh-muted); margin-top:3px; font-weight:500;}

.rh-card-arrow{color:var(--rh-muted);}



.rh-stats{display:flex; gap:12px; margin-top:22px;}

.rh-stat{flex:1; background:var(--rh-surface); border:1px solid var(--rh-border); border-radius:14px; padding:14px; text-align:center;}

.rh-stat-num{font-size:20px; font-weight:900; color:var(--rh-primary);}

.rh-stat-lbl{font-size:10.5px; color:var(--rh-muted); font-weight:700; text-transform:uppercase; letter-spacing:.5px; margin-top:2px;}



.rh-tmpl-strip{margin-top:26px;}

.rh-section-lbl{font-size:12px; font-weight:800; color:var(--rh-muted); text-transform:uppercase; letter-spacing:.6px; margin-bottom:10px;}

.rh-tmpl-scroll{display:flex; gap:10px; overflow-x:auto; padding-bottom:4px;}

.rh-tmpl-chip{flex-shrink:0; padding:10px 16px; border-radius:12px; background:var(--rh-surface); border:1px solid var(--rh-border); font-size:12.5px; font-weight:700; white-space:nowrap; transition:.2s;}

.rh-tmpl-chip:hover{border-color:var(--rh-primary); color:var(--rh-primary); transform:translateY(-2px);}



/* ===== TOP BAR ===== */

.rh-topbar{display:flex; align-items:center; gap:10px; padding:14px 16px; background:var(--rh-surface); border-bottom:1px solid var(--rh-border); flex-shrink:0; box-shadow:0 4px 14px rgba(0,0,0,.04); z-index:20;}

.rh-filename{flex:1; min-width:0; background:transparent; border:none; font-size:15px; font-weight:800; color:var(--rh-text); padding:6px 8px; border-radius:8px; outline:none;}

.rh-filename:focus{background:var(--rh-input);}

.rh-dirty-dot{width:8px; height:8px; border-radius:50%; background:var(--rh-accent); flex-shrink:0; display:none;}

.rh-dirty-dot.show{display:block;}



/* ===== TABS ===== */

.rh-tabs{display:flex; gap:6px; padding:10px 16px; background:var(--rh-surface); border-bottom:1px solid var(--rh-border); flex-shrink:0;}

.rh-tab{flex:1; text-align:center; padding:9px; border-radius:10px; font-size:13px; font-weight:700; color:var(--rh-muted); display:flex; align-items:center; justify-content:center; gap:6px; transition:.2s;}

.rh-tab svg{width:16px;height:16px;}

.rh-tab.active{background:var(--rh-input); color:var(--rh-primary);}



/* ===== TOOLBAR ROWS ===== */

.rh-toolrow{display:flex; align-items:center; gap:8px; padding:10px 14px; overflow-x:auto; background:var(--rh-surface); border-bottom:1px solid var(--rh-border); flex-shrink:0;}

.rh-toolrow::-webkit-scrollbar{display:none;}

.rh-divider{width:1px; height:22px; background:var(--rh-border); flex-shrink:0; margin:0 2px;}



.rh-statusbar{display:flex; align-items:center; gap:10px; padding:7px 14px; font-size:11px; color:var(--rh-muted); background:var(--rh-input); border-bottom:1px solid var(--rh-border); flex-shrink:0; font-weight:600;}

.rh-lint-badge{display:flex; align-items:center; gap:5px; padding:3px 9px; border-radius:20px; font-weight:800; font-size:10.5px; cursor:pointer;}

.rh-lint-badge svg{width:13px; height:13px;}

.rh-lint-badge.ok{background:rgba(16,185,129,.14); color:var(--rh-success);}

.rh-lint-badge.bad{background:rgba(239,68,68,.14); color:var(--rh-danger);}

.rh-status-sep{opacity:.5;}

.rh-status-fill{flex:1;}



/* ===== EDITOR ===== */

.rh-editor-wrap{flex:1; min-height:0; position:relative; background:var(--rh-code-bg);}

.rh-editor-wrap textarea{display:none;}

.CodeMirror{height:100% !important; font-family:'JetBrains Mono', monospace !important; font-size:13px; line-height:1.6;}

.rh-plain-fallback{width:100%; height:100%; background:var(--rh-code-bg); color:#e2e8f0; border:none; outline:none; resize:none; padding:14px; font-family:'JetBrains Mono',monospace; font-size:13px; line-height:1.6;}



/* FULLSCREEN MODE CSS */

.rh-editor-wrap.fs-mode {

    position: fixed; inset: 0; z-index: 100000; background: var(--rh-code-bg); height: 100dvh !important;

}

.floating-fs-close { display: none; position: absolute; top: 14px; right: 14px; z-index: 100001; background: rgba(239,68,68,0.15); color: var(--rh-danger); border: 1px solid var(--rh-danger); }

.rh-editor-wrap.fs-mode .floating-fs-close { display: flex; }

.floating-fs-close:hover { background: var(--rh-danger); color: #fff; }



/* SEARCH DIALOG FIX (THE "X" BUTTON) */

.CodeMirror-dialog { background:var(--rh-surface) !important; color:var(--rh-text) !important; padding:10px 14px !important; position: relative; padding-right: 50px !important; }

.CodeMirror-dialog input { background:var(--rh-input); color:var(--rh-text); border:1px solid var(--rh-border); border-radius:8px; padding:6px 10px; width: calc(100% - 60px); }

.CodeMirror-search-close {

    position: absolute !important; right: 10px !important; top: 50% !important; transform: translateY(-50%) !important;

    background: rgba(239,68,68,0.15) !important; color: var(--rh-danger) !important; border: 1px solid rgba(239,68,68,0.3) !important; border-radius: 8px !important;

    width: 32px !important; height: 32px !important; font-size: 16px !important; cursor: pointer !important; display: flex !important; align-items: center !important; justify-content: center !important;

    opacity: 1 !important;

}

.CodeMirror-search-close:hover { background: var(--rh-danger) !important; color: #fff !important; }



/* ===== PREVIEW ===== */

.rh-preview-pane{flex:1; min-height:0; display:none; flex-direction:column; background:var(--rh-bg);}

.rh-preview-pane.active{display:flex;}

.rh-device-row{display:flex; align-items:center; gap:8px; padding:10px 14px; overflow-x:auto; background:var(--rh-surface); border-bottom:1px solid var(--rh-border); flex-shrink:0;}

.rh-preview-stage{flex:1; overflow:auto; display:flex; align-items:flex-start; justify-content:center; padding:22px 14px 40px;}

.rh-frame-wrap{transition:width .3s ease, height .3s ease; flex-shrink:0;}



.rh-device{position:relative; background:#0b0b12; box-shadow:0 20px 50px rgba(0,0,0,.35); transition:.3s ease;}

.rh-device iframe{width:100%; height:100%; border:none; background:#fff; display:block;}

.rh-device.iphone{width:300px; height:620px; border-radius:42px; padding:14px 10px;}

.rh-device.iphone iframe{border-radius:28px;}

.rh-device.iphone::before{content:''; position:absolute; top:14px; left:50%; transform:translateX(-50%); width:110px; height:26px; background:#0b0b12; border-radius:16px; z-index:5;}

.rh-device.android{width:290px; height:600px; border-radius:26px; padding:10px;}

.rh-device.android iframe{border-radius:18px;}

.rh-device.android::before{content:''; position:absolute; top:20px; left:24px; width:10px; height:10px; border-radius:50%; background:#0b0b12; box-shadow:0 0 0 3px #1c1c26; z-index:5;}

.rh-device.tablet{width:440px; height:580px; border-radius:22px; padding:16px 14px;}

.rh-device.tablet iframe{border-radius:10px;}

.rh-device.desktop{width:680px; height:440px; border-radius:14px; padding:10px 10px 34px;}

.rh-device.desktop iframe{border-radius:6px;}

.rh-device.desktop::after{content:''; position:absolute; bottom:8px; left:50%; transform:translateX(-50%); width:60px; height:5px; border-radius:3px; background:#2a2a36;}

.rh-device.full{width:100%; max-width:900px; height:70vh; border-radius:14px; padding:0; box-shadow:none; border:1px solid var(--rh-border);}

.rh-device.full iframe{border-radius:14px;}

.rh-device.landscape{transform:rotate(90deg);}

.rh-device.landscape.full{transform:none;}



.rh-inspect-info{position:fixed; bottom:90px; left:50%; transform:translateX(-50%); background:var(--rh-text); color:var(--rh-surface); font:600 11px 'JetBrains Mono',monospace; padding:6px 12px; border-radius:20px; display:none; z-index:200; white-space:nowrap;}

.rh-inspect-info.show{display:block; animation:rh-fadeUp .2s ease;}



/* ===== CONSOLE DRAWER ===== */

.rh-console{flex-shrink:0; max-height:0; overflow:hidden; background:#101018; border-top:1px solid #2a2a38; transition:max-height .28s ease;}

.rh-console.open{max-height:36vh;}

.rh-console-head{display:flex; align-items:center; gap:8px; padding:9px 14px; color:#94a3b8; font-size:11px; font-weight:800; text-transform:uppercase; letter-spacing:.5px; border-bottom:1px solid #23232f;}

.rh-console-head .rh-status-fill{flex:1;}

.rh-console-body{height:calc(36vh - 38px); overflow-y:auto; padding:8px 14px; font-family:'JetBrains Mono',monospace; font-size:12px;}

.rh-console-line{padding:5px 0; border-bottom:1px solid #1c1c28; color:#cbd5e1; word-break:break-word; display:flex; gap:8px;}

.rh-console-line .tag{flex-shrink:0; font-weight:800; font-size:9px; padding:1px 6px; border-radius:6px; text-transform:uppercase; height:fit-content;}

.rh-console-line.log .tag{background:rgba(148,163,184,.15); color:#94a3b8;}

.rh-console-line.warn .tag{background:rgba(245,158,11,.15); color:#f59e0b;}

.rh-console-line.error .tag{background:rgba(239,68,68,.15); color:#f87171;}

.rh-console-empty{color:#475569; font-size:12px; padding:20px 0; text-align:center;}



/* ===== BOTTOM BAR ===== */

.rh-bottombar{display:flex; align-items:center; gap:10px; padding:12px 16px calc(12px + env(safe-area-inset-bottom)); background:var(--rh-surface); border-top:1px solid var(--rh-border); flex-shrink:0; box-shadow:0 -8px 24px rgba(0,0,0,.06); z-index:20;}

.rh-live-toggle{display:flex; align-items:center; gap:6px; flex-shrink:0;}

.rh-switch{width:38px; height:22px; border-radius:20px; background:var(--rh-border); position:relative; transition:.2s; flex-shrink:0;}

.rh-switch::after{content:''; position:absolute; width:16px; height:16px; border-radius:50%; background:#fff; top:3px; left:3px; transition:.2s; box-shadow:0 1px 3px rgba(0,0,0,.3);}

.rh-switch.on{background:var(--rh-primary);}

.rh-switch.on::after{left:19px;}

.rh-live-lbl{font-size:10px; font-weight:800; color:var(--rh-muted); text-transform:uppercase;}



/* ===== TOAST ===== */

#toastStack{position:fixed; top:14px; left:50%; transform:translateX(-50%); width:min(94vw,420px); display:flex; flex-direction:column; gap:8px; z-index:99999; pointer-events:none;}

.toast{pointer-events:auto; position:relative; overflow:hidden; display:flex; align-items:center; gap:10px; background:var(--rh-surface); border:1px solid var(--rh-border); border-left:4px solid var(--rh-muted); border-radius:12px; padding:12px 14px; box-shadow:0 12px 30px rgba(0,0,0,.15); opacity:0; transform:translateY(-16px); transition:.28s cubic-bezier(.175,.885,.32,1.275);}

.toast.show{opacity:1; transform:translateY(0);}

.toast-error{border-left-color:var(--rh-danger);}

.toast-success{border-left-color:var(--rh-success);}

.toast-info{border-left-color:var(--rh-secondary);}

.toast-icon{flex-shrink:0; width:20px; height:20px;}

.toast-error .toast-icon{color:var(--rh-danger);}

.toast-success .toast-icon{color:var(--rh-success);}

.toast-info .toast-icon{color:var(--rh-secondary);}

.toast-msg{flex:1; font-size:12.5px; font-weight:600; line-height:1.4;}

.toast-close{flex-shrink:0; width:20px; height:20px; color:var(--rh-muted);}

.toast-bar{position:absolute; bottom:0; left:0; height:2.5px; background:currentColor; opacity:.35; animation:rh-shrink linear forwards; width:100%;}

.toast-error .toast-bar{color:var(--rh-danger);}

.toast-success .toast-bar{color:var(--rh-success);}

.toast-info .toast-bar{color:var(--rh-secondary);}

@keyframes rh-shrink{from{width:100%;} to{width:0%;}}

@keyframes rh-slideIn{from{opacity:0; transform:translateX(-14px);} to{opacity:1; transform:translateX(0);}}



/* ===== MODAL / SHEET ===== */

.rh-overlay{position:fixed; inset:0; background:rgba(6,8,20,.55); backdrop-filter:blur(3px); display:none; align-items:flex-end; justify-content:center; z-index:9000; opacity:0; transition:opacity .25s ease;}

.rh-overlay.show{display:flex; opacity:1;}

.rh-overlay.center{align-items:center; padding:20px;}

.rh-sheet{width:100%; max-width:560px; max-height:88vh; background:var(--rh-surface); border-radius:24px 24px 0 0; display:flex; flex-direction:column; transform:translateY(100%); transition:transform .32s cubic-bezier(.175,.885,.32,1.275); overflow:hidden;}

.rh-overlay.show .rh-sheet{transform:translateY(0);}

.rh-overlay.center .rh-sheet{border-radius:22px; max-height:85vh;}

.rh-sheet-handle{width:40px; height:4px; border-radius:3px; background:var(--rh-border); margin:10px auto 0; flex-shrink:0;}

.rh-sheet-head{display:flex; align-items:center; gap:10px; padding:14px 18px; border-bottom:1px solid var(--rh-border); flex-shrink:0;}

.rh-sheet-title{flex:1; font-size:16px; font-weight:800;}

.rh-sheet-body{flex:1; overflow-y:auto; padding:18px;}

.rh-sheet-foot{padding:14px 18px calc(14px + env(safe-area-inset-bottom)); border-top:1px solid var(--rh-border); flex-shrink:0;}



.rh-field-lbl{font-size:11.5px; font-weight:800; color:var(--rh-muted); text-transform:uppercase; letter-spacing:.5px; margin-bottom:8px; display:block;}

.rh-input{width:100%; padding:12px 14px; border-radius:12px; background:var(--rh-input); border:1px solid var(--rh-border); font-size:14px; outline:none; transition:.2s;}

.rh-input:focus{border-color:var(--rh-primary); box-shadow:0 0 0 3px var(--rh-primary-glow);}

textarea.rh-input{resize:vertical; min-height:90px; line-height:1.5;}



.rh-chip-grid{display:flex; flex-wrap:wrap; gap:8px; margin-bottom:16px;}

.rh-chip{padding:9px 15px; border-radius:20px; background:var(--rh-input); border:1px solid var(--rh-border); font-size:12.5px; font-weight:700; transition:.18s;}

.rh-chip.selected{background:var(--rh-primary); color:#fff; border-color:var(--rh-primary);}



.rh-gen-result{display:none; margin-top:16px;}

.rh-gen-result.show{display:block; animation:rh-fadeUp .3s ease;}

.rh-gen-preview{height:220px; border-radius:14px; overflow:hidden; border:1px solid var(--rh-border);}

.rh-gen-actions{display:flex; gap:8px; margin-top:12px; flex-wrap:wrap;}

.rh-gen-actions .rh-btn{flex:1; font-size:12.5px; padding:11px 10px;}



.rh-mic-row{display:flex; gap:8px; align-items:center; margin-top:10px;}



/* ===== TEMPLATE GALLERY ===== */

.rh-tmpl-grid{display:grid; grid-template-columns:1fr 1fr; gap:12px;}

.rh-tmpl-card{padding:16px 12px; border-radius:14px; background:var(--rh-input); border:1px solid var(--rh-border); text-align:center; transition:.2s;}

.rh-tmpl-card:hover{border-color:var(--rh-primary); transform:translateY(-2px);}

.rh-tmpl-card svg{width:26px; height:26px; margin:0 auto 8px; color:var(--rh-primary);}

.rh-tmpl-card-name{font-size:12.5px; font-weight:800;}



/* ===== CHAT / EXPLAIN ===== */

.rh-chat-body{display:flex; flex-direction:column; gap:12px;}

.rh-chat-empty{text-align:center; padding:30px 10px; color:var(--rh-muted);}

.rh-chat-empty svg{width:36px; height:36px; margin:0 auto 10px; opacity:.5;}

.rh-chat-empty p{font-size:13px; font-weight:600;}

.rh-msg{display:flex; max-width:88%;}

.rh-msg.user{align-self:flex-end; justify-content:flex-end;}

.rh-msg.ai{align-self:flex-start;}

.rh-bubble{padding:12px 15px; border-radius:16px; font-size:13.5px; line-height:1.55; word-break:break-word;}

.rh-msg.user .rh-bubble{background:linear-gradient(135deg, var(--rh-secondary), var(--rh-primary)); color:#fff; border-bottom-right-radius:5px;}

.rh-msg.ai .rh-bubble{background:var(--rh-input); border:1px solid var(--rh-border); border-bottom-left-radius:5px;}

.rh-bubble pre{background:#0d1117; color:#c9d1d9; padding:10px; border-radius:8px; overflow-x:auto; margin:6px 0; font-size:12px;}

.rh-bubble code{font-family:'JetBrains Mono',monospace; font-size:12px;}

.rh-bubble p{margin-bottom:6px;}

.rh-typing{display:flex; gap:4px; padding:14px 15px;}

.rh-typing span{width:6px; height:6px; border-radius:50%; background:var(--rh-primary); animation:rh-bounce 1.2s infinite;}

.rh-typing span:nth-child(2){animation-delay:.15s;}

.rh-typing span:nth-child(3){animation-delay:.3s;}

@keyframes rh-bounce{0%,60%,100%{transform:translateY(0); opacity:.5;} 30%{transform:translateY(-5px); opacity:1;}}

.rh-chat-input-row{display:flex; gap:8px; align-items:flex-end;}

.rh-chat-input-row textarea{flex:1; max-height:100px; min-height:44px;}



/* ===== HISTORY ===== */

.rh-hist-body{flex:1; overflow-y:auto; padding:16px;}

.rh-hist-toolbar{display:flex; gap:8px; margin-bottom:14px;}

.rh-hist-toolbar .rh-input{flex:1;}

.rh-hist-empty{text-align:center; padding:60px 20px; color:var(--rh-muted);}

.rh-hist-empty svg{width:48px; height:48px; margin:0 auto 14px; opacity:.4;}

.rh-hist-list{display:flex; flex-direction:column; gap:12px;}

.rh-hist-card{background:var(--rh-surface); border:1px solid var(--rh-border); border-radius:16px; padding:16px; box-shadow:0 6px 16px rgba(0,0,0,.04);}

.rh-hist-top{display:flex; align-items:flex-start; gap:10px;}

.rh-hist-ic{width:40px; height:40px; border-radius:11px; background:linear-gradient(135deg, var(--rh-secondary), var(--rh-primary)); display:flex; align-items:center; justify-content:center; color:#fff; flex-shrink:0;}

.rh-hist-ic svg{width:19px;height:19px;}

.rh-hist-meta{flex:1; min-width:0;}

.rh-hist-name{font-size:14.5px; font-weight:800; white-space:nowrap; overflow:hidden; text-overflow:ellipsis;}

.rh-hist-sub{font-size:11px; color:var(--rh-muted); font-weight:600; margin-top:2px;}

.rh-hist-snippet{margin-top:10px; background:var(--rh-code-bg); color:#8b93a8; border-radius:10px; padding:9px 11px; font-family:'JetBrains Mono',monospace; font-size:10.5px; line-height:1.5; max-height:52px; overflow:hidden; white-space:pre-wrap; word-break:break-all;}

.rh-hist-actions{display:flex; gap:6px; margin-top:12px; flex-wrap:wrap;}

.rh-hist-actions .rh-icon-btn{flex:1; width:auto;}



/* ===== CONFIRM ===== */

.rh-confirm-body{text-align:center; padding:6px 4px 4px;}

.rh-confirm-ic{width:52px; height:52px; border-radius:16px; background:rgba(239,68,68,.12); color:var(--rh-danger); display:flex; align-items:center; justify-content:center; margin:0 auto 14px;}

.rh-confirm-ic svg{width:26px; height:26px;}

.rh-confirm-msg{font-size:13.5px; color:var(--rh-muted); font-weight:500; margin-bottom:4px;}

.rh-confirm-actions{display:flex; gap:10px; margin-top:18px;}

.rh-confirm-actions .rh-btn{flex:1;}



@media (min-width:760px){

    .rh-sheet{max-width:640px;}

    .rh-overlay:not(.center) .rh-sheet{margin-bottom:20px; border-radius:22px;}

}

.menu-row{display:flex; align-items:center; gap:12px; width:100%; padding:13px 10px; border-radius:12px; font-size:14px; font-weight:700; text-align:left; transition:.15s;}

.menu-row:hover{background:var(--rh-input);}

.menu-row svg{width:18px;height:18px; color:var(--rh-primary);}

</style>
</head>
<body>
<style>

/* === UNIVERSAL SIDEBAR (injected — this page had no navigation drawer before) === */

#globalMenuBtn { position: fixed; top: 14px; left: 14px; z-index: 999997; width: 42px; height: 42px; border-radius: 50%; border: none; background: var(--primary, #8b5cf6); color: #fff; font-size: 18px; display: flex; align-items: center; justify-content: center; cursor: pointer; box-shadow: 0 4px 14px rgba(0,0,0,0.25); }

#overlay { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999998; display: none; opacity: 0; transition: 0.3s; }

#overlay.active { display: block; opacity: 1; }

.sidebar { position: fixed; top: 0; left: -300px; width: 280px; height: 100%; background: var(--bg-surface, #ffffff); z-index: 999999; transition: left 0.3s ease; box-shadow: 4px 0 25px rgba(0,0,0,0.3); padding: 20px 14px; box-sizing: border-box; overflow-y: auto; display: flex; flex-direction: column; gap: 6px; }

.sidebar.active { left: 0; }

.sidebar button { display: block; width: 100%; text-align: left; padding: 12px 14px; border-radius: 10px; border: none; background: transparent; color: var(--text-main, #1e293b); font-size: 14.5px; font-weight: 600; cursor: pointer; }

.sidebar button:hover { background: var(--border-light, rgba(139,92,246,0.1)); }

.sidebar-close-btn { color: #ef4444 !important; font-weight: 800 !important; margin-bottom: 10px; border: 1px solid rgba(239,68,68,0.3) !important; }

</style>
<button id="globalMenuBtn" onclick="toggleSidebar()">☰</button>
<div class="overlay" id="overlay" onclick="toggleSidebar()"></div>
<div class="sidebar" id="sidebar" style="overflow-y:auto;">
  <button class="sidebar-close-btn" onclick="toggleSidebar()">✖ Close Menu</button>
  <button onclick="window.location.href='index.html'">🏠 Dashboard</button>
  <button onclick="window.location.href='lens.html'">✨ Lens Studio</button>
  <button onclick="window.location.href='books.html'">📚 Book Deep Study</button>
  <button onclick="window.location.href='maths.html'">🧮 Math Solver</button>
  <button onclick="window.location.href='search.html'">🔎 Deep Search</button>
  <button onclick="window.location.href='downloader.html'">📥 Video Downloader</button>
  <button onclick="window.location.href='board.html'">📋 Whiteboard</button>
  <button onclick="window.location.href='clone.html'">📑 Website Cloner</button>
  <button onclick="window.location.href='runhtml.html'" style="border-left: 4px solid var(--primary); color: var(--primary); background: var(--border-light);">🌐 Write HTML</button>
  <button onclick="window.location.href='youtube.html'">▶️ YouTube Search</button>
  <button onclick="window.location.href='managequiz.html'">⚙️ Manage Quiz</button>
  <button onclick="window.location.href='tutor.html'">👨‍🏫 AI Tutor</button>
  <button onclick="window.location.href='quiz.html'">📝 Take a Quiz!</button>
  <button onclick="window.location.href='book_quiz.html'">📝 Take a Book Quiz!</button>
  <button onclick="window.location.href='tables.html'">🔢 Maths Table</button>
  <button onclick="window.location.href='coding.html'">💻 AI Coding</button>
  <button onclick="window.location.href='chess.html'">♟️ Chess AI</button>
  <button onclick="window.location.href='translator.html'">🎙️ Text Translator</button>
  <button onclick="window.location.href='image.html'">🖼️ Image Translator</button>
  <button onclick="window.location.href='create.html'">🎨 Image Creator</button>
  <button onclick="window.location.href='qa.html'">📚 Document Q&A</button>
  <button onclick="window.location.href='history.html'">🕒 History & Downloads</button>
  <button onclick="window.location.href='storage.html'">📂 Storage</button>
  <button onclick="window.location.href='hub.html'">🛰️ HF Command Center</button>
  <button onclick="window.location.href='live.html'">🗣️ Gemini Live</button>
</div>
<script>

function toggleSidebar() { const s = document.getElementById("sidebar"), o = document.getElementById("overlay"); const a = !s.classList.contains("active"); s.classList.toggle("active", a); o.classList.toggle("active", a); }

</script>

<div id="rhApp">

    <!-- ===================== HOME ===================== -->
    <div class="rh-view active" id="view-home">
        <div class="rh-home-scroll">
            <div class="rh-hero">
                <div class="rh-logo">
                    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="16 18 22 12 16 6"/><polyline points="8 6 2 12 8 18"/></svg>
                </div>
                <div class="rh-title">RunHTML</div>
                <div class="rh-subtitle">Write. Generate. Test on mobile. Instantly.</div>
            </div>

            <div class="rh-draft-banner" id="draftBanner">
                <span id="ic-draft"></span>
                <div class="rh-draft-txt">Unsaved draft found<small id="draftTime"></small></div>
                <button class="rh-btn rh-btn-primary" style="padding:8px 14px;font-size:12px;" id="btnResumeDraft">Resume</button>
                <button class="rh-icon-btn sm" id="btnDiscardDraft"></button>
            </div>

            <div class="rh-card-row">
                <button class="rh-card create" id="btnGoCreate">
                    <div class="rh-card-ic" id="ic-create-card"></div>
                    <div class="rh-card-body">
                        <div class="rh-card-title">Create HTML</div>
                        <div class="rh-card-desc">Write or AI-generate a page, then run it</div>
                    </div>
                    <span class="rh-card-arrow" id="ic-arrow1"></span>
                </button>
                <button class="rh-card history" id="btnGoHistory">
                    <div class="rh-card-ic" id="ic-history-card"></div>
                    <div class="rh-card-body">
                        <div class="rh-card-title">Load History</div>
                        <div class="rh-card-desc">Restore a saved project & its chat</div>
                    </div>
                    <span class="rh-card-arrow" id="ic-arrow2"></span>
                </button>
            </div>

            <div class="rh-stats">
                <div class="rh-stat"><div class="rh-stat-num" id="statCount">0</div><div class="rh-stat-lbl">Saved</div></div>
                <div class="rh-stat"><div class="rh-stat-num" id="statSize">0 KB</div><div class="rh-stat-lbl">Storage</div></div>
                <div class="rh-stat"><div class="rh-stat-num" id="statLast">—</div><div class="rh-stat-lbl">Last Edit</div></div>
            </div>

            <div class="rh-tmpl-strip">
                <div class="rh-section-lbl">Quick start templates</div>
                <div class="rh-tmpl-scroll" id="homeTemplateStrip"></div>
            </div>
        </div>
    </div>

    <!-- ===================== CREATE / EDITOR ===================== -->
    <div class="rh-view" id="view-create">
        <div class="rh-topbar">
            <button class="rh-icon-btn" id="btnBackHome"></button>
            <input class="rh-filename" id="fileNameInput" value="Untitled Project" maxlength="60">
            <span class="rh-dirty-dot" id="dirtyDot"></span>
            <button class="rh-icon-btn" id="btnMoreMenu"></button>
        </div>

        <div class="rh-tabs">
            <button class="rh-tab active" data-tab="code" id="tabCode"></button>
            <button class="rh-tab" data-tab="preview" id="tabPreview"></button>
        </div>

        <!-- CODE TAB -->
        <div class="rh-toolrow" id="codeToolbar">
            <button class="rh-icon-btn" id="btnFullscreen" title="Full Screen Editor"></button>
            <div class="rh-divider"></div>
            <button class="rh-icon-btn" id="btnGenerate" title="Generate with AI"></button>
            <div class="rh-divider"></div>
            <button class="rh-icon-btn" id="btnUndo" title="Undo"></button>
            <button class="rh-icon-btn" id="btnRedo" title="Redo"></button>
            <div class="rh-divider"></div>
            <button class="rh-icon-btn" id="btnFind" title="Find & Replace"></button>
            <button class="rh-icon-btn" id="btnBeautify" title="Beautify code"></button>
            <div class="rh-divider"></div>
            <button class="rh-icon-btn" id="btnTemplates" title="Templates"></button>
            <button class="rh-icon-btn" id="btnImport" title="Import .html file"></button>
            <button class="rh-icon-btn" id="btnCopyCode" title="Copy code"></button>
            <button class="rh-icon-btn" id="btnClearCode" title="Clear editor"></button>
        </div>
        <div class="rh-statusbar">
            <span class="rh-lint-badge ok" id="lintBadge"></span>
            <span class="rh-status-sep">•</span>
            <span id="statLines">0 lines</span>
            <span class="rh-status-sep">•</span>
            <span id="statChars">0 chars</span>
            <span class="rh-status-sep">•</span>
            <span id="statBytes">0 KB</span>
            <span class="rh-status-fill"></span>
            <span id="autosaveTxt">—</span>
        </div>
        <div class="rh-editor-wrap" id="tabpane-code">
            <button class="rh-icon-btn floating-fs-close" id="btnCloseFs" title="Close Fullscreen"></button>
            <textarea id="codeArea" spellcheck="false"></textarea>
        </div>

        <!-- PREVIEW TAB -->
        <div class="rh-preview-pane" id="tabpane-preview">
            <div class="rh-device-row">
                <button class="rh-icon-btn active" data-device="iphone" id="devIphone"></button>
                <button class="rh-icon-btn" data-device="android" id="devAndroid"></button>
                <button class="rh-icon-btn" data-device="tablet" id="devTablet"></button>
                <button class="rh-icon-btn" data-device="desktop" id="devDesktop"></button>
                <button class="rh-icon-btn" data-device="full" id="devFull"></button>
                <div class="rh-divider"></div>
                <button class="rh-icon-btn" id="btnRotate" title="Rotate orientation"></button>
                <button class="rh-icon-btn" id="btnInspect" title="Inspect element"></button>
                <button class="rh-icon-btn" id="btnScreenshot" title="Screenshot preview"></button>
                <button class="rh-icon-btn" id="btnConsoleToggle" title="Dev console"></button>
            </div>
            <div class="rh-preview-stage" id="previewStage">
                <div class="rh-frame-wrap" id="frameWrap">
                    <div class="rh-device iphone" id="deviceEl">
                        <iframe id="previewFrame" title="preview" sandbox="allow-scripts allow-forms allow-popups allow-modals allow-same-origin"></iframe>
                    </div>
                </div>
            </div>
            <div class="rh-console" id="consoleDrawer">
                <div class="rh-console-head">
                    <span id="ic-terminal"></span><span>Console</span>
                    <span class="rh-status-fill"></span>
                    <button class="rh-icon-btn sm" id="btnClearConsole"></button>
                </div>
                <div class="rh-console-body" id="consoleBody">
                    <div class="rh-console-empty">No output yet — hit Run to see logs & errors here.</div>
                </div>
            </div>
        </div>

        <div class="rh-inspect-info" id="inspectInfo"></div>

        <div class="rh-bottombar">
            <div class="rh-live-toggle" id="liveToggleWrap">
                <div class="rh-switch" id="liveSwitch"></div>
                <span class="rh-live-lbl">Live</span>
            </div>
            <button class="rh-icon-btn" id="btnExplain" title="Explain / Ask AI"></button>
            <button class="rh-btn rh-btn-primary" id="btnRun" style="flex:1;"></button>
            <button class="rh-icon-btn" id="btnSave" title="Save"></button>
            <button class="rh-icon-btn" id="btnDownload" title="Download .html"></button>
        </div>
    </div>

    <!-- ===================== HISTORY ===================== -->
    <div class="rh-view" id="view-history">
        <div class="rh-topbar">
            <button class="rh-icon-btn" id="btnBackHome2"></button>
            <div class="rh-filename" style="font-weight:900;">History</div>
        </div>
        <div class="rh-hist-body">
            <div class="rh-hist-toolbar">
                <input class="rh-input" id="histSearch" placeholder="Search saved projects...">
                <button class="rh-icon-btn" id="btnHistSort" title="Sort"></button>
            </div>
            <div class="rh-hist-empty" id="histEmpty">
                <span id="ic-empty"></span>
                <p style="font-weight:800; font-size:14px; margin-bottom:4px;">Nothing saved yet</p>
                <p style="font-size:12.5px;">Projects you save from the editor will show up here.</p>
            </div>
            <div class="rh-hist-list" id="histList"></div>
        </div>
    </div>

    <!-- ===================== MORE MENU SHEET ===================== -->
    <div class="rh-overlay" id="ovMore" data-sheet>
        <div class="rh-sheet" style="max-height:60vh;">
            <div class="rh-sheet-handle"></div>
            <div class="rh-sheet-body" style="padding:14px;">
                <button class="menu-row" id="menuSaveAs"></button>
                <button class="menu-row" id="menuDuplicate"></button>
                <button class="menu-row" id="menuCopyChat"></button>
                <button class="menu-row" id="menuNewBlank"></button>
                <button class="menu-row" id="menuShortcuts"></button>
            </div>
        </div>
    </div>

    <!-- ===================== GENERATE MODAL ===================== -->
    <div class="rh-overlay" id="ovGenerate">
        <div class="rh-sheet">
            <div class="rh-sheet-handle"></div>
            <div class="rh-sheet-head">
                <span id="ic-gen-head"></span>
                <div class="rh-sheet-title">Generate with AI</div>
                <button class="rh-icon-btn sm" id="closeGenerate"></button>
            </div>
            <div class="rh-sheet-body">
                <label class="rh-field-lbl">Type of page</label>
                <div class="rh-chip-grid" id="genTypeChips"></div>

                <label class="rh-field-lbl">Describe what you want</label>
                <textarea class="rh-input" id="genPrompt" placeholder="e.g. A pricing page with 3 plans, purple accent, mobile-first, with a toggle for monthly/yearly..."></textarea>
                <div class="rh-mic-row">
                    <button class="rh-icon-btn" id="btnMic" title="Voice input"></button>
                    <span style="font-size:11px;color:var(--rh-muted);font-weight:600;" id="micStatus">Tap mic to speak your prompt</span>
                </div>

                <div class="rh-gen-result" id="genResult">
                    <label class="rh-field-lbl" style="margin-top:16px;">Preview</label>
                    <div class="rh-gen-preview"><iframe id="genPreviewFrame" title="generated preview" sandbox="allow-scripts allow-same-origin'"></iframe></div>
                    <div class="rh-gen-actions">
                        <button class="rh-btn rh-btn-primary" id="btnMoveReplace"></button>
                        <button class="rh-btn rh-btn-ghost" id="btnMoveInsert"></button>
                    </div>
                    <div class="rh-gen-actions">
                        <button class="rh-btn rh-btn-ghost" id="btnRegenerate"></button>
                        <button class="rh-btn rh-btn-danger" id="btnDiscardGen"></button>
                    </div>
                </div>
            </div>
            <div class="rh-sheet-foot">
                <button class="rh-btn rh-btn-primary rh-btn-block" id="btnDoGenerate"></button>
            </div>
        </div>
    </div>

    <!-- ===================== TEMPLATE GALLERY ===================== -->
    <div class="rh-overlay" id="ovTemplates">
        <div class="rh-sheet">
            <div class="rh-sheet-handle"></div>
            <div class="rh-sheet-head">
                <span id="ic-tmpl-head"></span>
                <div class="rh-sheet-title">Starter Templates</div>
                <button class="rh-icon-btn sm" id="closeTemplates"></button>
            </div>
            <div class="rh-sheet-body">
                <div class="rh-tmpl-grid" id="tmplGrid"></div>
            </div>
        </div>
    </div>

    <!-- ===================== SAVE MODAL ===================== -->
    <div class="rh-overlay center" id="ovSave">
        <div class="rh-sheet" style="border-radius:22px;">
            <div class="rh-sheet-head">
                <span id="ic-save-head"></span>
                <div class="rh-sheet-title">Save Project</div>
                <button class="rh-icon-btn sm" id="closeSave"></button>
            </div>
            <div class="rh-sheet-body">
                <label class="rh-field-lbl">Project name</label>
                <input class="rh-input" id="saveNameInput" placeholder="My awesome page">
            </div>
            <div class="rh-sheet-foot">
                <button class="rh-btn rh-btn-primary rh-btn-block" id="btnConfirmSave"></button>
            </div>
        </div>
    </div>

    <!-- ===================== EXPLAIN / CHAT SHEET ===================== -->
    <div class="rh-overlay" id="ovChat">
        <div class="rh-sheet" style="height:82vh; max-height:82vh;">
            <div class="rh-sheet-handle"></div>
            <div class="rh-sheet-head">
                <span id="ic-chat-head"></span>
                <div class="rh-sheet-title">AI Assistant</div>
                <button class="rh-icon-btn sm" id="btnCopyChatTop" title="Copy conversation"></button>
                <button class="rh-icon-btn sm" id="closeChat"></button>
            </div>
            <div class="rh-sheet-body">
                <div class="rh-chat-body" id="chatBody"></div>
            </div>
            <div class="rh-sheet-foot">
                <div class="rh-chat-input-row">
                    <textarea class="rh-input" id="chatInput" placeholder="Ask about your code or the last error..." rows="1"></textarea>
                    <button class="rh-icon-btn" id="btnChatSend" style="background:var(--rh-primary); color:#fff;"></button>
                </div>
            </div>
        </div>
    </div>

    <!-- ===================== CONFIRM DIALOG ===================== -->
    <div class="rh-overlay center" id="ovConfirm">
        <div class="rh-sheet" style="border-radius:22px; padding:22px;">
            <div class="rh-confirm-body">
                <div class="rh-confirm-ic" id="ic-confirm"></div>
                <div style="font-size:15.5px; font-weight:800; margin-bottom:6px;" id="confirmTitle">Are you sure?</div>
                <div class="rh-confirm-msg" id="confirmMsg"></div>
                <div class="rh-confirm-actions">
                    <button class="rh-btn rh-btn-ghost" id="confirmCancel">Cancel</button>
                    <button class="rh-btn rh-btn-danger" id="confirmOk">Delete</button>
                </div>
            </div>
        </div>
    </div>

    <input type="file" id="fileImportInput" accept=".html,.htm,text/html" style="display:none;">
    <div id="toastStack"></div>
</div>

<script>

'use strict';

/* =========================================================================

   RUNHTML — AI PRO SUITE MOBILE TESTING APP

   ========================================================================= */



/* ---------- Icon set (inline SVG, stroke-based) ---------- */

function svg(paths, extra){ return '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" '+(extra||'')+'>'+paths+'</svg>'; }

const ICONS = {

    back: svg('<polyline points="15 18 9 12 15 6"/>'),

    more: svg('<circle cx="12" cy="5" r="1.6" fill="currentColor"/><circle cx="12" cy="12" r="1.6" fill="currentColor"/><circle cx="12" cy="19" r="1.6" fill="currentColor"/>'),

    sparkles: svg('<path d="M12 3v4M12 17v4M3 12h4M17 12h4M5.8 5.8l2.6 2.6M15.6 15.6l2.6 2.6M18.2 5.8l-2.6 2.6M8.4 15.6l-2.6 2.6"/>'),

    play: svg('<polygon points="6 3 20 12 6 21 6 3"/>'),

    undo: svg('<path d="M3 10h11a5 5 0 0 1 0 10h-4"/><polyline points="7 5 3 10 7 15"/>'),

    redo: svg('<path d="M21 10H10a5 5 0 0 0 0 10h4"/><polyline points="17 5 21 10 17 15"/>'),

    search: svg('<circle cx="11" cy="11" r="7"/><line x1="21" y1="21" x2="16.65" y2="16.65"/>'),

    wand: svg('<path d="M4.5 19.5L15 9M13 4l1.2 2.6L17 8l-2.8 1.2L13 12l-1.2-2.8L9 8l2.8-1.4z"/><path d="M18.5 14l.8 1.7 1.7.8-1.7.8-.8 1.7-.8-1.7-1.7-.8 1.7-.8z"/>'),

    layout: svg('<rect x="3" y="3" width="18" height="18" rx="3"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="9" y1="9" x2="9" y2="21"/>'),

    upload: svg('<path d="M12 15V4M7 9l5-5 5 5"/><path d="M4 19h16"/>'),

    copy: svg('<rect x="9" y="9" width="12" height="12" rx="2.5"/><path d="M5 15V5a2 2 0 0 1 2-2h10"/>'),

    trash: svg('<polyline points="3 6 5 6 21 6"/><path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2m2 0v13a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2V6h12z"/>'),

    message: svg('<path d="M21 11.5a8.4 8.4 0 0 1-8.9 8.4 8.6 8.6 0 0 1-3.8-.9L3 20l1.1-5.1a8.4 8.4 0 1 1 16.9-3.4z"/>'),

    camera: svg('<path d="M23 19a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3.5l2-3h7l2 3H21a2 2 0 0 1 2 2z"/><circle cx="12" cy="13" r="4"/>'),

    terminal: svg('<polyline points="4 17 10 11 4 5"/><line x1="12" y1="19" x2="20" y2="19"/>'),

    smartphone: svg('<rect x="6" y="2" width="12" height="20" rx="2.5"/><line x1="10" y1="19" x2="14" y2="19"/>'),

    android: svg('<rect x="5" y="3" width="14" height="18" rx="2.5"/><circle cx="9" cy="6.3" r=".4" fill="currentColor"/>'),

    tablet: svg('<rect x="4" y="3" width="16" height="18" rx="2.5"/><line x1="11" y1="18" x2="13" y2="18"/>'),

    monitor: svg('<rect x="2" y="4" width="20" height="14" rx="2.5"/><line x1="8" y1="21" x2="16" y2="21"/><line x1="12" y1="18" x2="12" y2="21"/>'),

    full: svg('<path d="M8 3H5a2 2 0 0 0-2 2v3M16 3h3a2 2 0 0 1 2 2v3M8 21H5a2 2 0 0 1-2-2v-3M16 21h3a2 2 0 0 0 2-2v-3"/>'),

    rotate: svg('<polyline points="23 4 23 10 17 10"/><path d="M20.5 14a9 9 0 1 1-2.1-9.5L23 10"/>'),

    crosshair: svg('<circle cx="12" cy="12" r="8.5"/><line x1="12" y1="2" x2="12" y2="6"/><line x1="12" y1="18" x2="12" y2="22"/><line x1="2" y1="12" x2="6" y2="12"/><line x1="18" y1="12" x2="22" y2="12"/>'),

    xcircle: svg('<circle cx="12" cy="12" r="9"/><line x1="14.5" y1="9.5" x2="9.5" y2="14.5"/><line x1="9.5" y1="9.5" x2="14.5" y2="14.5"/>'),

    checkcircle: svg('<circle cx="12" cy="12" r="9"/><polyline points="8 12.5 11 15.5 16 9"/>'),

    info: svg('<circle cx="12" cy="12" r="9"/><line x1="12" y1="11" x2="12" y2="16"/><circle cx="12" cy="7.6" r=".6" fill="currentColor" stroke="none"/>'),

    download: svg('<path d="M12 4v12M7 12l5 5 5-5"/><path d="M4 20h16"/>'),

    save: svg('<path d="M5 4h10l4 4v12a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1z"/><path d="M8 4v5h7V4"/><rect x="7.5" y="13" width="9" height="6"/>'),

    plus: svg('<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>'),

    clock: svg('<circle cx="12" cy="12" r="9"/><polyline points="12 7 12 12 15.5 14.5"/>'),

    folder: svg('<path d="M3 6.5A1.5 1.5 0 0 1 4.5 5h5l2 2h8A1.5 1.5 0 0 1 21 8.5v9A1.5 1.5 0 0 1 19.5 19h-15A1.5 1.5 0 0 1 3 17.5z"/>'),

    edit: svg('<path d="M12 20h9"/><path d="M16.5 3.5a2.1 2.1 0 0 1 3 3L7 19l-4.2.8L4 15.5z"/>'),

    send: svg('<line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/>'),

    close: svg('<line x1="6" y1="6" x2="18" y2="18"/><line x1="6" y1="18" x2="18" y2="6"/>'),

    mic: svg('<path d="M12 1a3 3 0 0 0-3 3v8a3 3 0 0 0 6 0V4a3 3 0 0 0-3-3z"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="23"/>'),

    duplicate: svg('<rect x="8" y="8" width="12" height="12" rx="2.5"/><path d="M4 16V4a2 2 0 0 1 2-2h10"/>'),

    fileImport: svg('<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>'),

    sort: svg('<line x1="4" y1="6" x2="14" y2="6"/><line x1="4" y1="12" x2="11" y2="12"/><line x1="4" y1="18" x2="8" y2="18"/><polyline points="17 15 20 18 20 4"/>'),

    alert: svg('<path d="M12 9v4M12 17h.01"/><path d="M10.3 3.9L1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/>'),

    file: svg('<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>'),

    grid: svg('<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>'),

    form: svg('<rect x="3" y="4" width="18" height="16" rx="2"/><line x1="7" y1="9" x2="17" y2="9"/><line x1="7" y1="13" x2="17" y2="13"/><rect x="7" y="16" width="6" height="2"/>'),

    list: svg('<line x1="9" y1="6" x2="20" y2="6"/><line x1="9" y1="12" x2="20" y2="12"/><line x1="9" y1="18" x2="20" y2="18"/><circle cx="4.5" cy="6" r="1"/><circle cx="4.5" cy="12" r="1"/><circle cx="4.5" cy="18" r="1"/>'),

    timer: svg('<circle cx="12" cy="13" r="8"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="9" y1="3" x2="15" y2="3"/>'),

    layers: svg('<polygon points="12 2 22 8.5 12 15 2 8.5 12 2"/><polyline points="2 15.5 12 22 22 15.5"/>'),

    empty: svg('<path d="M21 8v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h5"/><path d="M16 2l6 6M22 2l-6 6"/>'),

    fullscreen: svg('<path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/>'),

    minimize: svg('<path d="M8 3v3h-3m14 -3v3h3m-14 14v-3h-3m14 3v-3h3"/>')

};

function setIc(id, key, cls){ const el = document.getElementById(id); if(el) el.innerHTML = ICONS[key] || ''; if(cls) el.classList.add(cls); }



/* ---------- Storage (localforage with localStorage fallback) ---------- */

const storage = (function(){

    if (window.localforage && typeof window.localforage.getItem === 'function'){

        try{ window.localforage.config({ name:'RunHTML', storeName:'runhtml_store' }); }catch(e){}

        return window.localforage;

    }

    return {

        getItem: (k)=> Promise.resolve().then(()=>{ const v = localStorage.getItem('lf_'+k); return v ? JSON.parse(v) : null; }),

        setItem: (k,v)=> Promise.resolve().then(()=>{ localStorage.setItem('lf_'+k, JSON.stringify(v)); return v; }),

        removeItem: (k)=> Promise.resolve().then(()=>{ localStorage.removeItem('lf_'+k); })

    };

})();

const HISTORY_KEY = 'runhtml_history_v1';

const DRAFT_KEY = 'runhtml_draft_v1';



const TEMPLATES = {

    blank: { name:'Blank Page', icon:'file', code:

`<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>New Page</title>

<style>

  body{font-family:sans-serif; padding:20px; background:#f8fafc;}

</style>

</head>

<body>

  <h1>Hello world</h1>

  <p>Start building here.</p>

</body>

</html>` },

    landing: { name:'Landing Page', icon:'layout', code:

`<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Landing</title>

<style>

  *{box-sizing:border-box;margin:0;padding:0;font-family:sans-serif;}

  body{background:#0f172a;color:#fff;}

  .hero{min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;padding:30px;}

  h1{font-size:2.2rem;background:linear-gradient(90deg,#3b82f6,#8b5cf6);-webkit-background-clip:text;-webkit-text-fill-color:transparent;}

  p{color:#94a3b8;margin:14px 0 26px;max-width:400px;}

  button{background:linear-gradient(135deg,#3b82f6,#8b5cf6);color:#fff;border:none;padding:14px 30px;border-radius:12px;font-size:15px;font-weight:700;cursor:pointer;}

</style>

</head>

<body>

  <div class="hero">

    <h1>Build something great</h1>

    <p>A clean starting point for your next idea. Edit this text and make it yours.</p>

    <button onclick="alert('Clicked!')">Get Started</button>

  </div>

</body>

</html>` },

    form: { name:'Login Form', icon:'form', code:

`<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Login</title>

<style>

  *{box-sizing:border-box;font-family:sans-serif;}

  body{background:#f1f5f9;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;padding:20px;}

  .card{background:#fff;padding:30px 26px;border-radius:18px;box-shadow:0 10px 30px rgba(0,0,0,.08);width:100%;max-width:340px;}

  h2{margin-bottom:18px;}

  input{width:100%;padding:12px;margin-bottom:12px;border:1px solid #e2e8f0;border-radius:10px;font-size:14px;}

  button{width:100%;padding:12px;background:#8b5cf6;color:#fff;border:none;border-radius:10px;font-weight:700;cursor:pointer;}

</style>

</head>

<body>

  <div class="card">

    <h2>Welcome back</h2>

    <form onsubmit="event.preventDefault(); alert('Signed in as ' + document.getElementById('em').value);">

      <input id="em" type="email" placeholder="Email" required>

      <input type="password" placeholder="Password" required>

      <button type="submit">Sign In</button>

    </form>

  </div>

</body>

</html>` },

    cards: { name:'Card Grid', icon:'grid', code:

`<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Cards</title>

<style>

  *{box-sizing:border-box;font-family:sans-serif;}

  body{background:#f8fafc;padding:16px;margin:0;}

  .grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;}

  .card{background:#fff;border-radius:14px;padding:16px;box-shadow:0 4px 14px rgba(0,0,0,.06);}

  .card h3{font-size:14px;margin-bottom:6px;}

  .card p{font-size:12px;color:#64748b;}

</style>

</head>

<body>

  <div class="grid" id="grid"></div>

  <script>

    const items=[["Design","UI kits & tokens"],["Code","Snippets & tools"],["Ship","Deploy fast"],["Learn","Guides & docs"]];

    document.getElementById("grid").innerHTML = items.map(i=>

      '<div class="card"><h3>'+i[0]+'</h3><p>'+i[1]+'</p></div>'

    ).join("");

  <\/script>

</body>

</html>` },

    todo: { name:'Todo App', icon:'list', code:

`<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Todo</title>

<style>

  *{box-sizing:border-box;font-family:sans-serif;}

  body{background:#f1f5f9;margin:0;padding:20px;}

  .wrap{max-width:380px;margin:0 auto;background:#fff;border-radius:16px;padding:18px;box-shadow:0 8px 24px rgba(0,0,0,.06);}

  .row{display:flex;gap:8px;margin-bottom:14px;}

  input[type=text]{flex:1;padding:10px;border:1px solid #e2e8f0;border-radius:10px;}

  button{padding:10px 14px;background:#3b82f6;color:#fff;border:none;border-radius:10px;font-weight:700;cursor:pointer;}

  ul{list-style:none;padding:0;}

  li{display:flex;justify-content:space-between;padding:10px;border-bottom:1px solid #f1f5f9;font-size:14px;}

  li.done{text-decoration:line-through;color:#94a3b8;}

  li span.x{cursor:pointer;color:#ef4444;font-weight:700;}

</style>

</head>

<body>

  <div class="wrap">

    <div class="row">

      <input type="text" id="in" placeholder="Add a task...">

      <button onclick="addTask()">Add</button>

    </div>

    <ul id="list"></ul>

  </div>

  <script>

    let tasks=[];

    function render(){

      document.getElementById("list").innerHTML = tasks.map((t,i)=>

        '<li class="'+(t.done?"done":"")+'"><span onclick="toggle('+i+')">'+t.text+'</span><span class="x" onclick="remove('+i+')">\\u2715</span></li>'

      ).join("");

    }

    function addTask(){

      const inp=document.getElementById("in");

      if(!inp.value.trim())return;

      tasks.push({text:inp.value.trim(),done:false});

      inp.value="";

      render();

    }

    function toggle(i){ tasks[i].done=!tasks[i].done; render(); }

    function remove(i){ tasks.splice(i,1); render(); }

    render();

  <\/script>

</body>

</html>` },

    timer: { name:'Countdown Timer', icon:'timer', code:

`<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>Countdown</title>

<style>

  *{box-sizing:border-box;font-family:sans-serif;}

  body{background:#0f172a;color:#fff;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;}

  .disp{font-size:3.4rem;font-weight:800;font-variant-numeric:tabular-nums;}

  .wrap{text-align:center;}

  .row{margin-top:18px;display:flex;gap:10px;justify-content:center;}

  button{padding:10px 18px;border-radius:10px;border:none;font-weight:700;cursor:pointer;background:#8b5cf6;color:#fff;}

</style>

</head>

<body>

  <div class="wrap">

    <div class="disp" id="disp">00:30</div>

    <div class="row">

      <button onclick="start()">Start</button>

      <button onclick="reset()">Reset</button>

    </div>

  </div>

  <script>

    let seconds=30, iv=null;

    function render(){

      const m=String(Math.floor(seconds/60)).padStart(2,"0");

      const s=String(seconds%60).padStart(2,"0");

      document.getElementById("disp").textContent=m+":"+s;

    }

    function start(){

      if(iv)return;

      iv=setInterval(()=>{

        if(seconds<=0){clearInterval(iv);iv=null;return;}

        seconds--; render();

      },1000);

    }

    function reset(){ clearInterval(iv); iv=null; seconds=30; render(); }

    render();

  <\/script>

</body>

</html>` }

};

  

/* ---------- Injected iframe monitor (function stringified & inlined) ---------- */

function __runhtmlMonitor(){

    var _log=console.log, _warn=console.warn, _err=console.error;

    function ser(args){

        try{

            return Array.prototype.slice.call(args).map(function(a){

                if(a===undefined) return 'undefined';

                if(a===null) return 'null';

                if(typeof a==='object'){ try{ return JSON.stringify(a); }catch(e){ return String(a); } }

                return String(a);

            }).join(' ');

        }catch(e){ return ''; }

    }

    function post(level,args){ try{ parent.postMessage({source:'runhtml-console', level:level, text:ser(args)}, '*'); }catch(e){} }

    console.log=function(){ post('log',arguments); _log.apply(console,arguments); };

    console.warn=function(){ post('warn',arguments); _warn.apply(console,arguments); };

    console.error=function(){ post('error',arguments); _err.apply(console,arguments); };

    window.onerror=function(msg,src,line,col){ try{ parent.postMessage({source:'runhtml-error', text: msg+' (line '+line+')'}, '*'); }catch(e){} return false; };

    window.addEventListener('unhandledrejection', function(e){

        try{ var r=e.reason; var m=(r && r.message) ? r.message : String(r); parent.postMessage({source:'runhtml-error', text:'Unhandled Promise Rejection: '+m}, '*'); }catch(err){}

    });



    var inspectOn=false, overlay=null, labelEl=null;

    function ensureOverlay(){

        if(overlay) return;

        overlay=document.createElement('div');

        overlay.style.cssText='position:fixed;pointer-events:none;border:2px solid #8b5cf6;background:rgba(139,92,246,0.15);z-index:2147483647;transition:all .05s ease;display:none;box-sizing:border-box;';

        labelEl=document.createElement('div');

        labelEl.style.cssText='position:fixed;pointer-events:none;background:#8b5cf6;color:#fff;font:11px monospace;padding:2px 7px;border-radius:5px;z-index:2147483647;display:none;';

        document.documentElement.appendChild(overlay);

        document.documentElement.appendChild(labelEl);

    }

    function describeEl(el){

        var t=el.tagName ? el.tagName.toLowerCase() : 'node';

        var id=el.id ? ('#'+el.id) : '';

        var cls=(el.className && typeof el.className==='string') ? '.'+el.className.trim().split(/\s+/).join('.') : '';

        return t+id+cls;

    }

    function onMove(e){

        if(!inspectOn) return;

        var el=e.target; if(!el || el===document.documentElement) return;

        ensureOverlay();

        var r=el.getBoundingClientRect();

        overlay.style.display='block';

        overlay.style.left=r.left+'px'; overlay.style.top=r.top+'px';

        overlay.style.width=r.width+'px'; overlay.style.height=r.height+'px';

        labelEl.style.display='block';

        labelEl.textContent=describeEl(el)+' \u00b7 '+Math.round(r.width)+'\u00d7'+Math.round(r.height);

        var ly=r.top-22; if(ly<0) ly=r.bottom+2;

        labelEl.style.left=r.left+'px'; labelEl.style.top=ly+'px';

    }

    function onClick(e){

        if(!inspectOn) return;

        e.preventDefault(); e.stopPropagation();

        var el=e.target;

        var r=el.getBoundingClientRect();

        parent.postMessage({source:'runhtml-inspect', desc:describeEl(el), w:Math.round(r.width), h:Math.round(r.height)}, '*');

    }

    document.addEventListener('mousemove', onMove, true);

    document.addEventListener('click', onClick, true);



    window.addEventListener('message', function(e){

        var d=e.data; if(!d || !d.cmd) return;

        if(d.cmd==='inspect-on'){ inspectOn=true; ensureOverlay(); }

        if(d.cmd==='inspect-off'){ inspectOn=false; if(overlay) overlay.style.display='none'; if(labelEl) labelEl.style.display='none'; }

        if(d.cmd==='screenshot'){

            function run(){

                try{

                    window.html2canvas(document.documentElement, {backgroundColor:null}).then(function(canvas){

                        parent.postMessage({source:'runhtml-screenshot', dataUrl:canvas.toDataURL('image/png')}, '*');

                    }).catch(function(err){ parent.postMessage({source:'runhtml-screenshot-error', text:err.message}, '*'); });

                }catch(err){ parent.postMessage({source:'runhtml-screenshot-error', text:err.message}, '*'); }

            }

            if(window.html2canvas){ run(); }

            else{

                var s=document.createElement('script');

                s.src='https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js';

                s.onload=run;

                s.onerror=function(){ parent.postMessage({source:'runhtml-screenshot-error', text:'Could not load screenshot library (are you online?)'}, '*'); };

                document.head.appendChild(s);

            }

        }

    });

}

function injectMonitor(code){

    // Splitting the string prevents the HTML parser from breaking prematurely

    const tag = '<scr' + 'ipt>(' + __runhtmlMonitor.toString() + ')();</scr' + 'ipt>';

    if(/<head[^>]*>/i.test(code)) return code.replace(/<head[^>]*>/i, m=> m+tag);

    if(/<html[^>]*>/i.test(code)) return code.replace(/<html[^>]*>/i, m=> m+tag);

    return tag+code;

}



/* ---------- Lint engine ---------- */

const VOID_TAGS = new Set(['area','base','br','col','embed','hr','img','input','link','meta','param','source','track','wbr']);

function lintHTML(code){

    const issues = [];

    if(!code || !code.trim()) return { ok:true, issues:[] };

    let stripped = code.replace(/<!--[\s\S]*?-->/g, '');



    const scriptRe = /<script(?![^>]*\bsrc=)[^>]*>([\s\S]*?)<\/script>/gi;

    let sm;

    while((sm = scriptRe.exec(stripped))){

        const js = sm[1];

        if(!js || !js.trim()) continue;

        try{ new Function(js); }

        catch(err){ issues.push('JavaScript error: ' + err.message); }

    }



    let forTags = stripped

        .replace(/(<script[^>]*>)([\s\S]*?)(<\/script>)/gi, '$1$3')

        .replace(/(<style[^>]*>)([\s\S]*?)(<\/style>)/gi, '$1$3');



    const tagRe = /<\/?([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*?(\/)?>/g;

    const stack = [];

    let m;

    while((m = tagRe.exec(forTags))){

        const raw = m[0];

        const name = m[1].toLowerCase();

        if(name === '!doctype') continue;

        const selfClose = !!m[2] || /\/>\s*$/.test(raw);

        if(raw[1] === '/'){

            if(VOID_TAGS.has(name)) continue;

            if(stack.length === 0){

                issues.push('Unexpected closing tag </'+name+'> — no matching open tag');

                continue;

            }

            let idx = -1;

            for(let i=stack.length-1;i>=0;i--){ if(stack[i]===name){ idx=i; break; } }

            if(idx === -1){

                issues.push('Closing tag </'+name+'> does not match any open tag');

            } else {

                while(stack.length-1 > idx){

                    const unclosed = stack.pop();

                    issues.push('Tag <'+unclosed+'> was never closed before </'+name+'>');

                }

                stack.pop();

            }

        } else {

            if(VOID_TAGS.has(name) || selfClose) continue;

            stack.push(name);

        }

    }

    if(stack.length){

        issues.push('Missing closing tag(s) for: ' + [...new Set(stack)].map(t=>'<'+t+'>').join(', '));

    }

    return { ok: issues.length===0, issues };

}



/* ---------- App state ---------- */

const state = {

    view:'home',

    tab:'code',

    currentId:null,

    currentName:'Untitled Project',

    conversation:[],

    device:'iphone',

    orientation:'portrait',

    liveAuto:false,

    inspectOn:false,

    consoleOpen:false,

    dirty:false,

    lastError:null,

    history:[],

    genLastCode:null,

    genType:'Landing Page',

    pendingDelete:null,

    listening:false

};



let cm = null; // CodeMirror instance (or null -> fallback textarea)

let autosaveTimer = null;

let liveTimer = null;

let lintTimer = null;



/* ---------- Toast system ---------- */

function showToast(message, type, duration){

    type = type || 'info'; duration = duration || 4500;

    const stack = document.getElementById('toastStack');

    const el = document.createElement('div');

    el.className = 'toast toast-'+type;

    const iconKey = type==='error' ? 'xcircle' : (type==='success' ? 'checkcircle' : 'info');

    el.innerHTML = '<span class="toast-icon">'+ICONS[iconKey]+'</span><span class="toast-msg"></span><button class="toast-close">'+ICONS.close+'</button><div class="toast-bar"></div>';

    el.querySelector('.toast-msg').textContent = message;

    stack.appendChild(el);

    requestAnimationFrame(()=> el.classList.add('show'));

    const bar = el.querySelector('.toast-bar');

    bar.style.animationDuration = duration+'ms';

    const remove = () => { el.classList.remove('show'); setTimeout(()=> el.remove(), 280); };

    const t = setTimeout(remove, duration);

    el.querySelector('.toast-close').onclick = () => { clearTimeout(t); remove(); };

    return el;

}



/* ---------- View router ---------- */

function goView(name){

    document.querySelectorAll('.rh-view').forEach(v=> v.classList.remove('active'));

    document.getElementById('view-'+name).classList.add('active');

    state.view = name;

    if(name === 'home') renderHome();

    if(name === 'history') renderHistory();

    if(name === 'create'){ 

        // THIS FIXES THE EDITOR NOT TYPING BUG (forces proper initialization on next frame)

        requestAnimationFrame(() => {

            if(cm) {

                cm.refresh();

                cm.focus();

            }

            fitDeviceFrame();

        });

    }

}



/* ---------- Sheets / modals ---------- */

function openSheet(id){ document.getElementById(id).classList.add('show'); }

function closeSheet(id){ document.getElementById(id).classList.remove('show'); }

document.querySelectorAll('.rh-overlay').forEach(ov=>{

    ov.addEventListener('click', (e)=>{ if(e.target === ov) ov.classList.remove('show'); });

});



/* ---------- Editor init ---------- */

function initEditor(){

    const ta = document.getElementById('codeArea');

    if(window.CodeMirror){

        ta.value = ""; // Clear out hidden values that break history

        cm = CodeMirror.fromTextArea(ta, {

            mode:'htmlmixed', theme:'dracula', lineNumbers:true, lineWrapping:true,

            matchBrackets:true, autoCloseBrackets:true, autoCloseTags:true,

            tabSize:2, indentUnit:2, styleActiveLine:true,

            readOnly: false, // EXPLICITLY MAKE IT WRITABLE

            extraKeys:{

                'Ctrl-S': ()=>{ handleSaveClick(); },

                'Cmd-S': ()=>{ handleSaveClick(); },

                'Ctrl-Enter': ()=>{ runPreview(true); },

                'Cmd-Enter': ()=>{ runPreview(true); },

                'Ctrl-F': 'findPersistent',

                'Cmd-F': 'findPersistent',

                'Ctrl-B': ()=>{ beautifyCode(); },

                'Cmd-B': ()=>{ beautifyCode(); }

            }

        });

        cm.setValue(TEMPLATES.blank.code);

        cm.clearHistory(); // Force a clean history slate

        cm.on('change', onEditorChange);

        cm.on('cursorActivity', updateUndoRedoButtons);

    } else {

        ta.style.display = 'block';

        ta.className = 'rh-plain-fallback';

        ta.value = TEMPLATES.blank.code;

        ta.addEventListener('input', onEditorChange);

        showToast('Code editor library failed to load — using plain text mode.', 'info', 5000);

    }

    updateUndoRedoButtons();

}

function getCode(){ return cm ? cm.getValue() : document.getElementById('codeArea').value; }

function setCode(code, resetHistory){

    if(cm){ cm.setValue(code || ''); if(resetHistory) cm.clearHistory(); }

    else { document.getElementById('codeArea').value = code || ''; }

    onEditorChange();

}

function updateUndoRedoButtons(){

    const undoBtn = document.getElementById('btnUndo'), redoBtn = document.getElementById('btnRedo');

    if(cm){

        const hs = cm.historySize();

        undoBtn.disabled = hs.undo === 0;

        redoBtn.disabled = hs.redo === 0;

    } else { undoBtn.disabled = true; redoBtn.disabled = true; }

}

function onEditorChange(){

    markDirty(true);

    updateStatusCounts();

    updateUndoRedoButtons();

    clearTimeout(lintTimer);

    lintTimer = setTimeout(updateLintBadge, 500);

    scheduleAutosave();

    if(state.liveAuto){

        clearTimeout(liveTimer);

        liveTimer = setTimeout(()=> runPreview(false), 900);

    }

}

function markDirty(v){ state.dirty = v; document.getElementById('dirtyDot').classList.toggle('show', v); }



function updateStatusCounts(){

    const code = getCode();

    const lines = code.split('\n').length;

    const chars = code.length;

    const kb = (new Blob([code]).size / 1024).toFixed(1);

    document.getElementById('statLines').textContent = lines + ' lines';

    document.getElementById('statChars').textContent = chars + ' chars';

    document.getElementById('statBytes').textContent = kb + ' KB';

}

function updateLintBadge(){

    const res = lintHTML(getCode());

    const badge = document.getElementById('lintBadge');

    if(res.ok){

        badge.className = 'rh-lint-badge ok';

        badge.innerHTML = ICONS.checkcircle + '<span>OK</span>';

        badge.title = 'No issues detected';

    } else {

        badge.className = 'rh-lint-badge bad';

        badge.innerHTML = ICONS.xcircle + '<span>'+res.issues.length+' issue'+(res.issues.length>1?'s':'')+'</span>';

        badge.title = res.issues.join('\n');

    }

    badge.onclick = () => {

        if(res.ok) showToast('No syntax issues detected in your code.', 'success', 3000);

        else showToast(res.issues[0] + (res.issues.length>1 ? ' (+'+(res.issues.length-1)+' more)' : ''), 'error', 6000);

    };

}



/* ---------- Autosave draft ---------- */

function scheduleAutosave(){

    clearTimeout(autosaveTimer);

    autosaveTimer = setTimeout(async ()=>{

        try{

            await storage.setItem(DRAFT_KEY, { name: state.currentName, code: getCode(), conversation: state.conversation, id: state.currentId, ts: Date.now() });

            document.getElementById('autosaveTxt').textContent = 'Draft saved ' + new Date().toLocaleTimeString([], {hour:'2-digit', minute:'2-digit'});

        }catch(e){ /* silent */ }

    }, 1500);

}

async function checkDraftOnHome(){

    try{

        const draft = await storage.getItem(DRAFT_KEY);

        const banner = document.getElementById('draftBanner');

        if(draft && draft.code && draft.code.trim() && draft.code !== TEMPLATES.blank.code){

            banner.style.display = 'flex';

            document.getElementById('draftTime').textContent = 'From ' + new Date(draft.ts).toLocaleString();

        } else {

            banner.style.display = 'none';

        }

    }catch(e){}

}



/* ---------- Lint-aware Run / Preview ---------- */

function buildSrcDoc(code){ return injectMonitor(code); }



function runPreview(showRunToast){

    const code = getCode();

    const lint = lintHTML(code);

    updateLintBadge();

    const iframe = document.getElementById('previewFrame');

    iframe.srcdoc = buildSrcDoc(code);

    clearConsole();

    if(!lint.ok){

        state.lastError = lint.issues[0];

        showToast(lint.issues[0], 'error', 6500);

    } else if(showRunToast){

        showToast('Running preview...', 'success', 1800);

    }

    switchTab('preview');

}



/* ---------- Console drawer ---------- */

function appendConsoleLine(level, text){

    const body = document.getElementById('consoleBody');

    const empty = body.querySelector('.rh-console-empty');

    if(empty) empty.remove();

    const line = document.createElement('div');

    line.className = 'rh-console-line ' + (level || 'log');

    const tag = document.createElement('span');

    tag.className = 'tag'; tag.textContent = level || 'log';

    const msg = document.createElement('span');

    msg.textContent = text;

    line.appendChild(tag); line.appendChild(msg);

    body.appendChild(line);

    body.scrollTop = body.scrollHeight;

}

function clearConsole(){

    document.getElementById('consoleBody').innerHTML = '<div class="rh-console-empty">No output yet — hit Run to see logs &amp; errors here.</div>';

}

function toggleConsole(){

    const d = document.getElementById('consoleDrawer');

    state.consoleOpen = !state.consoleOpen;

    d.classList.toggle('open', state.consoleOpen);

    document.getElementById('btnConsoleToggle').classList.toggle('active', state.consoleOpen);

}



/* ---------- postMessage listener from preview iframe ---------- */

window.addEventListener('message', (e)=>{

    const d = e.data; if(!d || !d.source) return;

    if(d.source === 'runhtml-console'){ appendConsoleLine(d.level, d.text); }

    else if(d.source === 'runhtml-error'){

        appendConsoleLine('error', d.text);

        state.lastError = d.text;

        showToast('Runtime error: ' + d.text, 'error', 6500);

    }

    else if(d.source === 'runhtml-inspect'){

        const info = document.getElementById('inspectInfo');

        info.textContent = d.desc + '  ' + d.w + '\u00d7' + d.h;

        info.classList.add('show');

        clearTimeout(info._t);

        info._t = setTimeout(()=> info.classList.remove('show'), 3000);

    }

    else if(d.source === 'runhtml-screenshot'){

        downloadDataUrl(d.dataUrl, (state.currentName || 'preview').replace(/\s+/g,'_') + '.png');

        showToast('Screenshot downloaded', 'success', 3000);

    }

    else if(d.source === 'runhtml-screenshot-error'){

        showToast('Screenshot failed: ' + d.text, 'error', 5000);

    }

});

function downloadDataUrl(dataUrl, filename){

    const a = document.createElement('a');

    a.href = dataUrl; a.download = filename;

    document.body.appendChild(a); a.click(); a.remove();

}



/* ---------- Device frame / orientation ---------- */

function setDevice(dev){

    state.device = dev;

    document.querySelectorAll('[data-device]').forEach(b=> b.classList.toggle('active', b.dataset.device === dev));

    const el = document.getElementById('deviceEl');

    el.className = 'rh-device ' + dev + (state.orientation === 'landscape' ? ' landscape' : '');

    fitDeviceFrame();

}

function toggleOrientation(){

    state.orientation = state.orientation === 'portrait' ? 'landscape' : 'portrait';

    document.getElementById('deviceEl').classList.toggle('landscape', state.orientation === 'landscape');

    fitDeviceFrame();

}

function fitDeviceFrame(){

    const stage = document.getElementById('previewStage');

    const wrap = document.getElementById('frameWrap');

    const el = document.getElementById('deviceEl');

    if(!stage || !el) return;

    wrap.style.transform = 'scale(1)';

    requestAnimationFrame(()=>{

        const stageW = stage.clientWidth - 20;

        const rect = el.getBoundingClientRect();

        const natural = state.orientation === 'landscape' ? rect.height : rect.width;

        if(natural > stageW && stageW > 0){

            const ratio = Math.max(stageW / natural, 0.45);

            wrap.style.transform = 'scale(' + ratio + ')';

            wrap.style.transformOrigin = 'top center';

        } else {

            wrap.style.transform = 'scale(1)';

        }

    });

}

window.addEventListener('resize', ()=>{ if(state.view === 'create') fitDeviceFrame(); });



/* ---------- Inspector ---------- */

function toggleInspect(){

    state.inspectOn = !state.inspectOn;

    document.getElementById('btnInspect').classList.toggle('active', state.inspectOn);

    const iframe = document.getElementById('previewFrame');

    try{ iframe.contentWindow.postMessage({ cmd: state.inspectOn ? 'inspect-on' : 'inspect-off' }, '*'); }catch(e){}

    showToast(state.inspectOn ? 'Inspector on — tap an element in the preview' : 'Inspector off', 'info', 2500);

}



/* ---------- Screenshot ---------- */

function requestScreenshot(){

    const iframe = document.getElementById('previewFrame');

    try{ iframe.contentWindow.postMessage({ cmd:'screenshot' }, '*'); showToast('Capturing screenshot...', 'info', 2000); }

    catch(e){ showToast('Could not access preview to capture.', 'error'); }

}



/* ---------- Tabs ---------- */

function switchTab(tab){

    state.tab = tab;

    document.getElementById('tabCode').classList.toggle('active', tab==='code');

    document.getElementById('tabPreview').classList.toggle('active', tab==='preview');

    document.getElementById('codeToolbar').style.display = tab==='code' ? 'flex' : 'none';

    document.querySelector('.rh-statusbar').style.display = tab==='code' ? 'flex' : 'none';

    document.getElementById('tabpane-code').style.display = tab==='code' ? 'block' : 'none';

    document.getElementById('tabpane-preview').classList.toggle('active', tab==='preview');

    if(tab==='preview') setTimeout(fitDeviceFrame, 30);

    // Explicit refresh check here too

    if(tab==='code' && cm) requestAnimationFrame(()=> cm.refresh());

}



/* ---------- Beautify ---------- */

function beautifyCode(){

    if(typeof html_beautify === 'undefined'){

        showToast('Beautifier library unavailable (check your connection).', 'error');

        return;

    }

    try{

        const out = html_beautify(getCode(), { indent_size:2, wrap_line_length:0, preserve_newlines:true });

        setCode(out);

        showToast('Code beautified', 'success', 2500);

    }catch(e){ showToast('Could not beautify: ' + e.message, 'error'); }

}



/* ---------- AI helper ---------- */

async function callAI(userPrompt, systemPrompt, isCode){

    const res = await fetch('/api/other', {

        method:'POST',

        headers:{ 'Content-Type':'application/json' },

        body: JSON.stringify({ userPrompt, systemPrompt: systemPrompt||'', isCode: !!isCode, providerOverride:'auto' })

    });

    if(!res.ok){ 

        let msg = 'AI request failed'; 

        try { const j = await res.json(); msg = j.error || msg; } catch(e){} 

        throw new Error(msg); 

    }

    const data = await res.json();

    

    // Checks multiple fields just in case your server.js formats the response differently for code

    return data.text || data.code || data.reply || data.response || (typeof data === 'string' ? data : JSON.stringify(data));

}



function extractCode(text){

    if(!text) return '';

    

    // 1. Catch standard markdown fences, even if it says ```xml or something dumb

    const fence = text.match(/```[a-zA-Z]*\s*([\s\S]*?)```/);

    if(fence) return fence[1].trim();

    

    // 2. If the AI ignored fences entirely but gave raw HTML, strictly slice it out

    const htmlStart = text.match(/<!DOCTYPE html>|<html/i);

    if(htmlStart) {

        return text.substring(htmlStart.index).trim();

    }

    

    return text.trim();

}



/* ---------- Generate modal ---------- */

const GEN_TYPES = ['Landing Page','Login / Signup Form','Dashboard','Card / Profile','Game','Quiz','Todo App','Countdown Timer','Custom'];

function renderGenChips(){

    const wrap = document.getElementById('genTypeChips');

    wrap.innerHTML = '';

    GEN_TYPES.forEach(t=>{

        const chip = document.createElement('button');

        chip.className = 'rh-chip' + (t === state.genType ? ' selected' : '');

        chip.textContent = t;

        chip.onclick = () => { state.genType = t; renderGenChips(); };

        wrap.appendChild(chip);

    });

}

function openGenerateModal(){

    document.getElementById('genResult').classList.remove('show');

    document.getElementById('genPrompt').value = '';

    renderGenChips();

    openSheet('ovGenerate');

}

async function doGenerate(){

    const promptText = document.getElementById('genPrompt').value.trim();

    if(!promptText){ showToast('Describe what you want first.', 'error'); return; }

    const btn = document.getElementById('btnDoGenerate');

    btn.classList.add('loading');

    btn.innerHTML = '<span class="rh-spinner"></span> Generating '+state.genType+'...';

    try{

        const userPrompt = 'Create a complete, single-file, mobile-friendly HTML page for: '+state.genType+'.\nRequirements: '+promptText+'\nReturn ONLY the raw HTML code (including <!DOCTYPE html>, inline <style> and <script> as needed). No explanation, no markdown fences — output must start directly with <!DOCTYPE html>.';

        const sysPrompt = 'You are an expert front-end developer. Always return a single, complete, runnable HTML file only — clean, modern, responsive, mobile-first. Never include commentary.';

        const text = await callAI(userPrompt, sysPrompt, true);

        const code = extractCode(text);

        state.genLastCode = code;

        document.getElementById('genPreviewFrame').srcdoc = buildSrcDoc(code);

        document.getElementById('genResult').classList.add('show');

        showToast('Generated! Preview it below.', 'success', 3000);

    }catch(e){

        showToast('Generate failed: ' + e.message, 'error', 6000);

    }finally{

        btn.classList.remove('loading');

        btn.innerHTML = ICONS.sparkles + ' Generate';

    }

}

function moveGenerated(mode){

    if(!state.genLastCode) return;

    if(mode === 'replace'){ setCode(state.genLastCode); }

    else {

        if(cm){ cm.replaceSelection(state.genLastCode); }

        else {

            const ta = document.getElementById('codeArea');

            const pos = ta.selectionStart;

            ta.value = ta.value.slice(0,pos) + state.genLastCode + ta.value.slice(pos);

            onEditorChange();

        }

    }

    closeSheet('ovGenerate');

    showToast('Code moved into editor', 'success', 2500);

    switchTab('code');

}



/* ---------- Voice input (Web Speech API) ---------- */

function initMic(){

    const SR = window.SpeechRecognition || window.webkitSpeechRecognition;

    const btn = document.getElementById('btnMic');

    if(!SR){ btn.disabled = true; document.getElementById('micStatus').textContent = 'Voice input not supported on this browser.'; return; }

    let rec = null;

    btn.addEventListener('click', ()=>{

        if(state.listening){ if(rec) rec.stop(); return; }

        rec = new SR();

        rec.lang = 'en-US'; rec.interimResults = false;

        rec.onstart = ()=>{ state.listening = true; btn.classList.add('active'); document.getElementById('micStatus').textContent = 'Listening...'; };

        rec.onerror = ()=>{ document.getElementById('micStatus').textContent = 'Could not hear you — try again.'; };

        rec.onend = ()=>{ state.listening = false; btn.classList.remove('active'); document.getElementById('micStatus').textContent = 'Tap mic to speak your prompt'; };

        rec.onresult = (e)=>{

            const t = e.results[0][0].transcript;

            const ta = document.getElementById('genPrompt');

            ta.value = (ta.value ? ta.value + ' ' : '') + t;

        };

        rec.start();

    });

}



/* ---------- Explain / Chat ---------- */

function renderChat(){

    const body = document.getElementById('chatBody');

    if(!state.conversation.length){

        body.innerHTML = '<div class="rh-chat-empty">'+ICONS.message.replace('<svg ', '<svg style="width:36px;height:36px;" ')+'<p>Ask about your code, or hit Explain right after Run to debug an error.</p></div>';

        return;

    }

    body.innerHTML = '';

    state.conversation.forEach(m=>{

        const row = document.createElement('div');

        row.className = 'rh-msg ' + m.role;

        const bub = document.createElement('div');

        bub.className = 'rh-bubble';

        if(m.role === 'ai' && window.marked){ bub.innerHTML = marked.parse(m.text); }

        else { bub.textContent = m.text; }

        row.appendChild(bub);

        body.appendChild(row);

    });

    body.scrollTop = body.scrollHeight;

}

function chatTranscript(){

    return state.conversation.map(m=> (m.role==='user' ? 'User: ' : 'Assistant: ') + m.text).join('\n\n');

}

async function openExplain(){

    openSheet('ovChat');

    renderChat();

    if(state.conversation.length === 0){

        const code = getCode();

        const errText = state.lastError;

        let firstMsg;

        if(errText){

            firstMsg = 'Here is my HTML code:\n\n```html\n' + code + '\n```\n\nExplain this error: ' + errText;

        } else {

            firstMsg = 'Here is my HTML code:\n\n```html\n' + code + '\n```\n\nExplain what this code does, briefly.';

        }

        await sendChat(firstMsg, true);

    }

}

async function sendChat(text, silent){

    if(!text || !text.trim()) return;

    state.conversation.push({ role:'user', text: text.trim(), ts: Date.now() });

    renderChat();

    const body = document.getElementById('chatBody');

    const typing = document.createElement('div');

    typing.className = 'rh-msg ai'; typing.id = 'typingIndicator';

    typing.innerHTML = '<div class="rh-bubble rh-typing"><span></span><span></span><span></span></div>';

    body.appendChild(typing); body.scrollTop = body.scrollHeight;

    try{

        const sysPrompt = 'You are a friendly, concise coding tutor helping someone test and debug an HTML page on their phone. Explain errors and code simply, suggest concrete fixes, use short paragraphs or bullet points. Continue the conversation naturally using the transcript given.';

        const transcript = chatTranscript();

        const reply = await callAI(transcript, sysPrompt, false);

        state.conversation.push({ role:'ai', text: reply.trim(), ts: Date.now() });

    }catch(e){

        state.conversation.push({ role:'ai', text: 'Sorry, I could not reach the AI service: ' + e.message, ts: Date.now() });

    }finally{

        const t = document.getElementById('typingIndicator'); if(t) t.remove();

        renderChat();

        scheduleAutosave();

    }

}



/* ---------- Save / History (localforage) ---------- */

async function loadHistory(){

    try{ state.history = (await storage.getItem(HISTORY_KEY)) || []; }

    catch(e){ state.history = []; }

    return state.history;

}

async function persistHistory(){ await storage.setItem(HISTORY_KEY, state.history); }



function openSaveModal(){

    document.getElementById('saveNameInput').value = state.currentName || 'Untitled Project';

    openSheet('ovSave');

}

async function confirmSave(){

    const name = document.getElementById('saveNameInput').value.trim() || 'Untitled Project';

    await loadHistory();

    const now = Date.now();

    if(state.currentId){

        const idx = state.history.findIndex(h=> h.id === state.currentId);

        if(idx >= 0){

            state.history[idx] = { ...state.history[idx], name, html:getCode(), conversation:state.conversation, updatedAt:now };

        } else {

            state.history.unshift({ id: state.currentId, name, html:getCode(), conversation:state.conversation, createdAt:now, updatedAt:now });

        }

    } else {

        const id = 'p_' + now + '_' + Math.random().toString(36).slice(2,8);

        state.currentId = id;

        state.history.unshift({ id, name, html:getCode(), conversation:state.conversation, createdAt:now, updatedAt:now });

    }

    state.currentName = name;

    document.getElementById('fileNameInput').value = name;

    await persistHistory();

    markDirty(false);

    closeSheet('ovSave');

    showToast('Saved to History ✓', 'success', 3000);

}

function handleSaveClick(){ openSaveModal(); }



async function restoreEntry(id){

    await loadHistory();

    const entry = state.history.find(h=> h.id === id);

    if(!entry) return;

    state.currentId = entry.id;

    state.currentName = entry.name;

    state.conversation = entry.conversation ? JSON.parse(JSON.stringify(entry.conversation)) : [];

    state.lastError = null;

    document.getElementById('fileNameInput').value = entry.name;

    setCode(entry.html, true);

    markDirty(false);

    goView('create');

    switchTab('code');

    showToast('Restored "' + entry.name + '"', 'success', 2500);

}

async function duplicateEntry(id){

    await loadHistory();

    const entry = state.history.find(h=> h.id === id);

    if(!entry) return;

    const now = Date.now();

    const copy = { ...entry, id:'p_'+now+'_'+Math.random().toString(36).slice(2,8), name: entry.name + ' (copy)', createdAt:now, updatedAt:now };

    state.history.unshift(copy);

    await persistHistory();

    renderHistory();

    showToast('Duplicated project', 'success', 2500);

}

function renameEntryPrompt(id){

    const entry = state.history.find(h=> h.id === id);

    if(!entry) return;

    const el = document.querySelector('.rh-hist-card[data-id="'+id+'"] .rh-hist-name');

    if(!el) return;

    el.contentEditable = 'true';

    el.focus();

    document.execCommand && document.execCommand('selectAll', false, null);

    const done = async ()=>{

        el.contentEditable = 'false';

        const newName = el.textContent.trim() || entry.name;

        entry.name = newName; entry.updatedAt = Date.now();

        if(state.currentId === id){ state.currentName = newName; document.getElementById('fileNameInput').value = newName; }

        await persistHistory();

        renderHistory();

    };

    el.addEventListener('blur', done, { once:true });

    el.addEventListener('keydown', (e)=>{ if(e.key === 'Enter'){ e.preventDefault(); el.blur(); } });

}

function askDeleteEntry(id){

    state.pendingDelete = id;

    document.getElementById('confirmTitle').textContent = 'Delete this project?';

    document.getElementById('confirmMsg').textContent = 'This will permanently remove it from your history. This can\'t be undone.';

    openSheet('ovConfirm');

}

async function doDeleteConfirmed(){

    if(!state.pendingDelete) return;

    await loadHistory();

    state.history = state.history.filter(h=> h.id !== state.pendingDelete);

    await persistHistory();

    if(state.currentId === state.pendingDelete) state.currentId = null;

    state.pendingDelete = null;

    closeSheet('ovConfirm');

    renderHistory();

    showToast('Project deleted', 'info', 2500);

}



/* ---------- History view render ---------- */

let histSortMode = 'newest';

function renderHistory(){

    loadHistory().then(()=>{

        const q = (document.getElementById('histSearch').value || '').toLowerCase();

        let list = state.history.filter(h=> h.name.toLowerCase().includes(q));

        list.sort((a,b)=>{

            if(histSortMode === 'newest') return b.updatedAt - a.updatedAt;

            if(histSortMode === 'oldest') return a.updatedAt - b.updatedAt;

            if(histSortMode === 'name') return a.name.localeCompare(b.name);

            return 0;

        });

        const empty = document.getElementById('histEmpty');

        const listEl = document.getElementById('histList');

        if(list.length === 0){

            empty.style.display = 'block'; listEl.innerHTML = '';

            setIc('ic-empty','folder');

            return;

        }

        empty.style.display = 'none';

        listEl.innerHTML = '';

        list.forEach(entry=>{

            const card = document.createElement('div');

            card.className = 'rh-hist-card';

            card.dataset.id = entry.id;

            const sizeKb = (new Blob([entry.html||'']).size/1024).toFixed(1);

            const dt = new Date(entry.updatedAt || entry.createdAt).toLocaleString([], {month:'short', day:'numeric', hour:'2-digit', minute:'2-digit'});

            card.innerHTML = `

                <div class="rh-hist-top">

                    <div class="rh-hist-ic">${ICONS.file}</div>

                    <div class="rh-hist-meta">

                        <div class="rh-hist-name" spellcheck="false"></div>

                        <div class="rh-hist-sub">${dt} · ${sizeKb} KB${entry.conversation && entry.conversation.length ? ' · ' + entry.conversation.length + ' msgs' : ''}</div>

                    </div>

                </div>

                <div class="rh-hist-snippet"></div>

                <div class="rh-hist-actions">

                    <button class="rh-icon-btn sm" data-act="restore" title="Restore">${ICONS.folder}</button>

                    <button class="rh-icon-btn sm" data-act="rename" title="Rename">${ICONS.edit}</button>

                    <button class="rh-icon-btn sm" data-act="dup" title="Duplicate">${ICONS.duplicate}</button>

                    <button class="rh-icon-btn sm" data-act="del" title="Delete">${ICONS.trash}</button>

                </div>

            `;

            card.querySelector('.rh-hist-name').textContent = entry.name;

            card.querySelector('.rh-hist-snippet').textContent = (entry.html||'').slice(0,160).replace(/\s+/g,' ');

            card.querySelector('[data-act="restore"]').onclick = ()=> restoreEntry(entry.id);

            card.querySelector('[data-act="rename"]').onclick = ()=> renameEntryPrompt(entry.id);

            card.querySelector('[data-act="dup"]').onclick = ()=> duplicateEntry(entry.id);

            card.querySelector('[data-act="del"]').onclick = ()=> askDeleteEntry(entry.id);

            listEl.appendChild(card);

        });

    });

}



/* ---------- Home view render ---------- */

function renderHome(){

    loadHistory().then((list)=>{

        document.getElementById('statCount').textContent = list.length;

        const totalBytes = list.reduce((s,h)=> s + new Blob([h.html||'']).size, 0);

        document.getElementById('statSize').textContent = (totalBytes/1024).toFixed(1) + ' KB';

        if(list.length){

            const latest = list.reduce((a,b)=> (a.updatedAt > b.updatedAt ? a : b));

            const days = Math.floor((Date.now() - latest.updatedAt) / 86400000);

            document.getElementById('statLast').textContent = days === 0 ? 'Today' : (days+'d ago');

        } else {

            document.getElementById('statLast').textContent = '—';

        }

    });

    checkDraftOnHome();

}



/* ---------- Templates gallery ---------- */

function renderTemplateGrid(targetId, onPick){

    const grid = document.getElementById(targetId);

    grid.innerHTML = '';

    Object.keys(TEMPLATES).forEach(key=>{

        const t = TEMPLATES[key];

        const card = document.createElement('button');

        card.className = targetId === 'homeTemplateStrip' ? 'rh-tmpl-chip' : 'rh-tmpl-card';

        if(targetId === 'homeTemplateStrip'){ card.textContent = t.name; }

        else { card.innerHTML = ICONS[t.icon] + '<div class="rh-tmpl-card-name">'+t.name+'</div>'; }

        card.onclick = ()=> onPick(key);

        grid.appendChild(card);

    });

}

function loadTemplateIntoEditor(key){

    const t = TEMPLATES[key];

    if(!t) return;

    if(state.dirty && getCode().trim() && getCode() !== TEMPLATES.blank.code){

        if(!confirm('Replace current code with "'+t.name+'" template? Unsaved changes will be lost.')) return;

    }

    setCode(t.code, true);

    state.currentId = null;

    state.currentName = t.name;

    document.getElementById('fileNameInput').value = t.name;

    state.conversation = [];

    markDirty(false);

    closeSheet('ovTemplates');

    goView('create'); switchTab('code');

    showToast('Loaded "'+t.name+'" template', 'success', 2500);

}



/* ---------- Import / Copy / Download / Clear ---------- */

function importFile(){ document.getElementById('fileImportInput').click(); }

function handleImportedFile(file){

    if(!file) return;

    const reader = new FileReader();

    reader.onload = ()=>{ setCode(reader.result, true); state.currentId = null; state.currentName = file.name.replace(/\.(html?|htm)$/i,''); document.getElementById('fileNameInput').value = state.currentName; showToast('Imported ' + file.name, 'success', 2500); };

    reader.onerror = ()=> showToast('Could not read that file.', 'error');

    reader.readAsText(file);

}

async function copyCode(){

    try{ await navigator.clipboard.writeText(getCode()); showToast('Code copied to clipboard', 'success', 2200); }

    catch(e){ showToast('Copy failed — select and copy manually.', 'error'); }

}

async function copyConversation(){

    try{ await navigator.clipboard.writeText(chatTranscript()); showToast('Conversation copied', 'success', 2200); }

    catch(e){ showToast('Copy failed.', 'error'); }

}

function downloadHTML(){

    const code = getCode();

    const blob = new Blob([code], { type:'text/html' });

    const url = URL.createObjectURL(blob);

    const a = document.createElement('a');

    a.href = url; a.download = (state.currentName || 'index').replace(/\s+/g,'_') + '.html';

    document.body.appendChild(a); a.click(); a.remove();

    URL.revokeObjectURL(url);

    showToast('Downloaded ' + a.download, 'success', 2500);

}

function clearEditorPrompt(){

    if(!confirm('Clear all code in the editor? This cannot be undone unless you use Undo.')) return;

    setCode('');

    showToast('Editor cleared', 'info', 2000);

}

function newBlankProject(){

    if(state.dirty && getCode().trim()){

        if(!confirm('Start a new blank project? Unsaved changes will be lost.')) return;

    }

    setCode(TEMPLATES.blank.code, true);

    state.currentId = null; state.currentName = 'Untitled Project'; state.conversation = [];

    document.getElementById('fileNameInput').value = state.currentName;

    markDirty(false);

    closeSheet('ovMore');

}



/* ---------- Wire up all icons ---------- */

function wireIcons(){

    setIc('btnBackHome','back'); setIc('btnBackHome2','back'); setIc('btnMoreMenu','more');

    setIc('tabCode','file'); document.getElementById('tabCode').innerHTML = ICONS.file + '<span>Code</span>';

    setIc('tabPreview','smartphone'); document.getElementById('tabPreview').innerHTML = ICONS.smartphone + '<span>Preview</span>';

    

    // FULLSCREEN TOGGLE

    setIc('btnFullscreen', 'fullscreen');

    setIc('btnCloseFs', 'close');



    setIc('btnGenerate','sparkles'); setIc('btnUndo','undo'); setIc('btnRedo','redo');

    setIc('btnFind','search'); setIc('btnBeautify','wand'); setIc('btnTemplates','layout');

    setIc('btnImport','fileImport'); setIc('btnCopyCode','copy'); setIc('btnClearCode','trash');

    setIc('devIphone','smartphone'); setIc('devAndroid','android'); setIc('devTablet','tablet');

    setIc('devDesktop','monitor'); setIc('devFull','full'); setIc('btnRotate','rotate');

    setIc('btnInspect','crosshair'); setIc('btnScreenshot','camera'); setIc('btnConsoleToggle','terminal');

    setIc('ic-terminal','terminal'); setIc('btnClearConsole','trash');

    setIc('btnExplain','message');

    document.getElementById('btnRun').innerHTML = ICONS.play + ' <span>Run</span>';

    setIc('btnSave','save'); setIc('btnDownload','download');

    setIc('ic-create-card','sparkles'); setIc('ic-history-card','clock');

    setIc('ic-arrow1','back'); document.getElementById('ic-arrow1').style.transform='rotate(180deg)';

    setIc('ic-arrow2','back'); document.getElementById('ic-arrow2').style.transform='rotate(180deg)';

    setIc('ic-draft','alert');

    setIc('btnDiscardDraft','close');

    setIc('ic-gen-head','sparkles'); setIc('closeGenerate','close');

    setIc('btnMic','mic');

    document.getElementById('btnMoveReplace').innerHTML = ICONS.download + ' Replace Editor';

    document.getElementById('btnMoveInsert').innerHTML = ICONS.plus + ' Insert at Cursor';

    document.getElementById('btnRegenerate').innerHTML = ICONS.sparkles + ' Regenerate';

    document.getElementById('btnDiscardGen').innerHTML = ICONS.trash + ' Discard';

    document.getElementById('btnDoGenerate').innerHTML = ICONS.sparkles + ' Generate';

    setIc('ic-tmpl-head','layout'); setIc('closeTemplates','close');

    setIc('ic-save-head','save'); setIc('closeSave','close');

    document.getElementById('btnConfirmSave').innerHTML = ICONS.save + ' Save Project';

    setIc('ic-chat-head','message'); setIc('closeChat','close'); setIc('btnCopyChatTop','copy');

    setIc('btnChatSend','send');

    setIc('ic-confirm','trash'); setIc('confirmOk','trash'); document.getElementById('confirmOk').innerHTML = ICONS.trash + ' Delete';

    setIc('confirmCancel','close'); document.getElementById('confirmCancel').textContent = 'Cancel';

    setIc('btnHistSort','sort');

    document.getElementById('menuSaveAs').innerHTML = ICONS.save + ' Save As New';

    document.getElementById('menuDuplicate').innerHTML = ICONS.duplicate + ' Duplicate Current';

    document.getElementById('menuCopyChat').innerHTML = ICONS.copy + ' Copy Conversation';

    document.getElementById('menuNewBlank').innerHTML = ICONS.plus + ' New Blank Project';

    document.getElementById('menuShortcuts').innerHTML = ICONS.terminal + ' Keyboard Shortcuts';

}



/* ---------- Event wiring ---------- */

function wireEvents(){

    document.getElementById('btnGoCreate').onclick = ()=>{ goView('create'); switchTab('code'); setTimeout(()=> cm && cm.focus(), 200); };

    document.getElementById('btnGoHistory').onclick = ()=> goView('history');

    document.getElementById('btnBackHome').onclick = ()=> goView('home');

    document.getElementById('btnBackHome2').onclick = ()=> goView('home');

    document.getElementById('btnResumeDraft').onclick = async ()=>{

        const draft = await storage.getItem(DRAFT_KEY);

        if(draft){

            state.currentId = draft.id || null; state.currentName = draft.name || 'Untitled Project';

            state.conversation = draft.conversation || [];

            document.getElementById('fileNameInput').value = state.currentName;

            goView('create'); switchTab('code');

            setTimeout(()=> setCode(draft.code, true), 60);

        }

    };

    document.getElementById('btnDiscardDraft').onclick = async ()=>{ await storage.removeItem(DRAFT_KEY); document.getElementById('draftBanner').style.display='none'; };



    document.getElementById('fileNameInput').oninput = (e)=>{ state.currentName = e.target.value || 'Untitled Project'; markDirty(true); scheduleAutosave(); };



    document.getElementById('tabCode').onclick = ()=> switchTab('code');

    document.getElementById('tabPreview').onclick = ()=> switchTab('preview');



    // FULL SCREEN TOGGLE LOGIC

    const toggleFs = () => {

        const wrap = document.getElementById('tabpane-code');

        wrap.classList.toggle('fs-mode');

        const isFs = wrap.classList.contains('fs-mode');

        setIc('btnFullscreen', isFs ? 'minimize' : 'fullscreen');

        if(cm) cm.refresh();

    };

    document.getElementById('btnFullscreen').onclick = toggleFs;

    document.getElementById('btnCloseFs').onclick = toggleFs;



    document.getElementById('btnGenerate').onclick = openGenerateModal;

    document.getElementById('closeGenerate').onclick = ()=> closeSheet('ovGenerate');

    document.getElementById('btnDoGenerate').onclick = doGenerate;

    document.getElementById('btnRegenerate').onclick = doGenerate;

    document.getElementById('btnMoveReplace').onclick = ()=> moveGenerated('replace');

    document.getElementById('btnMoveInsert').onclick = ()=> moveGenerated('insert');

    document.getElementById('btnDiscardGen').onclick = ()=> closeSheet('ovGenerate');



    document.getElementById('btnUndo').onclick = ()=>{ if(cm) cm.undo(); };

    document.getElementById('btnRedo').onclick = ()=>{ if(cm) cm.redo(); };

    document.getElementById('btnFind').onclick = ()=>{ if(cm) cm.execCommand('findPersistent'); else showToast('Find requires the code editor library.', 'info'); };

    document.getElementById('btnBeautify').onclick = beautifyCode;

    document.getElementById('btnTemplates').onclick = ()=>{ renderTemplateGrid('tmplGrid', loadTemplateIntoEditor); openSheet('ovTemplates'); };

    document.getElementById('closeTemplates').onclick = ()=> closeSheet('ovTemplates');

    document.getElementById('btnImport').onclick = importFile;

    document.getElementById('fileImportInput').onchange = (e)=> handleImportedFile(e.target.files[0]);

    document.getElementById('btnCopyCode').onclick = copyCode;

    document.getElementById('btnClearCode').onclick = clearEditorPrompt;



    document.querySelectorAll('[data-device]').forEach(b=> b.onclick = ()=> setDevice(b.dataset.device));

    document.getElementById('btnRotate').onclick = toggleOrientation;

    document.getElementById('btnInspect').onclick = toggleInspect;

    document.getElementById('btnScreenshot').onclick = requestScreenshot;

    document.getElementById('btnConsoleToggle').onclick = toggleConsole;

    document.getElementById('btnClearConsole').onclick = clearConsole;



    document.getElementById('btnRun').onclick = ()=> runPreview(true);

    document.getElementById('btnSave').onclick = handleSaveClick;

    document.getElementById('btnDownload').onclick = downloadHTML;

    document.getElementById('btnExplain').onclick = openExplain;



    document.getElementById('liveSwitch').onclick = ()=>{

        state.liveAuto = !state.liveAuto;

        document.getElementById('liveSwitch').classList.toggle('on', state.liveAuto);

        showToast(state.liveAuto ? 'Live auto-preview enabled' : 'Live auto-preview disabled', 'info', 2200);

    };



    document.getElementById('closeSave').onclick = ()=> closeSheet('ovSave');

    document.getElementById('btnConfirmSave').onclick = confirmSave;



    document.getElementById('closeChat').onclick = ()=> closeSheet('ovChat');

    document.getElementById('btnCopyChatTop').onclick = copyConversation;

    document.getElementById('btnChatSend').onclick = ()=>{

        const inp = document.getElementById('chatInput');

        const val = inp.value; inp.value = '';

        sendChat(val);

    };

    document.getElementById('chatInput').addEventListener('keydown', (e)=>{

        if(e.key === 'Enter' && !e.shiftKey){ e.preventDefault(); document.getElementById('btnChatSend').click(); }

    });



    document.getElementById('confirmCancel').onclick = ()=>{ state.pendingDelete = null; closeSheet('ovConfirm'); };

    document.getElementById('confirmOk').onclick = doDeleteConfirmed;



    document.getElementById('btnMoreMenu').onclick = ()=> openSheet('ovMore');

    document.getElementById('menuSaveAs').onclick = ()=>{ state.currentId = null; closeSheet('ovMore'); openSaveModal(); };

    document.getElementById('menuDuplicate').onclick = async ()=>{

        closeSheet('ovMore');

        if(!state.currentId){ showToast('Save this project first, then duplicate it from History.', 'info'); return; }

        await duplicateEntry(state.currentId);

        showToast('Duplicated — find it in History', 'success');

    };

    document.getElementById('menuCopyChat').onclick = ()=>{ closeSheet('ovMore'); copyConversation(); };

    document.getElementById('menuNewBlank').onclick = newBlankProject;

    document.getElementById('menuShortcuts').onclick = ()=>{

        closeSheet('ovMore');

        showToast('Ctrl+S Save · Ctrl+Enter Run · Ctrl+F Find · Ctrl+B Beautify · Ctrl+Z/Y Undo/Redo', 'info', 7000);

    };



    document.getElementById('histSearch').oninput = renderHistory;

    document.getElementById('btnHistSort').onclick = ()=>{

        histSortMode = histSortMode === 'newest' ? 'oldest' : (histSortMode === 'oldest' ? 'name' : 'newest');

        showToast('Sorted by: ' + histSortMode, 'info', 1800);

        renderHistory();

    };



    document.addEventListener('keydown', (e)=>{

        const mod = e.ctrlKey || e.metaKey;

        if(!mod) return;

        if(e.key.toLowerCase() === 's'){ e.preventDefault(); if(state.view === 'create') handleSaveClick(); }

        if(e.key === 'Enter'){ if(state.view === 'create'){ e.preventDefault(); runPreview(true); } }

    });

}



/* ---------- Init ---------- */

document.addEventListener('DOMContentLoaded', async ()=>{

    wireIcons();

    wireEvents();

    initEditor();

    initMic();

    renderTemplateGrid('homeTemplateStrip', (key)=>{ loadTemplateIntoEditor(key); });

    updateStatusCounts();

    updateLintBadge();

    setDevice('iphone');

    goView('home');

});

</script>
</body>
</html>