# All files / blocks/markdown edit.js

0% Statements 0/712
0% Branches 0/488
0% Functions 0/95
0% Lines 0/697

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    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
    2033
    2034
    2035
    2036
    2037
    2038
    2039
    2040
    2041
    2042
    2043
    2044
    2045
    2046
    2047
    2048
    2049
    2050
    2051
    2052
    2053
    2054
    2055
    2056
    2057
    2058
    2059
    2060
    2061
    2062
    2063
    2064
    2065
    2066
    2067
    2068
    2069

     /**
     * Markdown Block Editor Component
     *
     * @package WpGfmRenderer
     */

    import { __ } from '@wordpress/i18n';
    import {
    	useBlockProps,
    	BlockControls,
    	InspectorControls,
    	MediaUpload,
    	MediaUploadCheck
    } from '@wordpress/block-editor';
    import {
    	Panel,
    	PanelBody,
    	PanelRow,
    	ToolbarGroup,
    	ToolbarButton,
    	ResizableBox,
    	ColorPicker,
    	ToggleControl,
    	SelectControl,
    	TextControl,
    	Button,
    	Modal
    } from '@wordpress/components';
    import { useState, useEffect, useRef, useCallback, useMemo } from '@wordpress/element';
    import { RawHTML } from '@wordpress/element';

    // Import frontmatter parser
    import { parseFrontMatter, renderFrontmatterHeader } from './frontmatter-parser';

    // Import markdown-it
    import MarkdownIt from 'markdown-it';
    import markdownItTaskLists from 'markdown-it-task-lists';
    import markdownItFootnote from 'markdown-it-footnote';
    import markdownItMark from 'markdown-it-mark';
    import markdownItStrikethrough from 'markdown-it-strikethrough-alt';

    /**
     * Initialize markdown-it instance (with Shiki integration support)
     * Default highlight function is provided for pre-Shiki fallback
     */
    let md = new MarkdownIt({
    	html: true,        // Allow HTML tags
    	breaks: true,      // Convert newlines to <br>
    	linkify: true,     // Automatically convert URLs to links
    	typographer: true, // Enable typography features
    	highlight: function(code, lang) {
    		// Pre-Shiki fallback: render code blocks as plain text with escaping
    		const escapedCode = code
    			.replace(/&/g, '&amp;')
    			.replace(/</g, '&lt;')
    			.replace(/>/g, '&gt;');
    		const langClass = lang ? ` class="language-${lang}"` : '';
    		return `<pre class="gfmr-code-fallback"><code${langClass}>${escapedCode}</code></pre>`;
    	}
    })
    .use(markdownItTaskLists, { enabled: true })  // Task lists
    .use(markdownItFootnote)                      // Footnotes
    .use(markdownItMark)                          // Marking (==text==)
    .use(markdownItStrikethrough);                // Strikethrough

    // Cache for Shiki highlighter (for editor)
    let editorShikiHighlighter = null;
    let shikiLoadPromise = null;

    // Shiki retry configuration
    const SHIKI_RETRY_CONFIG = {
    	maxRetries: 3,
    	baseDelay: 1000, // 1 second
    	maxDelay: 8000,  // 8 seconds max
    };
    let shikiRetryCount = 0;
    let shikiLoadStatus = 'idle'; // 'idle' | 'loading' | 'loaded' | 'failed'

    /**
     * Calculate exponential backoff delay
     * @param {number} retryCount Current retry attempt number
     * @returns {number} Delay in milliseconds
     */
    const calculateBackoffDelay = (retryCount) => {
    	const delay = SHIKI_RETRY_CONFIG.baseDelay * Math.pow(2, retryCount);
    	return Math.min(delay, SHIKI_RETRY_CONFIG.maxDelay);
    };

    /**
     * Sleep helper function
     * @param {number} ms Milliseconds to sleep
     * @returns {Promise<void>}
     */
    const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    // ============================================
    // Multilingual Constants & Helpers
    // ============================================

    // Language code validation regex (ISO 639-1 format)
    const VALID_LANG_REGEX = /^[a-z]{2}(-[A-Z]{2})?$/;
    const MAX_LANGUAGES = 10;

    // Common languages list
    const COMMON_LANGUAGES = [
    	{ value: 'en', label: 'English (en)' },
    	{ value: 'ja', label: '日本語 (ja)' },
    	{ value: 'zh', label: '中文 (zh)' },
    	{ value: 'ko', label: '한국어 (ko)' },
    	{ value: 'es', label: 'Español (es)' },
    	{ value: 'fr', label: 'Français (fr)' },
    	{ value: 'de', label: 'Deutsch (de)' },
    	{ value: 'pt', label: 'Português (pt)' },
    	{ value: 'it', label: 'Italiano (it)' },
    	{ value: 'ru', label: 'Русский (ru)' },
    ];

    /**
     * Validate language code format
     * @param {string} code - Language code to validate
     * @returns {boolean}
     */
    const isValidLanguageCode = ( code ) => {
    	if ( ! code || typeof code !== 'string' ) return false;
    	// Normalize to lowercase for validation
    	const normalized = code.toLowerCase().trim();
    	return VALID_LANG_REGEX.test( normalized ) && normalized.length <= 5;
    };

    /**
     * Sanitize language code
     * @param {string} code - Language code to sanitize
     * @returns {string|null}
     */
    const sanitizeLangCode = ( code ) => {
    	if ( ! code ) return null;
    	const sanitized = code.toLowerCase().trim().slice( 0, 5 );
    	return isValidLanguageCode( sanitized ) ? sanitized : null;
    };

    // ============================================
    // Mermaid Detection Constants & Helpers
    // ============================================

    // Mermaid diagram type patterns (content must start with one of these)
    const MERMAID_START_PATTERNS = [
    	'graph', 'flowchart', 'sequenceDiagram', 'classDiagram',
    	'pie', 'gantt', 'stateDiagram', 'erDiagram', 'gitGraph', 'gitgraph',
    	'journey'
    ];

    // Mermaid inline patterns (content must include one of these)
    const MERMAID_INCLUDE_PATTERNS = [ 'graph TD', 'graph LR' ];

    // Patterns that indicate already-rendered SVG (not Mermaid source)
    const SVG_EXCLUSION_PATTERNS = [ '#gfmr-mermaid-', 'font-family:', '<svg', '</svg>' ];

    // Class-based Mermaid selectors (Phase 1 detection)
    const MERMAID_CLASS_SELECTORS = [
    	'pre code.language-mermaid',
    	'pre code[class*="language-mermaid"]',
    	'code.language-mermaid',
    	'.shiki .language-mermaid',
    	'[data-language="mermaid"]',
    	'pre[class*="language-mermaid"]'
    ];

    // Fallback selectors for content-based detection (Phase 2)
    // NOTE: Selectors are ordered by specificity. Avoid overly generic selectors like
    // bare 'code' to prevent performance issues when many inline code elements exist.
    const MERMAID_FALLBACK_SELECTORS = [
    	'pre.shiki code',
    	'.shiki code',
    	'pre code',
    	'.gfmr-markdown-rendered-preview pre code',
    	'.gfmr-markdown-rendered-preview code'
    ];

    /**
     * Check if debug mode is enabled via config or URL parameter
     * @returns {boolean} True if debug mode is enabled
     */
    const isDebugEnabled = () => {
    	return window.wpGfmConfig?.debug ||
    		window.location.search.includes( 'debug=true' ) ||
    		window.location.search.includes( 'gfmr-debug=1' ) ||
    		window.location.search.includes( 'debug=1' ) ||
    		false;
    };

    /**
     * Debug logger - outputs to console only when debug mode is enabled
     * @param {...any} args - Arguments to log
     */
    const logDebug = ( ...args ) => {
    	if ( isDebugEnabled() ) {
    		console.log( '[WP GFM Editor]', ...args );
    	}
    };

    /**
     * Debug warning logger - outputs to console only when debug mode is enabled
     * @param {...any} args - Arguments to log
     */
    const logDebugWarn = ( ...args ) => {
    	if ( isDebugEnabled() ) {
    		console.warn( '[WP GFM Editor]', ...args );
    	}
    };

    /**
     * Escape special characters in Markdown alt text
     *
     * @param {string} text - Text to escape
     * @returns {string} Escaped text
     */
    const escapeMarkdownAlt = ( text ) => {
    	if ( ! text ) {
    		return '';
    	}
    	return text.replace( /[\[\]\\]/g, '\\$&' );
    };

    /**
     * Encode URL for Markdown image syntax
     * Handles spaces and special characters
     *
     * @param {string} url - URL to encode
     * @returns {string} Encoded URL wrapped in angle brackets if needed
     */
    const encodeMarkdownUrl = ( url ) => {
    	if ( ! url ) {
    		return '';
    	}
    	// If URL contains spaces or parentheses, wrap in angle brackets
    	if ( /[\s()]/.test( url ) ) {
    		return `<${ url }>`;
    	}
    	return url;
    };

    /**
     * Validate image URL format
     * @param {string} url - URL to validate
     * @returns {boolean} - True if valid image URL
     */
    const isValidImageUrl = ( url ) => {
    	if ( ! url || typeof url !== 'string' ) {
    		return false;
    	}
    	try {
    		const parsedUrl = new URL( url );
    		return [ 'http:', 'https:' ].includes( parsedUrl.protocol );
    	} catch {
    		// Relative URL check (WordPress internal paths)
    		return url.startsWith( '/' ) && ! url.includes( '..' );
    	}
    };

    /**
     * Check if content is Mermaid diagram source (not rendered SVG)
     * @param {string} content - Content to check
     * @returns {boolean} True if content is Mermaid source
     */
    const isMermaidContent = ( content ) => {
    	if ( ! content ) return false;
    	const hasPattern = MERMAID_START_PATTERNS.some( p => content.startsWith( p ) ) ||
    	                   MERMAID_INCLUDE_PATTERNS.some( p => content.includes( p ) );
    	const isRenderedSvg = SVG_EXCLUSION_PATTERNS.some( e => content.includes( e ) );
    	return hasPattern && ! isRenderedSvg;
    };

    /**
     * Generate Mermaid container CSS style
     * @param {string} bgColor - Background color
     * @returns {string} CSS style string
     */
    const getMermaidContainerStyle = ( bgColor = 'transparent' ) =>
    	`text-align: center; margin: 20px 0; padding: 15px; background: ${bgColor}; border-radius: 6px; overflow-x: auto; border: none;`;

    /**
     * Build Mermaid error HTML template
     * @param {string} errorMessage - Error message
     * @param {string} code - Original Mermaid code
     * @returns {string} Error HTML
     */
    const buildMermaidErrorHTML = ( errorMessage, code ) => `
    	<div class="gfmr-mermaid-error-unified" style="color: #d1242f; background: #fff8f8; border: 1px solid #ffcdd2; border-radius: 6px; padding: 15px; margin: 10px 0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif; font-size: 14px; line-height: 1.5;">
    		<div style="font-weight: 600; margin-bottom: 8px;">🚨 Mermaid Rendering Error (editor)</div>
    		<div style="margin-bottom: 12px; font-size: 13px;">${errorMessage || 'Unknown error occurred'}</div>
    		<details style="margin-top: 10px;">
    			<summary style="cursor: pointer; font-size: 13px; margin-bottom: 8px;">View Original Code</summary>
    			<pre style="background: #f6f8fa; border: 1px solid #d1d9e0; border-radius: 4px; padding: 10px; margin: 5px 0; overflow-x: auto; font-size: 12px; font-family: 'SFMono-Regular', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, monospace; white-space: pre-wrap; word-wrap: break-word;">${code}</pre>
    		</details>
    	</div>
    `;

    /**
     * Helper function to get Shiki script URL
     * @returns {string} Shiki script URL
     */
    const getShikiScriptUrl = () => {
    	if (window.wpGfmBuildLocalAssetUrl) {
    		return window.wpGfmBuildLocalAssetUrl('assets/libs/shiki/shiki.min.js');
    	}

    	if (window.wpGfmConfig && window.wpGfmConfig.pluginUrl) {
    		return window.wpGfmConfig.pluginUrl + 'assets/libs/shiki/shiki.min.js';
    	}

    	// Fallback URL
    	return '/wp-content/plugins/markdown-renderer-for-github/assets/libs/shiki/shiki.min.js';
    };

    /**
     * Attempt to load Shiki script once
     * @returns {Promise<object|null>} Highlighter instance or null on failure
     */
    const attemptShikiLoad = async () => {
    	// Check if Shiki is already loaded
    	if (window.shiki) {
    		console.log('[WP GFM Editor] Shiki already loaded globally');
    		return window.shiki;
    	}

    	// Load Shiki locally (WordPress.org compliant)
    	const script = document.createElement('script');
    	script.src = getShikiScriptUrl();
    	script.async = true;

    	console.log('[WP GFM Editor] Loading Shiki locally:', script.src);

    	await new Promise((resolve, reject) => {
    		script.onload = resolve;
    		script.onerror = (error) => reject(new Error(`Script load failed: ${script.src}`));
    		document.head.appendChild(script);
    	});

    	// Access from window.shiki after local load
    	if (!window.shiki || !window.shiki.getHighlighter) {
    		throw new Error('Shiki global object not found after local asset load');
    	}

    	console.log('[WP GFM Editor] Shiki loaded successfully from local assets');
    	const { getHighlighter } = window.shiki;

    	// Create highlighter (new Shiki API)
    	const highlighter = await getHighlighter({
    		themes: ['github-dark', 'github-light'],
    		langs: ['javascript', 'typescript', 'python', 'ruby', 'go', 'rust', 'bash', 'css', 'html', 'json', 'yaml', 'xml', 'sql', 'php', 'java', 'csharp', 'cpp', 'diff']
    	});

    	return highlighter;
    };

    /**
     * Configure markdown-it with Shiki highlighter
     * @param {object} highlighter Shiki highlighter instance
     */
    const configureMarkdownItWithShiki = (highlighter) => {
    	md = md.set({
    		highlight: function(code, lang) {
    			try {
    				// Indent code blocks (no language specified) are treated as plain text
    				if (!lang || lang.trim() === '') {
    					const escapedCode = code
    						.replace(/&/g, '&amp;')
    						.replace(/</g, '&lt;')
    						.replace(/>/g, '&gt;');
    					return `<pre><code>${escapedCode}</code></pre>`;
    				}

    				// Normalize language name (only when language is specified)
    				const normalizedLang = lang.toLowerCase().trim();

    				// Language alias support
    				const langAliases = {
    					'js': 'javascript',
    					'ts': 'typescript',
    					'py': 'python',
    					'rb': 'ruby',
    					'sh': 'bash',
    					'shell': 'bash',
    					'yml': 'yaml',
    					'c++': 'cpp',
    					'c#': 'csharp',
    					'cs': 'csharp',
    					'patch': 'diff'
    				};

    				const finalLang = langAliases[normalizedLang] || normalizedLang;

    				// Skip chart blocks - handled by gfmr-charts.js
    				if (finalLang === 'chart' || finalLang === 'chart-pro') {
    					const escapedCode = code
    						.replace(/&/g, '&amp;')
    						.replace(/</g, '&lt;')
    						.replace(/>/g, '&gt;');
    					return `<pre><code class="language-${finalLang}">${escapedCode}</code></pre>`;
    				}

    				// Check if language is supported
    				const supportedLangs = highlighter.getLoadedLanguages();
    				// Special handling for Mermaid (highlight as plain text)
    				const langToUse = finalLang === 'mermaid' ? 'plaintext' :
    					(supportedLangs.includes(finalLang) ? finalLang : 'plaintext');

    				// Get theme from plugin settings (consistent with frontend)
    				let theme = window.wpGfmConfig?.theme?.shiki_theme ??
    					(window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'github-dark' : 'github-light');
    				if (theme === 'auto') {
    					const isDark = window.matchMedia &&
    						window.matchMedia('(prefers-color-scheme: dark)').matches;
    					theme = isDark ? 'github-dark' : 'github-light';
    				}

    				return highlighter.codeToHtml(code, {
    					lang: langToUse,
    					theme: theme
    				});
    			} catch (error) {
    				console.warn('[WP GFM Editor] Highlighting failed:', error);

    				// Fallback
    				const escapedCode = code
    					.replace(/&/g, '&amp;')
    					.replace(/</g, '&lt;')
    					.replace(/>/g, '&gt;');

    				return `<pre><code class="language-${lang || 'plaintext'}">${escapedCode}</code></pre>`;
    			}
    		}
    	});
    };

    /**
     * Shiki loading function (for editor) - with retry logic and exponential backoff
     * @returns {Promise<object|null>} Highlighter instance or null on failure
     */
    const loadShikiForEditor = async () => {
    	if (editorShikiHighlighter) {
    		return editorShikiHighlighter;
    	}

    	if (shikiLoadPromise) {
    		return shikiLoadPromise;
    	}

    	shikiLoadStatus = 'loading';

    	shikiLoadPromise = (async () => {
    		while (shikiRetryCount <= SHIKI_RETRY_CONFIG.maxRetries) {
    			try {
    				const highlighter = await attemptShikiLoad();

    				if (highlighter) {
    					editorShikiHighlighter = highlighter;
    					configureMarkdownItWithShiki(highlighter);
    					shikiLoadStatus = 'loaded';
    					shikiRetryCount = 0; // Reset for future use
    					return editorShikiHighlighter;
    				}
    			} catch (error) {
    				const isLastAttempt = shikiRetryCount >= SHIKI_RETRY_CONFIG.maxRetries;

    				if (isLastAttempt) {
    					console.error(`[WP GFM Editor] Failed to load Shiki after ${shikiRetryCount + 1} attempts:`, error);
    					console.log('[WP GFM Editor] Available globals:', {
    						wpGfmBuildLocalAssetUrl: typeof window.wpGfmBuildLocalAssetUrl,
    						wpGfmConfig: typeof window.wpGfmConfig,
    						wpGfmConfigContent: window.wpGfmConfig
    					});
    					shikiLoadStatus = 'failed';
    					shikiLoadPromise = null; // Allow future retry attempts
    					return null;
    				}

    				// Calculate backoff delay and retry
    				const delay = calculateBackoffDelay(shikiRetryCount);
    				console.warn(
    					`[WP GFM Editor] Shiki load attempt ${shikiRetryCount + 1} failed, retrying in ${delay}ms...`,
    					error.message
    				);

    				shikiRetryCount++;
    				await sleep(delay);
    			}
    		}

    		return null;
    	})();

    	return shikiLoadPromise;
    };

    /**
     * Get current Shiki load status
     * @returns {string} Current status: 'idle' | 'loading' | 'loaded' | 'failed'
     */
    const getShikiLoadStatus = () => shikiLoadStatus;

    /**
     * Reset Shiki loader state (useful for manual retry)
     */
    const resetShikiLoader = () => {
    	shikiLoadPromise = null;
    	shikiRetryCount = 0;
    	shikiLoadStatus = 'idle';
    	editorShikiHighlighter = null;
    };

    /**
     * Markdown block editor component
     */
    export default function Edit( { attributes, setAttributes } ) {
    	const {
    		content,
    		html,
    		mermaidBgColor,
    		showFrontmatter = false,
    		frontmatterData = {},
    		// Multilingual attributes
    		languages = {},
    		defaultLanguage = 'en',
    		availableLanguages = [],
    		showLanguageSwitcher = true,
    	} = attributes;

    	const [ isPreview, setIsPreview ] = useState( false );
    	const [ renderedHtml, setRenderedHtml ] = useState( html || '' );
    	const [ processedHtml, setProcessedHtml ] = useState( null );
    	const [ shikiLoaded, setShikiLoaded ] = useState( false );
    	const textareaRef = useRef( null );
    	const cursorPositionRef = useRef( null );
    	const previewRef = useRef( null );
    	const processMermaidBlocksRef = useRef( null );
    	const isMermaidProcessing = useRef( false );
    	const lastRenderedHtmlRef = useRef( '' );

    	// Ref to track latest content (avoiding stale closure in handleImageInsert)
    	const contentRef = useRef( content );
    	useEffect( () => {
    		contentRef.current = content;
    	}, [ content ] );

    	// Multilingual state
    	const [ currentEditingLang, setCurrentEditingLang ] = useState( defaultLanguage );
    	const [ isAddLanguageModalOpen, setIsAddLanguageModalOpen ] = useState( false );

    	// Check if multilingual mode is active (more than one language or has languages data)
    	const isMultilingualMode = availableLanguages.length > 0 || Object.keys( languages ).length > 0;

    	// 多言語データの整合性を保証
    	useEffect( () => {
    		const langKeys = Object.keys( languages );

    		// languagesオブジェクトがあるが、availableLanguagesが空または不一致の場合は修復
    		if ( langKeys.length > 0 ) {
    			const needsUpdate = availableLanguages.length === 0 ||
    				! langKeys.every( k => availableLanguages.includes( k ) );

    			if ( needsUpdate ) {
    				const newDefaultLang = langKeys.includes( defaultLanguage )
    					? defaultLanguage
    					: langKeys[ 0 ];

    				setAttributes( {
    					availableLanguages: langKeys,
    					defaultLanguage: newDefaultLang,
    					showLanguageSwitcher: langKeys.length > 1,
    				} );

    				setCurrentEditingLang( newDefaultLang );
    			}
    		}
    	}, [ languages ] );

    	// Get current content based on mode
    	const getCurrentContent = useCallback( () => {
    		if ( isMultilingualMode && languages[ currentEditingLang ] ) {
    			return languages[ currentEditingLang ].content || '';
    		}
    		return content || '';
    	}, [ isMultilingualMode, languages, currentEditingLang, content ] );

    	// Get current HTML based on mode
    	const getCurrentHtml = useCallback( () => {
    		if ( isMultilingualMode && languages[ currentEditingLang ] ) {
    			return languages[ currentEditingLang ].html || '';
    		}
    		return html || '';
    	}, [ isMultilingualMode, languages, currentEditingLang, html ] );

    	// Feature flags from PHP (for Pro version migration in the future)
    	const isImageInsertEnabled = window.wpGfmConfig?.features?.imageInsert ?? true;

    	/**
    	 * Update content and trigger re-render (unified for both modes)
    	 */
    	const updateContentWithRender = useCallback( async ( newContent ) => {
    		if ( isMultilingualMode ) {
    			const updatedLanguages = {
    				...languages,
    				[ currentEditingLang ]: {
    					...( languages[ currentEditingLang ] || {} ),
    					content: newContent,
    				},
    			};
    			setAttributes( { languages: updatedLanguages } );
    			try {
    				await renderMarkdownForLanguage( newContent, currentEditingLang, updatedLanguages );
    			} catch ( error ) {
    				console.warn( '[updateContentWithRender] Render failed:', error.message );
    			}
    		} else {
    			setAttributes( { content: newContent } );
    			try {
    				await renderMarkdown( newContent );
    			} catch ( error ) {
    				console.warn( '[updateContentWithRender] Render failed:', error.message );
    			}
    		}
    	}, [
    		isMultilingualMode, languages, currentEditingLang,
    		setAttributes, renderMarkdown, renderMarkdownForLanguage
    	] );

    	/**
    	 * Handle image insertion from media library
    	 *
    	 * @param {Object} media - WordPress media object
    	 */
    	const handleImageInsert = useCallback( async ( media ) => {
    		// Handle array case (multiple selection) - use first item
    		const selectedMedia = Array.isArray( media ) ? media[ 0 ] : media;

    		if ( ! selectedMedia ) {
    			console.warn( '[handleImageInsert] No media selected' );
    			return;
    		}

    		// Prefer source_url over url for reliability
    		const imageUrl = selectedMedia?.source_url || selectedMedia?.url;
    		if ( ! imageUrl || ! isValidImageUrl( imageUrl ) ) {
    			console.warn( '[handleImageInsert] Invalid or missing URL. Media ID:', selectedMedia?.id );
    			return;
    		}

    		// Build alt text: respect empty string as intentional empty alt
    		let altText = '';
    		if ( selectedMedia.alt !== '' && selectedMedia.alt != null ) {
    			altText = selectedMedia.alt;
    		} else if ( selectedMedia.alt !== '' && selectedMedia.title ) {
    			altText = selectedMedia.title;
    		}
    		// Note: If both alt and title are empty/undefined, altText remains ''

    		// Escape special characters
    		const escapedAlt = escapeMarkdownAlt( altText );
    		const encodedUrl = encodeMarkdownUrl( imageUrl );
    		const imageMarkdown = `![${ escapedAlt }](${ encodedUrl })`;

    		// If in preview mode, switch to edit mode first
    		if ( isPreview ) {
    			setIsPreview( false );
    		}

    		// Get current content based on mode
    		const currentContent = getCurrentContent();
    		const textarea = textareaRef.current;
    		const saved = cursorPositionRef.current;

    		// Determine insertion point and build new content
    		let newContent;
    		const separator = currentContent && currentContent.length > 0 ? '\n' : '';

    		if ( saved && saved.start >= 0 ) {
    			// Insert at saved cursor position
    			newContent =
    				currentContent.substring( 0, saved.start ) +
    				imageMarkdown +
    				currentContent.substring( saved.end );
    		} else {
    			// Append to end
    			newContent = currentContent + separator + imageMarkdown;
    		}

    		// Update content (unified)
    		await updateContentWithRender( newContent );

    		// Clear saved cursor position
    		cursorPositionRef.current = null;

    		// Focus and restore cursor position if possible
    		setTimeout( () => {
    			if ( textarea ) {
    				// Focus without scrolling (fallback for older browsers)
    				try {
    					textarea.focus( { preventScroll: true } );
    				} catch ( e ) {
    					console.warn( 'preventScroll not supported, using fallback:', e );
    					textarea.focus();
    				}

    				// Set cursor position
    				const newPos = saved && saved.start >= 0
    					? saved.start + imageMarkdown.length
    					: newContent.length;
    				textarea.setSelectionRange( newPos, newPos );
    			}
    		}, 0 );
    	}, [
    		setAttributes,
    		isPreview,
    		setIsPreview,
    		getCurrentContent,
    		updateContentWithRender
    	] );

    	// Compute theme CSS class for preview container (consistent with frontend gfmr-main.js)
    	const themeClass = useMemo( () => {
    		let theme = window.wpGfmConfig?.theme?.shiki_theme ??
    			(window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'github-dark' : 'github-light');
    		if ( theme === 'auto' ) {
    			const isDark = window.matchMedia &&
    				window.matchMedia( '(prefers-color-scheme: dark)' ).matches;
    			theme = isDark ? 'github-dark' : 'github-light';
    		}
    		return theme === 'github-dark' ? 'gfmr-dark' : 'gfmr-light';
    	}, [] );

    	// Initialize showFrontmatter from global settings for new blocks
    	useEffect( () => {
    		// Only apply global setting if showFrontmatter has never been set (undefined in saved data)
    		// Check if this is a new block (no content yet) and showFrontmatter is default false
    		if ( ! content && showFrontmatter === false ) {
    			const globalShowHeader = window.wpGfmConfig?.frontmatter?.showHeader ?? false;
    			if ( globalShowHeader ) {
    				setAttributes( { showFrontmatter: true } );
    			}
    		}
    	}, [] ); // Run only on mount

    	// Dynamically load Mermaid
    	// Note: Empty dependency array to stabilize function reference across renders.
    	// Uses window.mermaid as the source of truth instead of React state.
    	const loadMermaid = useCallback( async () => {
    		// Check window.mermaid directly for stability (avoids dependency chain issues)
    		if ( window.mermaid ) {
    			return true;
    		}

    		try {
    			// Load Mermaid.js locally (WordPress.org distribution compliant)
    			const script = document.createElement( 'script' );
    			script.src = window.wpGfmBuildAssetUrl ?
    				window.wpGfmBuildAssetUrl('assets/libs/mermaid/mermaid.min.js') :
    				(( window.wpGfmConfig?.pluginUrl || '' ) + '/assets/libs/mermaid/mermaid.min.js');
    			script.async = true;

    			await new Promise( ( resolve, reject ) => {
    				script.onload = resolve;
    				script.onerror = reject;
    				document.head.appendChild( script );
    			} );

    			if ( window.mermaid ) {
    				// Use unified initialization function (ensures frontend consistency)
    				if ( window.wpGfmInitializeMermaidUnified ) {
    					const initResult = await window.wpGfmInitializeMermaidUnified( true );
    					if ( initResult ) {
    						return true;
    					}
    				}

    				// Fallback: Full configuration matching frontend (gfmr-main.js)
    				window.mermaid.initialize( {
    					startOnLoad: false,
    					theme: 'default',
    					securityLevel: 'loose',
    					fontFamily: 'monospace',
    					themeVariables: {
    						background: 'transparent'
    					},
    					flowchart: {
    						useMaxWidth: false,
    						htmlLabels: true,
    						curve: 'basis',
    					},
    					sequence: {
    						useMaxWidth: true,
    						height: 65,
    					},
    					class: {
    						useMaxWidth: true,
    					},
    					state: {
    						useMaxWidth: false,
    					},
    					er: {
    						useMaxWidth: false,
    					},
    					gantt: {
    						useMaxWidth: true,
    					},
    					gitGraph: {
    						useMaxWidth: false,
    						mainLineWidth: 2,
    						mainBranchOrder: 0,
    					},
    				} );
    				return true;
    			}
    		} catch ( error ) {
    			console.error( '[WP GFM Editor] Failed to load Mermaid:', error );
    		}
    		return false;
    	}, [] );  // Empty dependency array for stable reference

    	/**
    	 * Extract plain text from Shiki-highlighted code for Chart.js
    	 * Removes span tags and decodes HTML entities
    	 */
    	const extractChartCodeFromShiki = ( element ) => {
    		// Clone element and replace all spans with text nodes
    		const clone = element.cloneNode( true );
    		const spans = clone.querySelectorAll( 'span' );
    		spans.forEach( ( span ) => {
    			const textNode = document.createTextNode( span.textContent );
    			span.parentNode.replaceChild( textNode, span );
    		} );

    		let text = clone.textContent || clone.innerText || '';

    		// Decode HTML entities
    		text = text
    			.replace( /&lt;/g, '<' )
    			.replace( /&gt;/g, '>' )
    			.replace( /&amp;/g, '&' )
    			.replace( /&quot;/g, '"' )
    			.replace( /&#39;/g, "'" )
    			.replace( /&nbsp;/g, ' ' );

    		return text.trim();
    	};

    	/**
    	 * Process Chart.js blocks in editor preview
    	 * Converts rendered charts to images for React state preservation
    	 */
    	const processChartBlocks = useCallback( async ( container ) => {
    		if ( ! container ) return 0;

    		// Find chart code blocks - only target elements with language-chart class
    		// Chart blocks are NOT processed by Shiki, so they won't have pre.shiki wrapper
    		const chartBlocks = container.querySelectorAll(
    			'code.language-chart:not([data-gfmr-chart-processed]), ' +
    			'code.language-chart-pro:not([data-gfmr-chart-processed])'
    		);

    		if ( chartBlocks.length === 0 ) {
    			return 0;
    		}

    		logDebug( `[Chart.js] Found ${ chartBlocks.length } chart blocks` );

    		// Load Chart.js library if not available
    		if ( ! window.Chart ) {
    			try {
    				const pluginUrl = window.wpGfmConfig?.pluginUrl || '/wp-content/plugins/markdown-renderer-for-github/';
    				await new Promise( ( resolve, reject ) => {
    					const script = document.createElement( 'script' );
    					script.src = pluginUrl + 'assets/libs/chartjs/chart.umd.min.js';
    					script.onload = resolve;
    					script.onerror = reject;
    					document.head.appendChild( script );
    				} );
    				logDebug( '[Chart.js] Library loaded' );
    			} catch ( error ) {
    				console.warn( '[WP GFM Editor] Failed to load Chart.js:', error );
    				return 0;
    			}
    		}

    		// Theme helper (charts always use light mode for consistency)
    		const getChartTheme = () => {
    			// Charts always use light theme colors
    			const colors = { text: '#24292f', grid: '#d0d7de', border: '#d0d7de', bg: '#ffffff' };
    			return { isDark: false, colors };
    		};

    		// Deep merge helper - preserves user-specified values
    		const deepMerge = ( target, source ) => {
    			const result = { ...target };
    			for ( const key in source ) {
    				if ( source[ key ] && typeof source[ key ] === 'object' && ! Array.isArray( source[ key ] ) ) {
    					result[ key ] = deepMerge( target[ key ] || {}, source[ key ] );
    				} else if ( target[ key ] === undefined ) {
    					// Only apply source value if target doesn't have it
    					result[ key ] = source[ key ];
    				}
    			}
    			return result;
    		};

    		// Get theme info for all charts
    		const themeInfo = getChartTheme();

    		// Apply to Chart.js defaults (for any charts that don't get explicit options)
    		window.Chart.defaults.color = themeInfo.colors.text;
    		window.Chart.defaults.borderColor = themeInfo.colors.border;
    		if ( window.Chart.defaults.scale ) {
    			window.Chart.defaults.scale.grid = window.Chart.defaults.scale.grid || {};
    			window.Chart.defaults.scale.grid.color = themeInfo.colors.grid;
    			window.Chart.defaults.scale.ticks = window.Chart.defaults.scale.ticks || {};
    			window.Chart.defaults.scale.ticks.color = themeInfo.colors.text;
    		}
    		if ( window.Chart.defaults.plugins?.legend?.labels ) {
    			window.Chart.defaults.plugins.legend.labels.color = themeInfo.colors.text;
    		}
    		if ( window.Chart.defaults.plugins?.title ) {
    			window.Chart.defaults.plugins.title.color = themeInfo.colors.text;
    		}

    		// Process each chart block and convert to image
    		let processedCount = 0;
    		for ( const block of chartBlocks ) {
    			try {
    				block.setAttribute( 'data-gfmr-chart-processed', 'true' );

    				// Extract plain text from potentially Shiki-highlighted code
    				const content = extractChartCodeFromShiki( block );
    				logDebug( '[Chart.js] Extracted content:', content.substring( 0, 100 ) );

    				const config = JSON.parse( content );

    				// Theme options for chart (applied only if not user-specified)
    				const chartThemeOptions = {
    					responsive: true,
    					maintainAspectRatio: true,
    					animation: false, // Editor-specific: render immediately
    					color: themeInfo.colors.text,
    					borderColor: themeInfo.colors.border,
    					scales: {
    						x: {
    							grid: { color: themeInfo.colors.grid },
    							ticks: { color: themeInfo.colors.text }
    						},
    						y: {
    							grid: { color: themeInfo.colors.grid },
    							ticks: { color: themeInfo.colors.text }
    						}
    					},
    					plugins: {
    						legend: { labels: { color: themeInfo.colors.text } },
    						title: { color: themeInfo.colors.text },
    						tooltip: {
    							backgroundColor: 'rgba(255, 255, 255, 0.95)',
    							titleColor: themeInfo.colors.text,
    							bodyColor: themeInfo.colors.text,
    							borderColor: themeInfo.colors.border,
    							borderWidth: 1
    						}
    					}
    				};

    				// Merge: user options override theme options
    				config.options = deepMerge( chartThemeOptions, config.options || {} );

    				// Create temporary off-screen canvas for rendering
    				const tempContainer = document.createElement( 'div' );
    				tempContainer.style.width = '600px';
    				tempContainer.style.height = '400px';
    				tempContainer.style.position = 'absolute';
    				tempContainer.style.left = '-9999px';
    				document.body.appendChild( tempContainer );

    				const canvas = document.createElement( 'canvas' );
    				tempContainer.appendChild( canvas );

    				// Render chart with Chart.js
    				const chart = new window.Chart( canvas.getContext( '2d' ), config );

    				// Convert to image (similar to Mermaid's approach)
    				const imageDataUrl = chart.toBase64Image( 'image/png', 1.0 );

    				// Clean up chart and temporary DOM
    				chart.destroy();
    				document.body.removeChild( tempContainer );

    				// Create image element to replace code block (light theme fixed)
    				const imgContainer = document.createElement( 'div' );
    				imgContainer.className = 'gfmr-chart-container gfmr-chart-image';
    				imgContainer.innerHTML = `<img src="${ imageDataUrl }" alt="Chart" style="max-width: 100%; height: auto;" />`;

    				// Replace pre element with image
    				const targetElement = block.closest( 'pre' ) || block.parentElement;
    				if ( targetElement?.parentNode ) {
    					targetElement.parentNode.replaceChild( imgContainer, targetElement );
    				}

    				processedCount++;
    			} catch ( error ) {
    				console.warn( '[WP GFM Editor] Chart render error:', error );
    				// Show error message (this will be preserved in processedHtml)
    				const errorDiv = document.createElement( 'div' );
    				errorDiv.className = 'gfmr-chart-error';
    				errorDiv.innerHTML = `<div class="gfmr-chart-error-content"><strong>Chart Error:</strong> ${ error.message }</div>`;
    				const targetElement = block.closest( 'pre' ) || block.parentElement;
    				if ( targetElement?.parentNode ) {
    					targetElement.parentNode.replaceChild( errorDiv, targetElement );
    				}
    				processedCount++; // Count errors too (DOM was modified)
    			}
    		}

    		return processedCount;
    	}, [] );

    	// Extract plain text from Shiki-highlighted code, preserving newlines
    	// Uses same approach as frontend extractPlainTextFromHighlighted for consistency
    	const extractMermaidCodeFromShiki = ( element ) => {
    		// Clone element and replace all spans with text nodes (preserves newlines in HTML structure)
    		const clone = element.cloneNode( true );
    		const spans = clone.querySelectorAll( 'span' );
    		spans.forEach( ( span ) => {
    			const textNode = document.createTextNode( span.textContent );
    			span.parentNode.replaceChild( textNode, span );
    		} );

    		let text = clone.textContent || clone.innerText || '';

    		// Decode HTML entities (consistent with front-end)
    		text = text
    			.replace( /&lt;/g, '<' )
    			.replace( /&gt;/g, '>' )
    			.replace( /&amp;/g, '&' )
    			.replace( /&quot;/g, '"' )
    			.replace( /&#39;/g, "'" );

    		return text;
    	};

    	// Unified Mermaid processing function for block editor (alternative to frontend version)
    	const processMermaidBlocksLocal = useCallback( async ( container, context = 'editor', bgColor = null ) => {
    		logDebug( 'processMermaidBlocksLocal called' );
    		logDebug( 'Container HTML preview:', container?.innerHTML?.substring( 0, 200 ) );

    		if ( ! container ) {
    			return 0;
    		}

    		// Check if Mermaid is available
    		const mermaidAvailable = await loadMermaid();
    		if ( ! mermaidAvailable ) {
    			logDebug( 'Mermaid not available' );
    			return 0;
    		}
    		logDebug( 'Mermaid is available' );

    		// Phase 1: Class-based detection
    		logDebug( 'Phase 1: Starting class-based detection' );
    		let mermaidBlocks = [];
    		for ( const selector of MERMAID_CLASS_SELECTORS ) {
    			const blocks = container.querySelectorAll( selector );
    			if ( blocks.length > 0 ) {
    				mermaidBlocks = Array.from( blocks );
    				logDebug( `Phase 1: Found ${ blocks.length } blocks with selector "${ selector }"` );
    				break;
    			}
    		}
    		logDebug( `Phase 1 result: ${ mermaidBlocks.length } blocks` );

    		// Phase 2: Content-based detection (when class-based detection finds nothing)
    		if ( mermaidBlocks.length === 0 ) {
    			logDebug( 'Phase 2: Starting content-based detection' );
    			for ( const selector of MERMAID_FALLBACK_SELECTORS ) {
    				const codeElements = container.querySelectorAll( selector );
    				logDebug( `Selector "${ selector }" found ${ codeElements.length } elements` );
    				for ( const codeElement of codeElements ) {
    					const cleanContent = ( codeElement.textContent || '' ).trim().replace( /\s+/g, ' ' );
    					logDebug( 'Content preview:', cleanContent.substring( 0, 60 ) );
    					if ( isMermaidContent( cleanContent ) ) {
    						logDebug( '✅ Mermaid content detected!' );
    						mermaidBlocks.push( codeElement );
    					}
    				}
    				if ( mermaidBlocks.length > 0 ) break;
    			}
    			logDebug( `Phase 2 result: ${ mermaidBlocks.length } blocks found` );
    		}

    		if ( mermaidBlocks.length === 0 ) {
    			return 0;
    		}

    		let processedCount = 0;
    		for ( let index = 0; index < mermaidBlocks.length; index++ ) {
    			const codeBlock = mermaidBlocks[ index ];

    			try {
    				const mermaidCode = extractMermaidCodeFromShiki( codeBlock );
    				const preElement = codeBlock.parentElement;

    				if ( ! preElement || ! mermaidCode?.trim() ) {
    					continue;
    				}

    				// Create Mermaid container with unified container style
    				const mermaidContainer = document.createElement( 'div' );
    				mermaidContainer.className = 'gfmr-mermaid-container';
    				mermaidContainer.style.cssText = getMermaidContainerStyle( bgColor || 'transparent' );

    				const mermaidId = `gfmr-editor-mermaid-${Date.now()}-${index}`;
    				const mermaidDiv = document.createElement( 'div' );
    				mermaidDiv.id = mermaidId;
    				mermaidDiv.className = 'gfmr-mermaid';

    				mermaidContainer.appendChild( mermaidDiv );
    				preElement.parentNode.replaceChild( mermaidContainer, preElement );

    				// Unified rendering process (local version)
    				try {
    					const renderResult = await window.mermaid.render( mermaidId + '-svg', mermaidCode.trim() );

    					let svgContent = '';
    					if ( renderResult && typeof renderResult === 'object' && renderResult.svg ) {
    						// Mermaid v10+ new API
    						svgContent = renderResult.svg;
    					} else if ( typeof renderResult === 'string' ) {
    						// Old API or string response
    						svgContent = renderResult;
    					} else {
    						throw new Error( 'Invalid render result format' );
    					}

    					// Insert SVG
    					mermaidDiv.innerHTML = svgContent;

    					// SVG optimization is handled via CSS (.gfmr-mermaid svg in mermaid-styles.css)
    					// which applies: display: block, margin: 0 auto, max-width: 100%, height: auto
    					// This separation of concerns keeps styling in CSS rather than JS.

    					mermaidDiv.setAttribute( 'data-mermaid-rendered', 'true' );
    					mermaidDiv.setAttribute( 'data-mermaid-context', context );
    					processedCount++;

    				} catch ( renderError ) {
    					console.error( `[WP GFM Editor] ❌ Render error for block ${index}:`, renderError );
    					mermaidDiv.innerHTML = buildMermaidErrorHTML( renderError.message, mermaidCode );
    				}

    			} catch ( error ) {
    				console.error( `[WP GFM Editor] ❌ Processing error for block ${index}:`, error );
    			}
    		}

    		return processedCount;
    	}, [ loadMermaid, mermaidBgColor ] );

    	// Mermaid processing function (unified version: ensures complete consistency between preview and content display)
    	const processMermaidBlocks = useCallback( async ( container, bgColor = null ) => {
    		logDebug( 'processMermaidBlocks called, container:', container?.tagName, container?.className );

    		if ( ! container ) {
    			logDebugWarn( 'No container provided for Mermaid processing' );
    			return;
    		}

    		// Use unified Mermaid block processing function if available
    		if ( window.wpGfmProcessMermaidBlocksUnified ) {
    			logDebug( 'Using unified Mermaid processing for editor' );

    			try {
    				// Verify Mermaid loading
    				const loaded = await loadMermaid();

    				if ( ! loaded ) {
    					logDebugWarn( 'Mermaid not available, skipping processing' );
    					return;
    				}

    				// Execute unified processing
    				const processedCount = await window.wpGfmProcessMermaidBlocksUnified( container, 'editor' );

    				logDebug( `✅ Unified Mermaid processing completed: ${ processedCount } blocks processed` );

    				return processedCount;
    			} catch ( error ) {
    				console.error( '[WP GFM Editor] Unified Mermaid processing failed:', error );
    				// Continue with fallback processing
    			}
    		}

    		// Local processing: block editor-specific unified processing
    		return processMermaidBlocksLocal( container, 'editor', bgColor );
    	}, [ loadMermaid, mermaidBgColor, processMermaidBlocksLocal ] );

    	// Mermaid error display (unified version: ensures complete consistency between preview and content display)
    	const showMermaidError = ( container, error, code, index ) => {
    		// Use unified error handler if available
    		if ( window.showEnhancedMermaidError ) {
    			window.showEnhancedMermaidError( container, error, code, index );
    			return;
    		}

    		// Fallback: emulate unified error display using helper
    		container.innerHTML = buildMermaidErrorHTML( error.message, code );
    	};

    	// Keep processMermaidBlocksRef updated with latest function reference
    	// This allows useEffect to use stable dependency array while accessing latest function
    	useEffect( () => {
    		processMermaidBlocksRef.current = processMermaidBlocks;
    	}, [ processMermaidBlocks ] );

    	// Shiki initialization (on component mount)
    	useEffect( () => {
    		if ( ! shikiLoaded ) {
    			loadShikiForEditor().then( ( highlighter ) => {
    				if ( highlighter ) {
    					setShikiLoaded( true );
    					console.log( '[WP GFM Editor] Shiki initialized for editor' );

    					// Re-render existing content after Shiki loading completes
    					if ( content ) {
    						renderMarkdown( content );
    					}
    				}
    			} ).catch( ( error ) => {
    				console.warn( '[WP GFM Editor] Shiki initialization failed:', error );
    			} );
    		}
    	}, [] );

    	// Initial rendering
    	useEffect( () => {
    		if ( content ) {
    			renderMarkdown( content );
    		}
    	}, [] );

    	// Re-render when showFrontmatter changes
    	useEffect( () => {
    		if ( content ) {
    			renderMarkdown( content );
    		}
    	}, [ showFrontmatter ] );

    	/**
    	 * Apply diff highlighting classes to HTML string
    	 * Adds CSS classes to lines based on their diff prefix (+, -, @@)
    	 *
    	 * @param {string} html - HTML string containing Shiki-highlighted code blocks
    	 * @return {string} - Modified HTML with diff classes applied
    	 */
    	const applyDiffHighlightingToHtml = ( html ) => {
    		// Skip if no Shiki code blocks
    		if ( ! html || ! html.includes( 'class="shiki"' ) ) {
    			return html;
    		}

    		const tempDiv = document.createElement( 'div' );
    		tempDiv.innerHTML = html;

    		const preElements = tempDiv.querySelectorAll( 'pre.shiki' );

    		preElements.forEach( ( pre ) => {
    			const codeElement = pre.querySelector( 'code' );
    			if ( ! codeElement ) {
    				return;
    			}

    			const lines = codeElement.querySelectorAll( '.line' );

    			let hasDiff = false;

    			lines.forEach( ( line ) => {
    			const text = ( line.textContent || '' ).trim();

    			// Remove empty lines (including whitespace-only lines)
    			if ( ! text ) {
    				line.remove();
    				return;
    			}

    			// Skip file header lines (+++, ---, diff --git, index)
    			if ( text.startsWith( '+' ) && ! text.startsWith( '+++' ) ) {
    				line.classList.add( 'diff', 'add' );
    				hasDiff = true;
    			} else if ( text.startsWith( '-' ) && ! text.startsWith( '---' ) ) {
    				line.classList.add( 'diff', 'remove' );
    				hasDiff = true;
    			} else if ( text.startsWith( '@@' ) ) {
    				line.classList.add( 'diff', 'hunk' );
    				hasDiff = true;
    			}
    		} );

    			if ( hasDiff ) {
    				pre.classList.add( 'has-diff' );
    			}
    		} );

    		return tempDiv.innerHTML;
    	};

    	// Markdown rendering (indent block preprocessing + Shiki integration support)
    	const renderMarkdown = useCallback( async ( markdownContent ) => {
    		if ( ! markdownContent ) {
    			setRenderedHtml( '' );
    			setAttributes( { html: '', shikiTheme: '', frontmatterData: {} } );
    			setProcessedHtml( null );
    			return;
    		}

    		try {
    			// Parse frontmatter before rendering
    			const { frontmatter, body } = parseFrontMatter( markdownContent );

    			// Update frontmatter attributes
    			setAttributes( { frontmatterData: frontmatter } );

    			// Wait for Shiki to load if not loaded yet
    			if ( ! shikiLoaded && ! editorShikiHighlighter ) {
    				await loadShikiForEditor();
    				setShikiLoaded( true );
    			}

    			// Render body only (without frontmatter section)
    			let bodyHtml;
    			if ( window.wpGfmRenderWithIndentPreprocessing ) {
    				console.log( '[WP GFM Editor] Using indent block preprocessing for editor' );
    				bodyHtml = window.wpGfmRenderWithIndentPreprocessing( body, md );
    			} else {
    				console.warn( '[WP GFM Editor] Indent preprocessor not available, using fallback' );
    				bodyHtml = md.render( body );
    			}

    			// Generate frontmatter header HTML
    			const fmHtml = showFrontmatter ? renderFrontmatterHeader( frontmatter ) : '';

    			// Combine frontmatter header and body
    			let html = fmHtml + bodyHtml;

    			// Apply diff highlighting to code blocks
    			html = applyDiffHighlightingToHtml( html );

    			// Get the current Shiki theme used for rendering
    			let currentShikiTheme = window.wpGfmConfig?.theme?.shiki_theme ??
    				(window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'github-dark' : 'github-light');
    			if ( currentShikiTheme === 'auto' ) {
    				const isDark = window.matchMedia &&
    					window.matchMedia( '(prefers-color-scheme: dark)' ).matches;
    				currentShikiTheme = isDark ? 'github-dark' : 'github-light';
    			}

    			setRenderedHtml( html );
    			setAttributes( { html, shikiTheme: currentShikiTheme } );

    			// Only reset processedHtml if HTML actually changed
    			// This prevents losing Mermaid processing results on unrelated re-renders
    			if ( lastRenderedHtmlRef.current !== html ) {
    				setProcessedHtml( null );
    				lastRenderedHtmlRef.current = html;
    			}

    			// Note: Mermaid processing is handled by useEffect on renderedHtml change
    			// No need for additional setTimeout here as it causes duplicate processing
    		} catch ( error ) {
    			console.error( '[WP GFM Renderer] Rendering error:', error );
    			setRenderedHtml( '<p>An error occurred while rendering Markdown</p>' );
    			setProcessedHtml( null );
    		}
    	}, [ shikiLoaded, showFrontmatter, setRenderedHtml, setProcessedHtml ] );

    	// Mermaid processing on preview mode switch
    	// Note: processMermaidBlocks is accessed via ref to avoid dependency chain issues
    	useEffect( () => {
    		let cleanup = false;
    		let timeoutId = null;

    		logDebug( '🔍 useEffect triggered:', { isPreview, renderedHtml: !!renderedHtml, previewRefExists: !!previewRef.current } );

    		if ( isPreview && renderedHtml && previewRef.current ) {
    			logDebug( '✅ All conditions met for Mermaid processing' );

    			// Execute Mermaid processing when switched to preview mode
    			// Wait more reliably for DOM update (wait for Shiki processing completion)
    			timeoutId = setTimeout( async () => {
    				// Skip if cleanup was called or already processing
    				if ( cleanup || isMermaidProcessing.current ) {
    					logDebug( '⏭️ Skipping: cleanup=', cleanup, 'isMermaidProcessing=', isMermaidProcessing.current );
    					return;
    				}

    				isMermaidProcessing.current = true;
    				logDebug( '⏰ previewRef.current exists in setTimeout:', !!previewRef.current );

    				try {
    					if ( previewRef.current && processMermaidBlocksRef.current ) {
    						logDebug( '🎯 previewRef.current type:', typeof previewRef.current );
    						logDebug( '🎯 previewRef.current tagName:', previewRef.current?.tagName );
    						logDebug( '🎯 previewRef.current innerHTML length:', previewRef.current?.innerHTML?.length || 0 );

    						// Use ref to access latest function without dependency
    						const mermaidResult = await processMermaidBlocksRef.current( previewRef.current, mermaidBgColor );
    						logDebug( '🎯 processMermaidBlocks call completed successfully, result:', mermaidResult );

    						// Process Chart.js blocks after Mermaid (before saving processed HTML)
    						let chartResult = 0;
    						if ( ! cleanup && previewRef.current ) {
    							try {
    								chartResult = await processChartBlocks( previewRef.current );
    								logDebug( '[Chart.js] Processing completed, result:', chartResult );
    							} catch ( chartError ) {
    								console.warn( '[WP GFM Editor] Chart processing error:', chartError );
    							}
    						}

    						// Save processed HTML only once after both Mermaid and Chart.js are done
    						// This preserves both Mermaid SVGs and Chart.js images in React state
    						if ( ! cleanup && ( mermaidResult > 0 || chartResult > 0 ) && previewRef.current ) {
    							setProcessedHtml( previewRef.current.innerHTML );
    						}
    					} else {
    						logDebug( '❌ previewRef.current or processMermaidBlocksRef.current is null/undefined' );
    					}
    				} catch ( error ) {
    					console.error( '[WP GFM Editor] ❌ processMermaidBlocks error:', error );
    					console.error( '[WP GFM Editor] ❌ Error stack:', error.stack );
    				} finally {
    					isMermaidProcessing.current = false;
    				}
    			}, 400 );
    		} else {
    			logDebug( '❌ Conditions not met:', {
    				isPreview,
    				renderedHtml: !!renderedHtml,
    				previewRefExists: !!previewRef.current
    			} );
    		}

    		// Cleanup function: clear timeout and reset flags on unmount or dependency change
    		return () => {
    			cleanup = true;
    			if ( timeoutId ) {
    				clearTimeout( timeoutId );
    			}
    			isMermaidProcessing.current = false;
    		};
    	}, [ isPreview, renderedHtml, mermaidBgColor ] );  // Removed processMermaidBlocks from deps

    	// Content change handler (async support, multilingual aware)
    	const handleChange = async ( event ) => {
    		const newContent = event.target.value;

    		if ( isMultilingualMode ) {
    			// Update content in the current language
    			const updatedLanguages = {
    				...languages,
    				[ currentEditingLang ]: {
    					...( languages[ currentEditingLang ] || {} ),
    					content: newContent,
    				},
    			};

    			// Render markdown and update HTML for current language
    			await renderMarkdownForLanguage( newContent, currentEditingLang, updatedLanguages );
    		} else {
    			// Legacy single-language mode
    			setAttributes( { content: newContent } );
    			await renderMarkdown( newContent );
    		}
    	};

    	// Render markdown for a specific language
    	const renderMarkdownForLanguage = async ( markdownContent, lang, updatedLanguages ) => {
    		if ( ! markdownContent ) {
    			const newLanguages = {
    				...updatedLanguages,
    				[ lang ]: { content: '', html: '' },
    			};
    			setAttributes( { languages: newLanguages } );
    			setRenderedHtml( '' );
    			setProcessedHtml( null );
    			return;
    		}

    		try {
    			// Parse frontmatter
    			const { frontmatter, body } = parseFrontMatter( markdownContent );
    			setAttributes( { frontmatterData: frontmatter } );

    			// Wait for Shiki
    			if ( ! shikiLoaded && ! editorShikiHighlighter ) {
    				await loadShikiForEditor();
    				setShikiLoaded( true );
    			}

    			// Render markdown
    			let bodyHtml;
    			if ( window.wpGfmRenderWithIndentPreprocessing ) {
    				bodyHtml = window.wpGfmRenderWithIndentPreprocessing( body, md );
    			} else {
    				bodyHtml = md.render( body );
    			}

    			const fmHtml = showFrontmatter ? renderFrontmatterHeader( frontmatter ) : '';
    			let generatedHtml = fmHtml + bodyHtml;
    			generatedHtml = applyDiffHighlightingToHtml( generatedHtml );

    			// Get Shiki theme
    			let currentShikiTheme = window.wpGfmConfig?.theme?.shiki_theme ??
    				(window.matchMedia?.('(prefers-color-scheme: dark)').matches ? 'github-dark' : 'github-light');
    			if ( currentShikiTheme === 'auto' ) {
    				const isDark = window.matchMedia &&
    					window.matchMedia( '(prefers-color-scheme: dark)' ).matches;
    				currentShikiTheme = isDark ? 'github-dark' : 'github-light';
    			}

    			// Update languages with rendered HTML
    			const newLanguages = {
    				...updatedLanguages,
    				[ lang ]: {
    					content: markdownContent,
    					html: generatedHtml,
    				},
    			};

    			setAttributes( {
    				languages: newLanguages,
    				shikiTheme: currentShikiTheme,
    				// Also keep top-level content/html updated with default language for compatibility
    				content: newLanguages[ defaultLanguage ]?.content || '',
    				html: newLanguages[ defaultLanguage ]?.html || '',
    			} );

    			setRenderedHtml( generatedHtml );

    			if ( lastRenderedHtmlRef.current !== generatedHtml ) {
    				setProcessedHtml( null );
    				lastRenderedHtmlRef.current = generatedHtml;
    			}
    		} catch ( error ) {
    			console.error( '[WP GFM Renderer] Rendering error:', error );
    			setRenderedHtml( '<p>An error occurred while rendering Markdown</p>' );
    			setProcessedHtml( null );
    		}
    	};

    	// Initialize multilingual mode (convert single-language to multilingual)
    	const initializeMultilingualMode = useCallback( () => {
    		const siteLang = window.wpGfmConfig?.siteLanguage || 'en';

    		// If already in multilingual mode, don't reinitialize
    		if ( availableLanguages.length > 0 ) {
    			return;
    		}

    		// Convert current content to multilingual format
    		const newLanguages = {
    			[ siteLang ]: {
    				content: content || '',
    				html: html || '',
    			},
    		};

    		setAttributes( {
    			languages: newLanguages,
    			defaultLanguage: siteLang,
    			availableLanguages: [ siteLang ],
    			showLanguageSwitcher: false,
    		} );

    		setCurrentEditingLang( siteLang );
    	}, [ content, html, availableLanguages.length, setAttributes ] );

    	// Add a new language
    	const handleAddLanguage = useCallback( ( langCode, copyFromLang = '' ) => {
    		if ( ! isValidLanguageCode( langCode ) ) {
    			console.error( '[GFMR] Invalid language code:', langCode );
    			return;
    		}

    		if ( availableLanguages.includes( langCode ) ) {
    			console.warn( '[GFMR] Language already exists:', langCode );
    			return;
    		}

    		if ( availableLanguages.length >= MAX_LANGUAGES ) {
    			console.warn( '[GFMR] Maximum language limit reached:', MAX_LANGUAGES );
    			return;
    		}

    		// Initialize multilingual mode if needed
    		if ( ! isMultilingualMode ) {
    			initializeMultilingualMode();
    		}

    		// Create new language content (optionally copy from existing)
    		let newLangContent = { content: '', html: '' };
    		if ( copyFromLang && languages[ copyFromLang ] ) {
    			newLangContent = { ...languages[ copyFromLang ] };
    		}

    		const updatedLanguages = {
    			...languages,
    			[ langCode ]: newLangContent,
    		};

    		const updatedAvailable = [ ...availableLanguages, langCode ];

    		setAttributes( {
    			languages: updatedLanguages,
    			availableLanguages: updatedAvailable,
    			showLanguageSwitcher: updatedAvailable.length > 1,
    		} );

    		// Switch to the new language
    		setCurrentEditingLang( langCode );
    		setIsAddLanguageModalOpen( false );
    	}, [ availableLanguages, languages, isMultilingualMode, initializeMultilingualMode, setAttributes ] );

    	// Delete a language
    	const handleDeleteLanguage = useCallback( ( langCode ) => {
    		if ( langCode === defaultLanguage ) {
    			alert( __( 'Cannot delete the default language. Please change the default first.', 'markdown-renderer-for-github' ) );
    			return;
    		}

    		if ( ! window.confirm(
    			__( 'Are you sure you want to delete this translation? This cannot be undone.', 'markdown-renderer-for-github' )
    		) ) {
    			return;
    		}

    		const { [ langCode ]: removed, ...remainingLanguages } = languages;
    		const updatedAvailable = availableLanguages.filter( l => l !== langCode );

    		setAttributes( {
    			languages: remainingLanguages,
    			availableLanguages: updatedAvailable,
    			showLanguageSwitcher: updatedAvailable.length > 1,
    		} );

    		// Switch to default language if we were editing the deleted language
    		if ( currentEditingLang === langCode ) {
    			setCurrentEditingLang( defaultLanguage );
    		}
    	}, [ defaultLanguage, languages, availableLanguages, currentEditingLang, setAttributes ] );

    	// Switch editing language
    	const handleLanguageSwitch = useCallback( ( langCode ) => {
    		// availableLanguagesまたはlanguagesオブジェクトにキーが存在すればOK
    		if ( ! availableLanguages.includes( langCode ) && ! languages[ langCode ] ) return;

    		setCurrentEditingLang( langCode );

    		// Update rendered HTML for the new language
    		const langContent = languages[ langCode ];
    		if ( langContent ) {
    			setRenderedHtml( langContent.html || '' );
    			setProcessedHtml( null );
    		}
    	}, [ availableLanguages, languages ] );

    	// Block properties
    	const blockProps = useBlockProps( {
    		className: 'gfmr-markdown-block'
    	} );

    	const previewHtml = processedHtml || renderedHtml;

    	return (
    		<>
    			<BlockControls>
    				<ToolbarGroup>
    					<ToolbarButton
    						icon={ isPreview ? 'edit' : 'visibility' }
    						label={ isPreview ? __( 'Edit', 'markdown-renderer-for-github' ) : __( 'Preview', 'markdown-renderer-for-github' ) }
    						onClick={ () => setIsPreview( ! isPreview ) }
    						isActive={ isPreview }
    					/>
    					{ isImageInsertEnabled && (
    						<MediaUploadCheck>
    							<MediaUpload
    								onSelect={ handleImageInsert }
    								allowedTypes={ [ 'image' ] }
    								multiple={ false }
    								render={ ( { open } ) => (
    								<ToolbarButton
    									icon="format-image"
    									label={ __( 'Insert Image', 'markdown-renderer-for-github' ) }
    									disabled={ isPreview }
    									onClick={ () => {
    										if ( isPreview ) {
    											return;
    										}
    										// Save cursor position before opening media library
    										const textarea = textareaRef.current;
    										if ( textarea ) {
    											cursorPositionRef.current = {
    												start: textarea.selectionStart,
    												end: textarea.selectionEnd
    											};
    										}
    										open();
    									} }
    								/>
    								) }
    							/>
    						</MediaUploadCheck>
    					) }
    				</ToolbarGroup>
    			</BlockControls>

    			<InspectorControls>
    				{ /* Language Settings Panel */ }
    				<PanelBody
    					title={ __( 'Language Settings', 'markdown-renderer-for-github' ) }
    					initialOpen={ isMultilingualMode }
    				>
    					{ ! isMultilingualMode ? (
    						<>
    							<p className="components-base-control__help" style={ { marginBottom: '12px' } }>
    								{ __( 'Enable multilingual mode to write content in multiple languages.', 'markdown-renderer-for-github' ) }
    							</p>
    							<Button
    								variant="secondary"
    								onClick={ () => {
    									initializeMultilingualMode();
    									setIsAddLanguageModalOpen( true );
    								} }
    							>
    								{ __( 'Enable Multilingual', 'markdown-renderer-for-github' ) }
    							</Button>
    						</>
    					) : (
    						<>
    							<SelectControl
    								label={ __( 'Default Language', 'markdown-renderer-for-github' ) }
    								value={ defaultLanguage }
    								options={ availableLanguages.map( l => ( {
    									label: l.toUpperCase(),
    									value: l,
    								} ) ) }
    								onChange={ ( value ) => {
    									setAttributes( {
    										defaultLanguage: value,
    										// Update top-level content/html with new default
    										content: languages[ value ]?.content || '',
    										html: languages[ value ]?.html || '',
    									} );
    								} }
    							/>
    							<ToggleControl
    								label={ __( 'Show Language Switcher', 'markdown-renderer-for-github' ) }
    								checked={ showLanguageSwitcher }
    								onChange={ ( value ) => setAttributes( { showLanguageSwitcher: value } ) }
    								help={ __( 'Display language buttons on the frontend', 'markdown-renderer-for-github' ) }
    							/>
    							{ availableLanguages.length > 0 && (
    								<div className="gfmr-language-list" style={ { marginTop: '16px' } }>
    									<p className="components-base-control__label" style={ { marginBottom: '8px' } }>
    										{ __( 'Languages', 'markdown-renderer-for-github' ) } ({ availableLanguages.length }/{ MAX_LANGUAGES })
    									</p>
    									{ availableLanguages.map( lang => (
    										<div
    											key={ lang }
    											style={ {
    												display: 'flex',
    												justifyContent: 'space-between',
    												alignItems: 'center',
    												padding: '4px 0',
    												borderBottom: '1px solid #ddd',
    											} }
    										>
    											<span>
    												{ lang.toUpperCase() }
    												{ lang === defaultLanguage && (
    													<span style={ { color: '#757575', marginLeft: '8px', fontSize: '12px' } }>
    														({ __( 'default', 'markdown-renderer-for-github' ) })
    													</span>
    												) }
    											</span>
    											{ lang !== defaultLanguage && (
    												<Button
    													isDestructive
    													isSmall
    													onClick={ () => handleDeleteLanguage( lang ) }
    												>
    													{ __( 'Delete', 'markdown-renderer-for-github' ) }
    												</Button>
    											) }
    										</div>
    									) ) }
    									{ availableLanguages.length < MAX_LANGUAGES && (
    										<Button
    											variant="secondary"
    											isSmall
    											onClick={ () => setIsAddLanguageModalOpen( true ) }
    											style={ { marginTop: '12px' } }
    										>
    											{ __( '+ Add Language', 'markdown-renderer-for-github' ) }
    										</Button>
    									) }
    								</div>
    							) }
    						</>
    					) }
    				</PanelBody>

    				<PanelBody
    					title={ __( 'Frontmatter Settings', 'markdown-renderer-for-github' ) }
    					initialOpen={ false }
    				>
    					<ToggleControl
    						label={ __( 'Show Frontmatter Header', 'markdown-renderer-for-github' ) }
    						checked={ showFrontmatter }
    						onChange={ ( value ) => setAttributes( { showFrontmatter: value } ) }
    						help={ __( 'Display YAML frontmatter metadata as a formatted header', 'markdown-renderer-for-github' ) }
    					/>
    				</PanelBody>

    				<PanelBody
    					title={ __( 'Mermaid Settings', 'markdown-renderer-for-github' ) }
    					initialOpen={ false }
    				>
    					<PanelRow>
    						<div style={ { width: '100%' } }>
    							<label
    								htmlFor="mermaid-bg-color"
    								style={ {
    									display: 'block',
    									marginBottom: '8px',
    									fontWeight: '500'
    								} }
    							>
    								{ __( 'Background Color', 'markdown-renderer-for-github' ) }
    							</label>
    							<ColorPicker
    								color={ (() => {
    									const currentColor = mermaidBgColor || 'transparent';
    									// ColorPicker constraint: fully transparent (#RRGGBB00) locks alpha to 0, so for 9-digit HEX8 ending in 00, replace with FF for display
    									if (currentColor.length === 9 && currentColor.endsWith('00')) {
    										const colorWithoutAlpha = currentColor.slice(0, 7);
    										const fixedColor = colorWithoutAlpha + 'FF';
    										return fixedColor;
    									}
    									return currentColor;
    								})() }
    								onChange={ ( color ) => {
    									// ColorPicker returns HEX8 format (#RRGGBBAA) when enableAlpha is enabled. Normalize fully transparent (#00000000) to 'transparent' string
    									const colorValue = color === '#00000000' ? 'transparent' : color;
    									setAttributes( { mermaidBgColor: colorValue } );
    								} }
    								enableAlpha
    							/>
    							<div
    								className="components-base-control__help"
    								style={ {
    									marginTop: '8px',
    									fontSize: '12px',
    									color: '#757575',
    									fontStyle: 'italic'
    								} }
    							>
    								💡 { __( 'After changing colors, return to edit mode and preview again', 'markdown-renderer-for-github' ) }
    							</div>
    						</div>
    					</PanelRow>
    				</PanelBody>
    			</InspectorControls>

    			{ /* Add Language Modal */ }
    			{ isAddLanguageModalOpen && (
    				<AddLanguageModal
    					onAdd={ handleAddLanguage }
    					onClose={ () => setIsAddLanguageModalOpen( false ) }
    					existingLanguages={ availableLanguages }
    				/>
    			) }

    			<div { ...blockProps }>
    				<div className="gfmr-markdown-header">
    					<span className="gfmr-markdown-label">
    						{ __( 'Markdown', 'markdown-renderer-for-github' ) }
    					</span>
    					<span className="gfmr-markdown-mode">
    						{ isPreview ? __( 'Preview', 'markdown-renderer-for-github' ) : __( 'Edit', 'markdown-renderer-for-github' ) }
    					</span>
    				</div>

    				{ /* Language Tabs (shown when multilingual mode is active) */ }
    				{ ( isMultilingualMode || Object.keys( languages ).length > 0 ) && (
    					<div className="gfmr-language-tabs">
    						{ ( availableLanguages.length > 0 ? availableLanguages : Object.keys( languages ) ).map( lang => (
    							<button
    								key={ lang }
    								type="button"
    								className={ `gfmr-lang-tab ${ currentEditingLang === lang ? 'active' : '' }` }
    								onClick={ () => handleLanguageSwitch( lang ) }
    								disabled={ isPreview }
    							>
    								{ lang.toUpperCase() }
    							</button>
    						) ) }
    						{ availableLanguages.length < MAX_LANGUAGES && (
    							<button
    								type="button"
    								className="gfmr-lang-add"
    								onClick={ () => setIsAddLanguageModalOpen( true ) }
    								disabled={ isPreview }
    								title={ __( 'Add Language', 'markdown-renderer-for-github' ) }
    							>
    								+
    							</button>
    						) }
    					</div>
    				) }

    				{ ! isPreview ? (
    					<ResizableBox
    						size={ { height: 300 } }
    						minHeight="100"
    						enable={ {
    							top: false,
    							right: false,
    							bottom: true,
    							left: false,
    							topRight: false,
    							bottomRight: false,
    							bottomLeft: false,
    							topLeft: false,
    						} }
    						className="gfmr-markdown-editor-wrapper"
    					>
    						<textarea
    							ref={ textareaRef }
    							className="gfmr-markdown-editor"
    							value={ getCurrentContent() }
    							onChange={ handleChange }
    							placeholder={ __( 'Enter Markdown here...\n\n# Heading\n**Bold** *Italic*\n- List item', 'markdown-renderer-for-github' ) }
    							spellCheck="false"
    						/>
    					</ResizableBox>
    				) : (
    					<div className={ `gfmr-markdown-preview gfmr-markdown-rendered-preview ${ themeClass }` } ref={ previewRef }>
    						{ previewHtml ? (
    							<RawHTML>
    								{ previewHtml }
    							</RawHTML>
    						) : (
    							<p className="gfmr-markdown-empty">
    								{ __( 'No Markdown content to preview', 'markdown-renderer-for-github' ) }
    							</p>
    						) }
    					</div>
    				) }
    			</div>
    		</>
    	);
    }

    /**
     * Add Language Modal Component
     */
    function AddLanguageModal( { onAdd, onClose, existingLanguages } ) {
    	const [ selectedLang, setSelectedLang ] = useState( '' );
    	const [ customLang, setCustomLang ] = useState( '' );
    	const [ copyFrom, setCopyFrom ] = useState( '' );
    	const [ error, setError ] = useState( '' );

    	const handleAdd = () => {
    		const langCode = selectedLang === 'custom'
    			? customLang.toLowerCase().trim()
    			: selectedLang;

    		// Validate
    		if ( ! langCode ) {
    			setError( __( 'Please select a language', 'markdown-renderer-for-github' ) );
    			return;
    		}

    		if ( ! isValidLanguageCode( langCode ) ) {
    			setError( __( 'Invalid language code format', 'markdown-renderer-for-github' ) );
    			return;
    		}

    		if ( existingLanguages.includes( langCode ) ) {
    			setError( __( 'This language already exists', 'markdown-renderer-for-github' ) );
    			return;
    		}

    		onAdd( langCode, copyFrom );
    	};

    	// Filter out already-used languages
    	const availableCommonLangs = COMMON_LANGUAGES.filter(
    		l => ! existingLanguages.includes( l.value )
    	);

    	return (
    		<Modal
    			title={ __( 'Add Language', 'markdown-renderer-for-github' ) }
    			onRequestClose={ onClose }
    			className="gfmr-add-language-modal"
    		>
    			<div style={ { minWidth: '300px' } }>
    				<SelectControl
    					label={ __( 'Language', 'markdown-renderer-for-github' ) }
    					value={ selectedLang }
    					options={ [
    						{ value: '', label: __( 'Select...', 'markdown-renderer-for-github' ) },
    						...availableCommonLangs,
    						{ value: 'custom', label: __( 'Other (enter code)', 'markdown-renderer-for-github' ) },
    					] }
    					onChange={ ( value ) => {
    						setSelectedLang( value );
    						setError( '' );
    					} }
    				/>

    				{ selectedLang === 'custom' && (
    					<TextControl
    						label={ __( 'Language Code (e.g., pt, nl, ar)', 'markdown-renderer-for-github' ) }
    						value={ customLang }
    						onChange={ ( value ) => {
    							setCustomLang( value );
    							setError( '' );
    						} }
    						maxLength={ 5 }
    						help={ __( 'Use ISO 639-1 format (2 letters, e.g., "pt" for Portuguese)', 'markdown-renderer-for-github' ) }
    					/>
    				) }

    				{ existingLanguages.length > 0 && (
    					<SelectControl
    						label={ __( 'Copy content from', 'markdown-renderer-for-github' ) }
    						value={ copyFrom }
    						options={ [
    							{ value: '', label: __( 'Start empty', 'markdown-renderer-for-github' ) },
    							...existingLanguages.map( l => ( {
    								value: l,
    								label: l.toUpperCase(),
    							} ) ),
    						] }
    						onChange={ setCopyFrom }
    					/>
    				) }

    				{ error && (
    					<p style={ { color: '#d63638', marginTop: '8px' } }>{ error }</p>
    				) }

    				<div style={ { marginTop: '16px', display: 'flex', gap: '8px', justifyContent: 'flex-end' } }>
    					<Button variant="secondary" onClick={ onClose }>
    						{ __( 'Cancel', 'markdown-renderer-for-github' ) }
    					</Button>
    					<Button variant="primary" onClick={ handleAdd }>
    						{ __( 'Add', 'markdown-renderer-for-github' ) }
    					</Button>
    				</div>
    			</div>
    		</Modal>
    	);
    }