piki-gui 0.3.0

FLTK-based GUI for Piki personal wiki application
Documentation
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
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
// Structured Rich Text Display
// A rendering and interaction widget for StructuredDocument
// Completely decoupled from markdown syntax

use super::structured_document::*;
use super::structured_editor::*;
use crate::draw_context::DrawContext;
use crate::draw_context::FontStyle;
use crate::draw_context::FontType;
use crate::theme::{FontSettings, Theme};

/// A search match in the document
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchMatch {
    /// Block index where the match starts
    pub block_index: usize,
    /// Character offset within the block where match starts
    pub start_offset: usize,
    /// Character offset within the block where match ends (exclusive)
    pub end_offset: usize,
}

/// Layout information for a rendered line
#[derive(Debug, Clone)]
pub struct LayoutLine {
    /// Y position of the line's baseline
    y: i32,
    /// Height of the line
    height: i32,
    /// Default x position for the cursor when the line has no text runs
    base_x: i32,
    /// Block index this line belongs to
    block_index: usize,
    /// Character offset range within the block [start, end)
    char_start: usize,
    char_end: usize,
    /// Preferred visual end offset for cursor placement
    visual_char_end: usize,
    /// Visual elements on this line
    runs: Vec<VisualRun>,
}

impl LayoutLine {}

/// Geometry for drawing a table's grid lines and header fills. Computed during
/// layout and consumed by `draw`. Coordinates are in layout space (relative to
/// the widget's content origin, before scroll translation).
#[derive(Debug, Clone)]
struct TableLayout {
    /// Document block index of the table.
    block_index: usize,
    /// X of each vertical grid line, left to right (length = columns + 1).
    col_x: Vec<i32>,
    /// Y of each horizontal grid line, top to bottom (length = rows + 1).
    row_y: Vec<i32>,
}

/// Finalize the current visual line: record its char range and wrap flag, then
/// move it into `lines`. Shared by the wrapping engine and `push_token_wrapped`.
fn push_line(
    lines: &mut Vec<Vec<VisualRun>>,
    ranges: &mut Vec<(usize, usize)>,
    wraps: &mut Vec<bool>,
    current_line: &mut Vec<VisualRun>,
    default_offset: usize,
    wrapped: bool,
) {
    let (start, end) = if let Some(first) = current_line.first() {
        let last_end = current_line
            .last()
            .map(|r| r.char_range.1)
            .unwrap_or(first.char_range.1);
        (first.char_range.0, last_end)
    } else {
        (default_offset, default_offset)
    };
    ranges.push((start, end));
    wraps.push(wrapped);
    lines.push(std::mem::take(current_line));
}

/// Build a [`VisualRun`] for content text with the given resolved style.
fn run_from_style(
    text: String,
    x: i32,
    width: i32,
    char_range: (usize, usize),
    inline_index: usize,
    block_idx: usize,
    style: ResolvedRunStyle,
) -> VisualRun {
    VisualRun {
        text,
        x,
        width,
        font_type: style.font_type,
        font_style: style.font_style,
        font_size: style.font_size,
        font_color: style.font_color,
        background_color: style.background_color,
        underline: style.underline,
        strikethrough: style.strikethrough,
        block_index: block_idx,
        char_range,
        inline_index: Some(inline_index),
        checklist: None,
    }
}

/// Place a single token (a word or a whole link) onto the current line, wrapping
/// to the next line when it doesn't fit.
///
/// When `break_long_words` is set and the token is wider than a full line, it is
/// split greedily at character boundaries so it can never bleed past the
/// available width — needed for narrow table cells. With the flag off, behavior
/// is identical to the original word wrapper (wrap once, then place whole).
#[allow(clippy::too_many_arguments)]
fn push_token_wrapped(
    ctx: &mut dyn DrawContext,
    lines: &mut Vec<Vec<VisualRun>>,
    line_ranges: &mut Vec<(usize, usize)>,
    line_wraps: &mut Vec<bool>,
    current_line: &mut Vec<VisualRun>,
    current_x: &mut i32,
    current_y: &mut i32,
    start_x: i32,
    width: i32,
    line_height: i32,
    break_long_words: bool,
    text: &str,
    char_base: usize,
    inline_index: usize,
    block_idx: usize,
    style: ResolvedRunStyle,
) {
    let (font, fstyle, size) = (style.font_type, style.font_style, style.font_size);
    let token_width = ctx.text_width(text, font, fstyle, size) as i32;

    let must_break = break_long_words && width > 0 && token_width > width;
    if !must_break {
        // Wrap to the next line if it doesn't fit and we're not already at the
        // line start, then place the whole token (original behavior).
        if *current_x + token_width > start_x + width && *current_x > start_x {
            push_line(
                lines,
                line_ranges,
                line_wraps,
                current_line,
                char_base,
                true,
            );
            *current_x = start_x;
            *current_y += line_height;
        }
        current_line.push(run_from_style(
            text.to_string(),
            *current_x,
            token_width,
            (char_base, char_base + text.len()),
            inline_index,
            block_idx,
            style,
        ));
        *current_x += token_width;
        return;
    }

    // The token is wider than a full line: break it greedily, character by
    // character, so it can never overflow into the neighbouring column.
    let indices: Vec<usize> = text.char_indices().map(|(i, _)| i).collect();
    let char_count = indices.len();
    let byte_end_of = |k: usize| {
        if k + 1 < char_count {
            indices[k + 1]
        } else {
            text.len()
        }
    };

    let mut seg_start = 0usize;
    let mut k = 0usize;
    while k < char_count {
        // Grow the chunk while it still fits from the current x.
        let mut fit_end = seg_start;
        let mut fit_k = k;
        while fit_k < char_count {
            let cand_end = byte_end_of(fit_k);
            let w = ctx.text_width(&text[seg_start..cand_end], font, fstyle, size) as i32;
            if *current_x + w > start_x + width {
                break;
            }
            fit_end = cand_end;
            fit_k += 1;
        }

        if fit_end > seg_start {
            let chunk = &text[seg_start..fit_end];
            let w = ctx.text_width(chunk, font, fstyle, size) as i32;
            current_line.push(run_from_style(
                chunk.to_string(),
                *current_x,
                w,
                (char_base + seg_start, char_base + fit_end),
                inline_index,
                block_idx,
                style,
            ));
            *current_x += w;
            seg_start = fit_end;
            k = fit_k;
        } else if *current_x == start_x {
            // Not even one character fits on a fresh line (column narrower than a
            // glyph). Force one through to guarantee forward progress.
            let cand_end = byte_end_of(k);
            let chunk = &text[seg_start..cand_end];
            let w = ctx.text_width(chunk, font, fstyle, size) as i32;
            current_line.push(run_from_style(
                chunk.to_string(),
                *current_x,
                w,
                (char_base + seg_start, char_base + cand_end),
                inline_index,
                block_idx,
                style,
            ));
            *current_x += w;
            seg_start = cand_end;
            k += 1;
        }

        // More to place: wrap to the next line.
        if seg_start < text.len() {
            push_line(
                lines,
                line_ranges,
                line_wraps,
                current_line,
                char_base + seg_start,
                true,
            );
            *current_x = start_x;
            *current_y += line_height;
        }
    }
}

/// Return a copy of inline content with every text run forced to bold. Used for
/// table header cells, which the renderer draws in bold like the tdoc CLI.
fn bolden_inline(content: &[InlineContent]) -> Vec<InlineContent> {
    content
        .iter()
        .map(|item| match item {
            InlineContent::Text(run) => {
                let mut style = run.style;
                style.bold = true;
                InlineContent::Text(TextRun::new(run.text.clone(), style))
            }
            InlineContent::Link { link, content } => InlineContent::Link {
                link: link.clone(),
                content: bolden_inline(content),
            },
            InlineContent::HardBreak => InlineContent::HardBreak,
        })
        .collect()
}

struct InlineContentLayout {
    lines: Vec<Vec<VisualRun>>,
    line_ranges: Vec<(usize, usize)>,
    line_wraps: Vec<bool>,
    y_after: i32,
}

/// Checklist marker rendering metadata
#[derive(Debug, Clone)]
struct ChecklistVisual {
    /// Whether the checklist item is checked
    checked: bool,
    /// Size of the checkbox square in pixels
    box_size: i32,
}

/// A visual run of text with styling
#[derive(Debug, Clone)]
struct VisualRun {
    /// Display text
    text: String,
    /// X position
    x: i32,
    /// Width of the text
    width: i32,
    /// Block index this belongs to
    block_index: usize,
    /// Character range within block
    char_range: (usize, usize),
    /// Inline content index (for link detection)
    inline_index: Option<usize>,
    /// Checklist rendering info (if this run is a checklist marker)
    checklist: Option<ChecklistVisual>,

    font_type: FontType,
    font_style: FontStyle,
    font_size: u8,
    font_color: u32,
    background_color: Option<u32>,
    underline: bool,
    strikethrough: bool,
    // Highlight not necessary, as we'll have a non-None background_color for that
}

#[derive(Clone, Copy)]
struct ResolvedRunStyle {
    font_type: FontType,
    font_style: FontStyle,
    font_size: u8,
    font_color: u32,
    background_color: Option<u32>,
    underline: bool,
    strikethrough: bool,
    // Highlight not necessary, as we'll have a non-None background_color for that
}

/// Rich Text Display for Structured Documents
pub struct StructuredRichDisplay {
    // Position and size
    x: i32,
    y: i32,
    w: i32,
    h: i32,

    // Editor (contains document and cursor)
    editor: StructuredEditor,

    // Layout cache
    layout_lines: Vec<LayoutLine>,
    // Grid geometry for table blocks, parallel to layout_lines (cell text lives
    // in layout_lines; borders/header fills are drawn from this).
    table_layouts: Vec<TableLayout>,
    layout_valid: bool,

    // Scrolling
    scroll_offset: i32,

    // Cursor display
    cursor_visible: bool,
    // Cursor blink state
    blink_on: bool,
    blink_period_ms: u64,
    // Most recent elapsed-ms value seen by `tick`; used as the time base when
    // re-anchoring the blink cycle on cursor movement.
    last_tick_ms: u64,
    // Elapsed-ms value at which the current blink cycle started (its "on" phase).
    blink_anchor_ms: u64,

    // Link hover state
    hovered_link: Option<(usize, usize)>, // (block_index, inline_index)

    // Sticky horizontal position for vertical navigation across proportional fonts
    cursor_preferred_line_offset: Option<usize>,

    // Search state
    search_term: String,
    search_matches: Vec<SearchMatch>,
    search_current_index: Option<usize>,

    // Theme
    theme: Theme,
}

impl StructuredRichDisplay {
    pub fn new(x: i32, y: i32, w: i32, h: i32) -> Self {
        StructuredRichDisplay {
            x,
            y,
            w,
            h,
            editor: StructuredEditor::new(),
            layout_lines: Vec::new(),
            table_layouts: Vec::new(),
            layout_valid: false,
            scroll_offset: 0,
            cursor_visible: true,
            blink_on: true,
            blink_period_ms: 1000, // 1s full period (500ms on/off)
            last_tick_ms: 0,
            blink_anchor_ms: 0,
            hovered_link: None,
            cursor_preferred_line_offset: None,
            search_term: String::new(),
            search_matches: Vec::new(),
            search_current_index: None,
            theme: Theme::default(),
        }
    }

    /// Get the editor
    pub fn editor(&self) -> &StructuredEditor {
        &self.editor
    }

    /// Get mutable editor
    pub fn editor_mut(&mut self) -> &mut StructuredEditor {
        self.layout_valid = false;
        &mut self.editor
    }

    /// Set scroll offset
    pub fn set_scroll(&mut self, offset: i32) {
        self.scroll_offset = offset.max(0);
    }

    /// Get scroll offset
    pub fn scroll_offset(&self) -> i32 {
        self.scroll_offset
    }

    /// Ensure the cursor's line is visible by adjusting scroll offset
    /// Minimally scrolls to bring the cursor line within the viewport with small margins
    pub fn ensure_cursor_visible(&mut self, ctx: &mut dyn DrawContext) {
        // Ensure layout is up to date
        self.layout(ctx);

        // Get cursor visual position (content coords)
        if let Some((_cx, cy, ch)) = self.get_cursor_visual_position(ctx) {
            let viewport_top = self.scroll_offset;
            let viewport_bottom = self.scroll_offset + self.h;

            // Provide a small comfort margin around the cursor line
            let margin_top = 8;
            let margin_bottom = 8;

            let mut new_scroll = self.scroll_offset;

            // If above viewport (with margin), scroll up
            if cy < viewport_top + margin_top {
                new_scroll = (cy - margin_top).max(0);
            }

            // If below viewport (with margin), scroll down
            if cy + ch > viewport_bottom - margin_bottom {
                new_scroll = (cy + ch + margin_bottom - self.h).max(0);
            }

            // Clamp to content height
            let max_scroll = (self.content_height() - self.h).max(0);
            if new_scroll > max_scroll {
                new_scroll = max_scroll;
            }

            self.scroll_offset = new_scroll;
        }
    }

    /// Get content height
    pub fn content_height(&self) -> i32 {
        if let Some(last_line) = self.layout_lines.last() {
            last_line.y + last_line.height + self.theme.padding_vertical
        } else {
            0
        }
    }

    /// Resize the widget
    pub fn resize(&mut self, x: i32, y: i32, w: i32, h: i32) {
        self.x = x;
        self.y = y;
        self.w = w;
        self.h = h;
        self.layout_valid = false;
    }

    /// Set horizontal padding (for write room mode)
    pub fn set_horizontal_padding(&mut self, padding: i32) {
        self.theme.padding_horizontal = padding;
        self.layout_valid = false;
    }

    /// Get current horizontal padding
    pub fn horizontal_padding(&self) -> i32 {
        self.theme.padding_horizontal
    }

    pub fn x(&self) -> i32 {
        self.x
    }
    pub fn y(&self) -> i32 {
        self.y
    }
    pub fn w(&self) -> i32 {
        self.w
    }
    pub fn h(&self) -> i32 {
        self.h
    }

    /// Perform layout
    fn layout(&mut self, ctx: &mut dyn DrawContext) {
        if self.layout_valid {
            return;
        }

        self.layout_lines.clear();
        self.table_layouts.clear();

        let content_width = self.w - 2 * self.theme.padding_horizontal;
        let mut current_y = self.theme.padding_vertical;

        // Clone blocks to avoid borrow checker issues
        let blocks = self.editor.document().blocks().to_vec();

        for (block_idx, block) in blocks.iter().enumerate() {
            current_y = self.layout_block(block, block_idx, current_y, content_width, ctx);
        }

        self.layout_valid = true;
    }

    /// Compute a precise character offset within a given line for a desired x position using font metrics.
    pub fn precise_offset_in_line(
        &self,
        line: &LayoutLine,
        x: i32,
        ctx: &mut dyn DrawContext,
    ) -> usize {
        let mut offset = line.char_start;
        for run in &line.runs {
            let run_end_x = run.x + run.width;
            if x < run.x {
                // Before this run: cursor snaps to beginning of this run
                return offset;
            }
            if x >= run.x && x < run_end_x {
                // Within this run: walk characters and measure
                let (font, fstyle, size) = (run.font_type, run.font_style, run.font_size);
                let mut last_offset = run.char_range.0;
                // Iterate char boundaries in the run's text
                for (i, _) in run
                    .text
                    .char_indices()
                    .chain(std::iter::once((run.text.len(), ' ')))
                {
                    let w = ctx.text_width(&run.text[..i], font, fstyle, size) as i32;
                    if run.x + w > x {
                        return last_offset;
                    }
                    last_offset = run.char_range.0 + i;
                }
                return run.char_range.1;
            }
            // After this run: advance offset
            offset = run.char_range.1;
        }
        offset
    }

    /// Find the index of the visual line containing the current cursor. If no exact match,
    /// returns the nearest line within the same block, otherwise None.
    fn is_last_visual_line_in_block(&self, line_index: usize) -> bool {
        if line_index >= self.layout_lines.len() {
            return true;
        }
        let block_idx = self.layout_lines[line_index].block_index;
        !self.layout_lines[line_index + 1..]
            .iter()
            .any(|line| line.block_index == block_idx)
    }

    fn offset_belongs_to_line(&self, line_index: usize, offset: usize) -> bool {
        if line_index >= self.layout_lines.len() {
            return false;
        }
        let line = &self.layout_lines[line_index];
        if line.char_start == line.char_end {
            return offset == line.char_start;
        }
        if offset < line.char_start {
            return false;
        }
        if offset < line.char_end {
            return true;
        }
        if offset == line.char_end && line.visual_char_end == line.char_end {
            return true;
        }
        self.is_last_visual_line_in_block(line_index) && offset == line.char_end
    }

    /// Get the character offset within the visual line for a given block index and offset.
    fn visual_line_offset(&self, pos: DocumentPosition) -> Option<usize> {
        for (i, line) in self.layout_lines.iter().enumerate() {
            if line.block_index == pos.block_index && self.offset_belongs_to_line(i, pos.offset) {
                return Some(pos.offset - line.char_start);
            }
        }
        None
    }

    fn compute_visual_char_end(&self, runs: &[VisualRun], char_end: usize, wrapped: bool) -> usize {
        if !wrapped {
            return char_end;
        }

        for run in runs.iter().rev() {
            if run.char_range.0 == run.char_range.1 {
                continue;
            }

            if run.text.is_empty() {
                continue;
            }

            let trimmed = run.text.trim_end_matches(|c: char| c.is_whitespace());
            if trimmed.len() == run.text.len() {
                return run.char_range.1;
            }

            if trimmed.is_empty() {
                continue;
            }

            let delta = run.text.len() - trimmed.len();
            return run.char_range.1.saturating_sub(delta);
        }

        char_end
    }

    fn current_line_index_for_cursor(&self) -> Option<usize> {
        let cursor = self.editor.cursor();
        // First, look for a line in the same block whose char range contains the offset
        for (i, line) in self.layout_lines.iter().enumerate() {
            if line.block_index == cursor.block_index
                && self.offset_belongs_to_line(i, cursor.offset)
            {
                return Some(i);
            }
        }
        // Fallback: closest line in the same block by char range proximity
        let mut candidate: Option<(usize, usize)> = None; // (index, distance)
        for (i, line) in self.layout_lines.iter().enumerate() {
            if line.block_index == cursor.block_index {
                let dist = if cursor.offset < line.char_start {
                    line.char_start - cursor.offset
                } else {
                    cursor.offset.saturating_sub(line.char_end)
                };
                candidate = match candidate {
                    Some((_, best_dist)) if best_dist <= dist => candidate,
                    _ => Some((i, dist)),
                };
            }
        }
        candidate.map(|(i, _)| i)
    }

    pub fn record_preferred_pos(&mut self, pos: DocumentPosition) {
        self.cursor_preferred_line_offset = self.visual_line_offset(pos);
    }

    fn get_preferred_pos_for_line(&self, line: &LayoutLine) -> DocumentPosition {
        let preferred_offset = self
            .cursor_preferred_line_offset
            .unwrap_or(self.visual_line_offset(self.editor.cursor()).unwrap_or(0));

        let line_visual_len = line.visual_char_end.saturating_sub(line.char_start);
        let effective_offset = preferred_offset.min(line_visual_len);

        DocumentPosition::new(line.block_index, line.char_start + effective_offset)
    }

    /// Whether the block at `block_index` is a (read-only) table.
    fn block_is_table(&self, block_index: usize) -> bool {
        matches!(
            self.editor
                .document()
                .blocks()
                .get(block_index)
                .map(|b| &b.block_type),
            Some(BlockType::Table { .. })
        )
    }

    /// Resolve the cursor position for a vertical move that landed on
    /// `target_idx`. A table is a single stop, so landing on any of its lines
    /// places the cursor at the table's start; other blocks honor the preferred
    /// (sticky) column.
    fn vertical_target_pos(&self, target_idx: usize) -> DocumentPosition {
        let line = &self.layout_lines[target_idx];
        if self.block_is_table(line.block_index) {
            DocumentPosition::new(line.block_index, 0)
        } else {
            self.get_preferred_pos_for_line(line)
        }
    }

    /// Move cursor one visual line up, using wrapped lines when applicable.
    /// When `extend` is true, extends the selection (Shift+Up behavior).
    pub fn move_cursor_visual_up(&mut self, extend: bool, ctx: &mut dyn DrawContext) {
        // Ensure layout is current for measurement
        self.layout(ctx);
        if self.layout_lines.is_empty() {
            if extend {
                self.editor.move_cursor_up_extend();
            } else {
                self.editor.move_cursor_up();
            }
            return;
        }

        let cur_idx = match self.current_line_index_for_cursor() {
            Some(i) => i,
            None => {
                if extend {
                    self.editor.move_cursor_up_extend();
                } else {
                    self.editor.move_cursor_up();
                }
                return;
            }
        };
        if cur_idx == 0 {
            // Already at the first line
            return;
        }

        // Treat a table as a single stop: skip up over all of its lines to the
        // line directly above it.
        let cur_block = self.layout_lines[cur_idx].block_index;
        let target_idx = if self.block_is_table(cur_block) {
            let mut first = cur_idx;
            while first > 0 && self.layout_lines[first - 1].block_index == cur_block {
                first -= 1;
            }
            if first == 0 {
                return; // table is the first block; nothing above
            }
            first - 1
        } else {
            cur_idx - 1
        };

        let new_pos = self.vertical_target_pos(target_idx);
        if extend {
            self.editor.extend_selection_to(new_pos);
        } else {
            self.editor.set_cursor(new_pos);
        }
    }

    /// Move cursor one visual line down, using wrapped lines when applicable.
    /// When `extend` is true, extends the selection (Shift+Down behavior).
    pub fn move_cursor_visual_down(&mut self, extend: bool, ctx: &mut dyn DrawContext) {
        self.layout(ctx);
        if self.layout_lines.is_empty() {
            if extend {
                self.editor.move_cursor_down_extend();
            } else {
                self.editor.move_cursor_down();
            }
            return;
        }

        let cur_idx = match self.current_line_index_for_cursor() {
            Some(i) => i,
            None => {
                if extend {
                    self.editor.move_cursor_down_extend();
                } else {
                    self.editor.move_cursor_down();
                }
                return;
            }
        };

        let len = self.layout_lines.len();
        // Treat a table as a single stop: skip down over all of its lines to the
        // first line below it.
        let cur_block = self.layout_lines[cur_idx].block_index;
        let target_idx = if self.block_is_table(cur_block) {
            let mut t = cur_idx + 1;
            while t < len && self.layout_lines[t].block_index == cur_block {
                t += 1;
            }
            t
        } else {
            cur_idx + 1
        };

        if target_idx >= len {
            // Already at (or past) the last line
            return;
        }

        let new_pos = self.vertical_target_pos(target_idx);
        if extend {
            self.editor.extend_selection_to(new_pos);
        } else {
            self.editor.set_cursor(new_pos);
        }
    }

    /// Move cursor to the beginning of the current visual line.
    pub fn move_cursor_visual_line_start(&mut self, extend: bool, ctx: &mut dyn DrawContext) {
        self.layout(ctx);
        if self.layout_lines.is_empty() {
            if extend {
                self.editor.move_cursor_to_line_start_extend();
            } else {
                self.editor.move_cursor_to_line_start();
            }
            return;
        }

        let cursor_block = self.editor.cursor().block_index;
        let line_idx = match self.current_line_index_for_cursor() {
            Some(idx) => idx,
            None => {
                if extend {
                    self.editor.move_cursor_to_line_start_extend();
                } else {
                    self.editor.move_cursor_to_line_start();
                }
                return;
            }
        };
        let line = &self.layout_lines[line_idx];
        if line.block_index != cursor_block {
            if extend {
                self.editor.move_cursor_to_line_start_extend();
            } else {
                self.editor.move_cursor_to_line_start();
            }
            return;
        }

        let new_pos = DocumentPosition::new(line.block_index, line.char_start);
        if extend {
            self.editor.extend_selection_to(new_pos);
        } else {
            self.editor.set_cursor(new_pos);
        }
        self.record_preferred_pos(new_pos);
    }

    /// Move cursor to the end of the current visual line.
    pub fn move_cursor_visual_line_end_precise(&mut self, extend: bool, ctx: &mut dyn DrawContext) {
        self.layout(ctx);
        if self.layout_lines.is_empty() {
            if extend {
                self.editor.move_cursor_to_line_end_extend();
            } else {
                self.editor.move_cursor_to_line_end();
            }
            return;
        }

        let cursor_block = self.editor.cursor().block_index;
        let line_idx = match self.current_line_index_for_cursor() {
            Some(idx) => idx,
            None => {
                if extend {
                    self.editor.move_cursor_to_line_end_extend();
                } else {
                    self.editor.move_cursor_to_line_end();
                }
                return;
            }
        };
        let line = &self.layout_lines[line_idx];
        if line.block_index != cursor_block {
            if extend {
                self.editor.move_cursor_to_line_end_extend();
            } else {
                self.editor.move_cursor_to_line_end();
            }
            return;
        }

        let mut target_offset = line.char_end;
        while target_offset > line.char_start
            && !self.offset_belongs_to_line(line_idx, target_offset)
        {
            target_offset -= 1;
        }

        let new_pos = DocumentPosition::new(line.block_index, target_offset);
        if extend {
            self.editor.extend_selection_to(new_pos);
        } else {
            self.editor.set_cursor(new_pos);
        }
        self.record_preferred_pos(new_pos);
    }

    /// Layout a single block
    fn layout_block(
        &mut self,
        block: &Block,
        block_idx: usize,
        y: i32,
        width: i32,
        ctx: &mut dyn DrawContext,
    ) -> i32 {
        let start_x = self.theme.padding_horizontal;
        let default_line_height = self.theme.line_height;

        match &block.block_type {
            BlockType::Paragraph => self.layout_inline_block(
                block,
                block_idx,
                y,
                start_x,
                width,
                default_line_height,
                ctx,
            ),
            BlockType::Heading { level } => {
                let header_font = match level {
                    1 => self.theme.header_level_1,
                    2 => self.theme.header_level_2,
                    _ => self.theme.header_level_3,
                };
                let height = ((header_font.font_size as f32) * 1.3) as i32;
                // Add top margin for headings (unless it's the first block)
                let top_margin = if block_idx > 0 { 15 } else { 0 };
                let y_after = self.layout_inline_block(
                    block,
                    block_idx,
                    y + top_margin,
                    start_x,
                    width,
                    height,
                    ctx,
                );
                y_after + 10 // Extra spacing after headings
            }
            BlockType::CodeBlock { .. } => {
                let text = block.to_plain_text();
                let lines: Vec<&str> = text.lines().collect();
                let f = self.theme.code_text;
                let mut current_y = y + 5;
                let code_start_x = start_x + 10;
                let is_empty = lines.is_empty();

                for line in &lines {
                    let line_width =
                        ctx.text_width(line, f.font_type, f.font_style, f.font_size) as i32;
                    let line_len = line.len();
                    let runs = vec![VisualRun {
                        text: (*line).to_string(),
                        x: code_start_x,
                        width: line_width,
                        font_type: f.font_type,
                        font_style: f.font_style,
                        font_size: f.font_size,
                        font_color: f.font_color,
                        background_color: f.background_color,
                        underline: false,
                        strikethrough: false,
                        block_index: block_idx,
                        char_range: (0, line_len),
                        inline_index: None,
                        checklist: None,
                    }];
                    let visual_char_end = self.compute_visual_char_end(&runs, line_len, false);
                    self.layout_lines.push(LayoutLine {
                        y: current_y,
                        height: default_line_height,
                        base_x: code_start_x,
                        block_index: block_idx,
                        char_start: 0,
                        char_end: line_len,
                        visual_char_end,
                        runs,
                    });
                    current_y += default_line_height;
                }

                if is_empty {
                    self.layout_lines.push(LayoutLine {
                        y: current_y,
                        height: default_line_height,
                        base_x: code_start_x,
                        block_index: block_idx,
                        char_start: 0,
                        char_end: 0,
                        visual_char_end: 0,
                        runs: Vec::new(),
                    });
                    current_y += default_line_height;
                }

                current_y + 10
            }
            BlockType::BlockQuote => {
                // Layout quote content with left padding; drawing of the vertical bar
                // happens during draw() per line based on block type.
                self.layout_inline_block(
                    block,
                    block_idx,
                    y + 5,
                    start_x + 20,
                    width - 20,
                    default_line_height,
                    ctx,
                ) + 5
            }
            BlockType::ListItem {
                ordered,
                number,
                checkbox,
            } => {
                let plain_font = self.theme.plain_text;

                // Base indent padding before label (keeps list labels off the edge)
                let label_left_pad = plain_font.font_size as i32;

                let mut checklist_visual: Option<ChecklistVisual> = None;

                // Determine label text and padding width
                let (label_text, label_pad_width, content_start_x) = if let Some(checked) = checkbox
                {
                    let mut marker_box_size = (plain_font.font_size as i32).saturating_sub(4);
                    if marker_box_size < 8 {
                        marker_box_size = 8;
                    }
                    if marker_box_size > default_line_height {
                        marker_box_size = default_line_height;
                    }

                    let mut space_width = ctx.text_width(
                        " ",
                        plain_font.font_type,
                        plain_font.font_style,
                        plain_font.font_size,
                    ) as i32;
                    if space_width < 4 {
                        space_width = 4;
                    }

                    let label_pad_width = marker_box_size + space_width;
                    let content_start_x = start_x + label_left_pad + label_pad_width;

                    checklist_visual = Some(ChecklistVisual {
                        checked: *checked,
                        box_size: marker_box_size,
                    });

                    (String::new(), label_pad_width, content_start_x)
                } else if *ordered {
                    // Find contiguous ordered list run (adjacent siblings)
                    let doc = self.editor.document();
                    let blocks = doc.blocks();

                    // Find run start
                    let mut run_start = block_idx;
                    while run_start > 0 {
                        if let BlockType::ListItem { ordered: true, .. } =
                            blocks[run_start - 1].block_type
                        {
                            run_start -= 1;
                        } else {
                            break;
                        }
                    }
                    // Find run end
                    let mut run_end = block_idx;
                    while run_end + 1 < blocks.len() {
                        if let BlockType::ListItem { ordered: true, .. } =
                            blocks[run_end + 1].block_type
                        {
                            run_end += 1;
                        } else {
                            break;
                        }
                    }

                    // Determine starting number (default to 1 if None)
                    let first_num = match blocks[run_start].block_type {
                        BlockType::ListItem {
                            ordered: true,
                            number,
                            ..
                        } => number.unwrap_or(1),
                        _ => 1,
                    };

                    // Compute the maximum used number across the run
                    let mut max_num = first_num;
                    for (i, b) in blocks[run_start..=run_end].iter().enumerate() {
                        if let BlockType::ListItem {
                            ordered: true,
                            number,
                            ..
                        } = b.block_type
                        {
                            let n = number.unwrap_or(first_num + i as u64);
                            if n > max_num {
                                max_num = n;
                            }
                        }
                    }

                    // Pad width is width of the largest label text (max_num + ". ")
                    let max_label = format!("{}. ", max_num);
                    let label_pad_width = ctx.text_width(
                        &max_label,
                        plain_font.font_type,
                        plain_font.font_style,
                        plain_font.font_size,
                    ) as i32;

                    // Current label text
                    let idx_in_run = block_idx - run_start;
                    let cur_num = number.unwrap_or(first_num + idx_in_run as u64);
                    let label_text = format!("{}. ", cur_num);
                    let content_start_x = start_x + label_left_pad + label_pad_width;

                    (label_text, label_pad_width, content_start_x)
                } else {
                    // Unordered bullet label and fixed width
                    let bullet_text = "• ".to_string();
                    let bullet_width = ctx.text_width(
                        &bullet_text,
                        plain_font.font_type,
                        plain_font.font_style,
                        plain_font.font_size,
                    ) as i32;
                    let content_start_x = start_x + label_left_pad + bullet_width;
                    (bullet_text, bullet_width, content_start_x)
                };

                // Assemble label run
                let mut runs = vec![VisualRun {
                    text: label_text,
                    x: start_x + label_left_pad,
                    width: label_pad_width,
                    font_type: self.theme.plain_text.font_type,
                    font_style: self.theme.plain_text.font_style,
                    font_size: self.theme.plain_text.font_size,
                    font_color: self.theme.plain_text.font_color,
                    background_color: self.theme.plain_text.background_color,
                    underline: false,
                    strikethrough: false,
                    block_index: block_idx,
                    char_range: (0, 0),
                    inline_index: None,
                    checklist: checklist_visual,
                }];

                // Layout the content with proper text indentation
                let layout = self.layout_inline_content(
                    &block.content,
                    &block.block_type,
                    block_idx,
                    y,
                    content_start_x,
                    width - (content_start_x - start_x),
                    default_line_height,
                    false,
                    ctx,
                );
                let (mut content_runs, content_ranges, content_wraps, _y_after) = (
                    layout.lines,
                    layout.line_ranges,
                    layout.line_wraps,
                    layout.y_after,
                );

                let mut current_y = y;

                // Merge bullet with first line
                if !content_runs.is_empty() && !content_runs[0].is_empty() {
                    let first_wrap = content_wraps.first().copied().unwrap_or(false);
                    let first_range = content_ranges.first().copied().unwrap_or((0, 0));
                    runs.append(&mut content_runs[0]);

                    // Calculate char range from content runs (skip bullet)
                    let char_start = runs
                        .iter()
                        .skip(1)
                        .map(|r| r.char_range.0)
                        .min()
                        .unwrap_or(first_range.0);
                    let char_end = runs
                        .iter()
                        .skip(1)
                        .map(|r| r.char_range.1)
                        .max()
                        .unwrap_or(first_range.1);

                    let visual_char_end = self.compute_visual_char_end(&runs, char_end, first_wrap);
                    self.layout_lines.push(LayoutLine {
                        y: current_y,
                        height: default_line_height,
                        base_x: content_start_x,
                        block_index: block_idx,
                        char_start,
                        char_end,
                        visual_char_end,
                        runs,
                    });
                    current_y += default_line_height;

                    // Add remaining lines
                    for (idx, line_runs) in content_runs.iter().enumerate().skip(1) {
                        let (char_start, char_end) =
                            content_ranges.get(idx).copied().unwrap_or((0, 0));
                        let wrapped = content_wraps.get(idx).copied().unwrap_or(false);
                        let visual_char_end =
                            self.compute_visual_char_end(line_runs, char_end, wrapped);

                        self.layout_lines.push(LayoutLine {
                            y: current_y,
                            height: default_line_height,
                            base_x: content_start_x,
                            block_index: block_idx,
                            char_start,
                            char_end,
                            visual_char_end,
                            runs: line_runs.clone(),
                        });
                        current_y += default_line_height;
                    }
                } else {
                    // Just bullet
                    self.layout_lines.push(LayoutLine {
                        y: current_y,
                        height: default_line_height,
                        base_x: content_start_x,
                        block_index: block_idx,
                        char_start: 0,
                        char_end: 0,
                        visual_char_end: 0,
                        runs,
                    });
                    current_y += default_line_height;
                }

                current_y + 2
            }
            BlockType::Table { rows } => self.layout_table(block_idx, rows, y, start_x, width, ctx),
        }
    }

    /// Lay out a read-only table: compute column widths, wrap each cell, and
    /// emit one `LayoutLine` per physical text line plus a `TableLayout` holding
    /// the grid geometry for `draw`. Modeled on the tdoc CLI's bordered grid.
    fn layout_table(
        &mut self,
        block_idx: usize,
        rows: &[TableRow],
        y: i32,
        start_x: i32,
        width: i32,
        ctx: &mut dyn DrawContext,
    ) -> i32 {
        const BORDER: i32 = 1;
        const PAD_H: i32 = 6; // horizontal padding inside each cell
        const PAD_V: i32 = 3; // vertical padding inside each row
        let line_height = self.theme.line_height;

        let column_count = rows.iter().map(|r| r.cells.len()).max().unwrap_or(0);
        if rows.is_empty() || column_count == 0 {
            return y;
        }

        // Natural (single-line) content width per column, measured with the
        // cell's font (header cells are bold and thus a touch wider).
        let plain = self.theme.plain_text;
        let mut natural = vec![0i32; column_count];
        for row in rows {
            for (col, cell) in row.cells.iter().enumerate() {
                let style = if cell.is_header {
                    FontStyle::Bold
                } else {
                    plain.font_style
                };
                let text = cell.to_plain_text().replace('\n', " ");
                let w = ctx.text_width(&text, plain.font_type, style, plain.font_size) as i32;
                natural[col] = natural[col].max(w);
            }
        }

        // Fit the columns into the available width. Each column needs PAD_H on
        // both sides; vertical borders add BORDER around/between columns.
        let cols = column_count as i32;
        let structural = (cols + 1) * BORDER + cols * 2 * PAD_H;
        let min_col = (plain.font_size as i32).max(8); // keep ~1 char visible
        let budget = (width - structural).max(cols * min_col);
        let total_natural: i32 = natural.iter().sum();

        let mut col_width = vec![0i32; column_count];
        if total_natural <= budget || total_natural == 0 {
            col_width.copy_from_slice(&natural);
        } else {
            // Shrink proportionally to fit, never below min_col.
            for (c, &nat) in natural.iter().enumerate() {
                let scaled = (nat as i64 * budget as i64 / total_natural as i64) as i32;
                col_width[c] = scaled.max(min_col);
            }
        }

        // Vertical grid-line positions: a border sits at each col_x; the cell
        // interior between consecutive lines is PAD_H + content + PAD_H.
        let mut col_x = vec![0i32; column_count + 1];
        col_x[0] = start_x;
        for c in 0..column_count {
            col_x[c + 1] = col_x[c] + BORDER + PAD_H + col_width[c] + PAD_H;
        }

        let mut row_y = Vec::with_capacity(rows.len() + 1);
        let mut current_y = y;

        for row in rows {
            row_y.push(current_y);

            // Wrap each cell to its column width, capturing its visual lines.
            let mut cell_lines: Vec<Vec<Vec<VisualRun>>> = Vec::with_capacity(column_count);
            for col in 0..column_count {
                let lines = match row.cells.get(col) {
                    Some(cell) if !cell.content.is_empty() => {
                        let content = if cell.is_header {
                            bolden_inline(&cell.content)
                        } else {
                            cell.content.clone()
                        };
                        let cell_x = col_x[col] + BORDER + PAD_H;
                        self.layout_inline_content(
                            &content,
                            &BlockType::Paragraph,
                            block_idx,
                            0,
                            cell_x,
                            col_width[col],
                            line_height,
                            // Force-break tokens too wide for the column so cell
                            // content can't bleed into the next column.
                            true,
                            ctx,
                        )
                        .lines
                    }
                    _ => Vec::new(),
                };
                cell_lines.push(lines);
            }

            let row_line_count = cell_lines.iter().map(Vec::len).max().unwrap_or(0).max(1);

            // One LayoutLine per physical text line, gathering the matching
            // wrapped line from every cell so the shared draw loop renders them.
            let content_top = current_y + BORDER + PAD_V;
            for li in 0..row_line_count {
                let mut runs: Vec<VisualRun> = Vec::new();
                for cell in &cell_lines {
                    if let Some(line) = cell.get(li) {
                        runs.extend(line.iter().cloned());
                    }
                }
                self.layout_lines.push(LayoutLine {
                    y: content_top + li as i32 * line_height,
                    height: line_height,
                    base_x: start_x,
                    block_index: block_idx,
                    char_start: 0,
                    char_end: 0,
                    visual_char_end: 0,
                    runs,
                });
            }

            current_y = content_top + row_line_count as i32 * line_height + PAD_V;
        }

        row_y.push(current_y); // bottom border

        self.table_layouts.push(TableLayout {
            block_index: block_idx,
            col_x,
            row_y,
        });

        current_y + BORDER + 10
    }

    /// Layout an inline block (paragraph, heading, etc.)
    #[allow(clippy::too_many_arguments)]
    fn layout_inline_block(
        &mut self,
        block: &Block,
        block_idx: usize,
        y: i32,
        start_x: i32,
        width: i32,
        line_height: i32,
        ctx: &mut dyn DrawContext,
    ) -> i32 {
        let layout = self.layout_inline_content(
            &block.content,
            &block.block_type,
            block_idx,
            y,
            start_x,
            width,
            line_height,
            false,
            ctx,
        );
        let (lines, line_ranges, line_wraps, _y_after) = (
            layout.lines,
            layout.line_ranges,
            layout.line_wraps,
            layout.y_after,
        );

        let mut current_y = y;

        if lines.is_empty() {
            // Empty block - create an empty layout line for cursor positioning
            self.layout_lines.push(LayoutLine {
                y: current_y,
                height: line_height,
                base_x: start_x,
                block_index: block_idx,
                char_start: 0,
                char_end: 0,
                visual_char_end: 0,
                runs: Vec::new(),
            });
            current_y += line_height;
        } else {
            for (line_runs, ((char_start, char_end), wrapped)) in lines
                .into_iter()
                .zip(line_ranges.into_iter().zip(line_wraps))
            {
                let base_x = line_runs
                    .iter()
                    .filter(|r| !(r.char_range.0 == r.char_range.1 && r.inline_index.is_none()))
                    .map(|r| r.x)
                    .min()
                    .unwrap_or(start_x);

                let visual_char_end = self.compute_visual_char_end(&line_runs, char_end, wrapped);

                self.layout_lines.push(LayoutLine {
                    y: current_y,
                    height: line_height,
                    base_x,
                    block_index: block_idx,
                    char_start,
                    char_end,
                    visual_char_end,
                    runs: line_runs,
                });
                current_y += line_height;
            }
        }

        current_y + 5
    }

    fn resolve_text_run_style(
        &self,
        base_font: FontSettings,
        text_style: &TextStyle,
    ) -> ResolvedRunStyle {
        let settings = if text_style.code {
            self.theme.code_text
        } else {
            base_font
        };

        let base_is_bold = matches!(settings.font_style, FontStyle::Bold | FontStyle::BoldItalic);
        let base_is_italic = matches!(
            settings.font_style,
            FontStyle::Italic | FontStyle::BoldItalic
        );

        let final_bold = text_style.bold || base_is_bold;
        let final_italic = text_style.italic || base_is_italic;

        let font_style = match (final_bold, final_italic) {
            (true, true) => FontStyle::BoldItalic,
            (true, false) => FontStyle::Bold,
            (false, true) => FontStyle::Italic,
            (false, false) => FontStyle::Regular,
        };

        let highlight = text_style.highlight;
        let mut background_color = settings.background_color;
        if highlight {
            background_color = Some(self.theme.highlight_color);
        }

        ResolvedRunStyle {
            font_type: settings.font_type,
            font_style,
            font_size: settings.font_size,
            font_color: settings.font_color,
            background_color,
            underline: text_style.underline,
            strikethrough: text_style.strikethrough,
        }
    }

    fn resolve_link_run_style(&self, base_font: FontSettings) -> ResolvedRunStyle {
        let mut style = self.resolve_text_run_style(base_font, &TextStyle::plain());
        style.font_color = self.theme.link_color;
        style.underline = true;
        style
    }

    /// Layout inline content with word wrapping
    /// Returns (lines of runs, final_y)
    #[allow(clippy::too_many_arguments)]
    fn layout_inline_content(
        &mut self,
        content: &[InlineContent],
        block_type: &BlockType,
        block_idx: usize,
        y: i32,
        start_x: i32,
        width: i32,
        line_height: i32,
        break_long_words: bool,
        ctx: &mut dyn DrawContext,
    ) -> InlineContentLayout {
        let mut lines: Vec<Vec<VisualRun>> = Vec::new();
        let mut line_wraps: Vec<bool> = Vec::new();
        let mut line_ranges: Vec<(usize, usize)> = Vec::new();
        let mut current_line: Vec<VisualRun> = Vec::new();
        let mut current_x = start_x;
        let mut current_y = y;
        let mut char_offset = 0;

        let base_font = match block_type {
            BlockType::Heading { level } => match level {
                1 => self.theme.header_level_1,
                2 => self.theme.header_level_2,
                _ => self.theme.header_level_3,
            },
            BlockType::BlockQuote => self.theme.quote_text,
            BlockType::CodeBlock { .. } => self.theme.code_text,
            _ => self.theme.plain_text,
        };

        let mut pending_empty_line = false;

        for (inline_idx, item) in content.iter().enumerate() {
            match item {
                InlineContent::Text(run) => {
                    pending_empty_line = false;
                    let style = self.resolve_text_run_style(base_font, &run.style);
                    let font = style.font_type;
                    let fstyle = style.font_style;
                    let size = style.font_size;

                    // Word wrap - track actual positions in original text
                    let text = &run.text;
                    let mut word_start = 0;
                    let mut in_word = false;
                    let mut leading_space_handled = false;

                    for (i, ch) in text
                        .char_indices()
                        .chain(std::iter::once((text.len(), ' ')))
                    {
                        let is_whitespace = ch.is_whitespace();

                        // Handle leading whitespace at the start of the run
                        if !leading_space_handled && is_whitespace && i == 0 {
                            // Find all leading whitespace
                            let mut space_end = 0;
                            for (idx, c) in text.char_indices() {
                                if c.is_whitespace() {
                                    space_end = idx + c.len_utf8();
                                } else {
                                    break;
                                }
                            }

                            if space_end > 0 {
                                let space_text = &text[..space_end];
                                let space_width =
                                    ctx.text_width(space_text, font, fstyle, size) as i32;

                                current_line.push(VisualRun {
                                    text: space_text.to_string(),
                                    x: current_x,
                                    width: space_width,
                                    font_type: style.font_type,
                                    font_style: style.font_style,
                                    font_size: style.font_size,
                                    font_color: style.font_color,
                                    background_color: style.background_color,
                                    underline: style.underline,
                                    strikethrough: style.strikethrough,
                                    block_index: block_idx,
                                    char_range: (char_offset, char_offset + space_end),
                                    inline_index: Some(inline_idx),
                                    checklist: None,
                                });

                                current_x += space_width;
                            }
                            leading_space_handled = true;
                        }

                        if in_word && (is_whitespace || i == text.len()) {
                            // End of word - extract word with trailing whitespace
                            let mut word_end = i;
                            // Include trailing whitespace in the word
                            while word_end < text.len()
                                && text[word_end..]
                                    .chars()
                                    .next()
                                    .is_some_and(|c| c.is_whitespace() && c != '\n')
                            {
                                word_end += text[word_end..].chars().next().unwrap().len_utf8();
                            }

                            let word_text = &text[word_start..word_end];
                            push_token_wrapped(
                                ctx,
                                &mut lines,
                                &mut line_ranges,
                                &mut line_wraps,
                                &mut current_line,
                                &mut current_x,
                                &mut current_y,
                                start_x,
                                width,
                                line_height,
                                break_long_words,
                                word_text,
                                char_offset + word_start,
                                inline_idx,
                                block_idx,
                                style,
                            );
                            in_word = false;
                        } else if !in_word && !is_whitespace {
                            // Start of new word
                            word_start = i;
                            in_word = true;
                        }
                    }

                    char_offset += text.len();
                }
                InlineContent::Link {
                    link: _,
                    content: link_content,
                } => {
                    pending_empty_line = false;
                    // Render link content using link styling
                    let style = self.resolve_link_run_style(base_font);
                    let text = link_content
                        .iter()
                        .map(|c| c.to_plain_text())
                        .collect::<String>();

                    push_token_wrapped(
                        ctx,
                        &mut lines,
                        &mut line_ranges,
                        &mut line_wraps,
                        &mut current_line,
                        &mut current_x,
                        &mut current_y,
                        start_x,
                        width,
                        line_height,
                        break_long_words,
                        &text,
                        char_offset,
                        inline_idx,
                        block_idx,
                        style,
                    );
                    char_offset += text.len();
                }
                InlineContent::HardBreak => {
                    push_line(
                        &mut lines,
                        &mut line_ranges,
                        &mut line_wraps,
                        &mut current_line,
                        char_offset,
                        false,
                    );
                    current_x = start_x;
                    current_y += line_height;
                    char_offset += 1;
                    pending_empty_line = true;
                }
            }
        }

        let is_empty = lines.is_empty();

        if !current_line.is_empty() {
            push_line(
                &mut lines,
                &mut line_ranges,
                &mut line_wraps,
                &mut current_line,
                char_offset,
                false,
            );
        } else if pending_empty_line {
            // Preserve the trailing hard break by materializing an empty visual line.
            push_line(
                &mut lines,
                &mut line_ranges,
                &mut line_wraps,
                &mut current_line,
                char_offset,
                false,
            );
        }

        InlineContentLayout {
            lines,
            line_ranges,
            line_wraps,
            y_after: if is_empty { y } else { current_y },
        }
    }

    /// Check if a visual run intersects with the current selection
    /// Returns None if no selection, or Some((start_offset, end_offset)) relative to the run
    fn get_run_selection_range(&self, run: &VisualRun) -> Option<(usize, usize)> {
        let selection = self.editor.selection()?;
        let (sel_start, sel_end) = selection;

        // Normalize selection so start <= end
        let (sel_start, sel_end) = if sel_start.block_index < sel_end.block_index
            || (sel_start.block_index == sel_end.block_index && sel_start.offset <= sel_end.offset)
        {
            (sel_start, sel_end)
        } else {
            (sel_end, sel_start)
        };

        // Check if this run's block is within the selection
        if run.block_index < sel_start.block_index || run.block_index > sel_end.block_index {
            return None;
        }

        // Determine the selection range within this run
        let run_start = run.char_range.0;
        let run_end = run.char_range.1;

        let sel_start_offset = if run.block_index == sel_start.block_index {
            sel_start.offset
        } else {
            0
        };

        let sel_end_offset = if run.block_index == sel_end.block_index {
            sel_end.offset
        } else {
            usize::MAX
        };

        // Check if run intersects with selection
        if run_end <= sel_start_offset || run_start >= sel_end_offset {
            return None;
        }

        // Calculate the intersection
        let start_in_run = sel_start_offset
            .saturating_sub(run_start)
            .min(run_end - run_start);
        let end_in_run = sel_end_offset
            .saturating_sub(run_start)
            .min(run_end - run_start);

        Some((start_in_run, end_in_run))
    }

    /// Draw the grid lines and header-cell backgrounds for every table block.
    /// Cell text itself is drawn by the normal `LayoutLine` run loop; this only
    /// paints the structural decoration around it.
    fn draw_tables(&self, ctx: &mut dyn DrawContext) {
        let viewport_top = self.scroll_offset;
        let viewport_bottom = self.scroll_offset + self.h;
        let blocks = self.editor.document().blocks();

        for table in &self.table_layouts {
            let (top, bottom) = match (table.row_y.first(), table.row_y.last()) {
                (Some(&t), Some(&b)) => (t, b),
                _ => continue,
            };
            // Skip tables entirely outside the viewport.
            if bottom < viewport_top || top > viewport_bottom {
                continue;
            }
            let left = *table.col_x.first().unwrap();
            let right = *table.col_x.last().unwrap();

            let sx = self.x;
            let sy = self.y - self.scroll_offset;

            // Header-cell backgrounds, drawn first so text and grid sit on top.
            if let Some(BlockType::Table { rows }) =
                blocks.get(table.block_index).map(|b| &b.block_type)
            {
                ctx.set_color(self.theme.table_header_background);
                for (r, row) in rows.iter().enumerate() {
                    if r + 1 >= table.row_y.len() {
                        break;
                    }
                    let cell_top = sy + table.row_y[r];
                    let cell_h = table.row_y[r + 1] - table.row_y[r];
                    for (c, cell) in row.cells.iter().enumerate() {
                        if cell.is_header && c + 1 < table.col_x.len() {
                            let cx = sx + table.col_x[c];
                            let cw = table.col_x[c + 1] - table.col_x[c];
                            ctx.draw_rect_filled(cx, cell_top, cw, cell_h);
                        }
                    }
                }
            }

            // Grid lines.
            ctx.set_color(self.theme.table_border_color);
            for &x in &table.col_x {
                ctx.draw_line(sx + x, sy + top, sx + x, sy + bottom);
            }
            for &yv in &table.row_y {
                ctx.draw_line(sx + left, sy + yv, sx + right, sy + yv);
            }
        }
    }

    /// Draw the widget
    pub fn draw(&mut self, ctx: &mut dyn DrawContext) {
        self.layout(ctx);

        // Draw background
        ctx.set_color(self.theme.background_color);
        ctx.draw_rect_filled(self.x, self.y, self.w, self.h);

        // Set up clipping
        ctx.push_clip(self.x, self.y, self.w, self.h);

        // Draw visible lines
        let viewport_top = self.scroll_offset;
        let viewport_bottom = self.scroll_offset + self.h;

        // Table grid lines and header fills sit behind the cell text.
        self.draw_tables(ctx);

        for line in &self.layout_lines {
            if line.y + line.height < viewport_top || line.y > viewport_bottom {
                continue;
            }

            // If this line belongs to a BlockQuote, draw a vertical bar to the left.
            // We draw a short segment per line to keep implementation simple.
            if let Some(block) = self.editor.document().blocks().get(line.block_index)
                && let BlockType::BlockQuote = block.block_type
            {
                // Position the bar slightly left of the quote text indent (start_x + 20)
                let bar_x = self.x + self.theme.padding_horizontal + 12;
                let bar_y1 = self.y + line.y - self.scroll_offset;
                let bar_y2 = bar_y1 + line.height;
                ctx.set_color(self.theme.quote_bar_color);
                ctx.draw_line(bar_x, bar_y1, bar_x, bar_y2);
            }

            for run in &line.runs {
                // Check if this run is part of a hovered link
                let is_hovered = self.hovered_link.is_some_and(|(block_idx, inline_idx)| {
                    run.block_index == block_idx && run.inline_index == Some(inline_idx)
                });

                let descent = ctx.text_descent(run.font_type, run.font_style, run.font_size);
                ctx.set_font(run.font_type, run.font_style, run.font_size);
                ctx.set_color(run.font_color);

                let line_top = self.y + line.y - self.scroll_offset;
                let draw_x = self.x + run.x;

                if let Some(checklist) = &run.checklist {
                    let mut box_size = checklist.box_size;
                    if box_size > line.height {
                        box_size = line.height;
                    }
                    if box_size <= 0 {
                        continue;
                    }

                    let box_y = line_top + (line.height - box_size) / 2 + descent / 2;
                    let box_right = draw_x + box_size;
                    let box_bottom = box_y + box_size;

                    ctx.draw_line(draw_x, box_y, box_right, box_y);
                    ctx.draw_line(draw_x, box_y, draw_x, box_bottom);
                    ctx.draw_line(draw_x, box_bottom, box_right, box_bottom);
                    ctx.draw_line(box_right, box_y, box_right, box_bottom);

                    if checklist.checked {
                        let mut inset = ((box_size as f32) * 0.2).round() as i32;
                        if inset < 2 {
                            inset = 2;
                        }
                        if inset * 2 >= box_size {
                            inset = box_size / 2;
                        }
                        let x1 = draw_x + inset;
                        let y1 = box_y + inset;
                        let x2 = box_right - inset;
                        let y2 = box_bottom - inset;
                        ctx.draw_line(x1, y1, x2, y2);
                        ctx.draw_line(x1, y2, x2, y1);
                    }

                    continue;
                }

                let draw_y = line_top + run.font_size as i32;

                // Draw inline highlight background for styles that specify a bgcolor
                // (e.g., text highlight). Draw this first so selection can paint over it.
                {
                    let text_width =
                        ctx.text_width(&run.text, run.font_type, run.font_style, run.font_size)
                            as i32;
                    if let Some(col) = run.background_color {
                        ctx.set_color(col);
                        ctx.draw_rect_filled(draw_x, line_top, text_width, line.height);
                        ctx.set_color(run.font_color); // Restore text color for text drawing
                    }
                }

                // Draw background for hover (if link is hovered)
                // Draw this BEFORE selection so selection remains visible on top
                if is_hovered {
                    let text_width =
                        ctx.text_width(&run.text, run.font_type, run.font_style, run.font_size)
                            as i32;
                    ctx.set_color(self.theme.link_hover_background);
                    ctx.draw_rect_filled(draw_x, line_top, text_width, line.height);
                    ctx.set_color(run.font_color); // Restore text color
                }

                // Draw search highlight (if run contains a search match)
                // Draw BEFORE selection so selection takes priority
                if let Some((search_start, search_end, is_current)) =
                    self.get_run_search_highlight(run)
                    && search_end > search_start
                {
                    let text_before = if search_start < run.text.len() {
                        &run.text[..search_start]
                    } else {
                        &run.text
                    };
                    let text_match = if search_end <= run.text.len() {
                        &run.text[search_start..search_end]
                    } else if search_start < run.text.len() {
                        &run.text[search_start..]
                    } else {
                        ""
                    };

                    let before_width =
                        ctx.text_width(text_before, run.font_type, run.font_style, run.font_size)
                            as i32;
                    let match_width =
                        ctx.text_width(text_match, run.font_type, run.font_style, run.font_size)
                            as i32;

                    // Use different color for current match vs other matches
                    let highlight_color = if is_current {
                        self.theme.search_current_highlight_color
                    } else {
                        self.theme.search_highlight_color
                    };

                    ctx.set_color(highlight_color);
                    ctx.draw_rect_filled(draw_x + before_width, line_top, match_width, line.height);
                    ctx.set_color(run.font_color); // Restore text color
                }

                // Draw selection highlight (if run is selected)
                // Draw AFTER hover so the selection rectangle is on top
                if let Some((sel_start, sel_end)) = self.get_run_selection_range(run)
                    && sel_end > sel_start
                {
                    // Measure the text before and within selection
                    let text_before = if sel_start < run.text.len() {
                        &run.text[..sel_start]
                    } else {
                        &run.text
                    };
                    let text_selected = if sel_end <= run.text.len() {
                        &run.text[sel_start..sel_end]
                    } else if sel_start < run.text.len() {
                        &run.text[sel_start..]
                    } else {
                        ""
                    };

                    let before_width =
                        ctx.text_width(text_before, run.font_type, run.font_style, run.font_size)
                            as i32;
                    let sel_width =
                        ctx.text_width(text_selected, run.font_type, run.font_style, run.font_size)
                            as i32;

                    ctx.set_color(self.theme.selection_color);
                    ctx.draw_rect_filled(draw_x + before_width, line_top, sel_width, line.height);
                    ctx.set_color(run.font_color); // Restore text color
                }

                ctx.draw_text(&run.text, draw_x, draw_y);

                let text_width =
                    ctx.text_width(&run.text, run.font_type, run.font_style, run.font_size) as i32;

                // Draw underline if needed
                if run.underline {
                    ctx.draw_line(draw_x, draw_y + 2, draw_x + text_width, draw_y + 2);
                }

                // Draw strikethrough if needed
                if run.strikethrough {
                    // Draw line through middle of text (roughly at half the font size)
                    let descent = ctx.text_descent(run.font_type, run.font_style, run.font_size);
                    let strike_y = draw_y - (run.font_size as i32) / 2 + descent / 2 + 1;
                    ctx.set_color(0xaaaaaaff);
                    ctx.draw_rect_filled(draw_x, strike_y, text_width, 1);
                }
            }
        }

        // Draw cursor (only when widget has keyboard focus)
        if self.cursor_visible
            && ctx.has_focus()
            && self.blink_on
            && let Some((cx, cy, ch)) = self.get_cursor_visual_position(ctx)
        {
            let screen_y = self.y + cy - self.scroll_offset;
            let screen_x = self.x + cx;

            if screen_y >= self.y && screen_y < self.y + self.h {
                ctx.set_color(self.theme.cursor_color);
                // Draw the caret as a 2px-wide bar rather than a 1px line so
                // it's easier to spot (a hairline caret is easy to lose,
                // especially on high-DPI displays).
                ctx.draw_rect_filled(screen_x, screen_y, 2, ch);
            }
        }

        ctx.pop_clip();
    }

    /// Get visual position of cursor (x, y, height) relative to widget
    fn get_cursor_visual_position(&self, ctx: &mut dyn DrawContext) -> Option<(i32, i32, i32)> {
        let cursor = self.editor.cursor();
        let doc = self.editor.document();

        if cursor.block_index >= doc.block_count() {
            return None;
        }

        // Find the layout line containing the cursor
        for (idx, line) in self.layout_lines.iter().enumerate() {
            if line.block_index != cursor.block_index {
                continue;
            }
            if !self.offset_belongs_to_line(idx, cursor.offset) {
                continue;
            }

            let mut x = line.base_x;

            for run in &line.runs {
                // Skip non-content runs (like list bullets with char_range (0,0))
                if run.char_range.0 == run.char_range.1 && run.inline_index.is_none() {
                    continue;
                }

                if cursor.offset >= run.char_range.0 && cursor.offset <= run.char_range.1 {
                    // Cursor is in this run - measure actual text width
                    let offset_in_run = cursor.offset - run.char_range.0;
                    let (font, fstyle, size) = (run.font_type, run.font_style, run.font_size);

                    // Measure the text up to the cursor position
                    let text_before_cursor = if offset_in_run < run.text.len() {
                        &run.text[..offset_in_run]
                    } else {
                        &run.text
                    };

                    let width_before =
                        ctx.text_width(text_before_cursor, font, fstyle, size) as i32;
                    x = run.x + width_before;
                    return Some((x, line.y, line.height));
                }

                if cursor.offset > run.char_range.1 {
                    // Cursor is after this run - measure full run width
                    let (font, fstyle, size) = (run.font_type, run.font_style, run.font_size);
                    x = run.x + ctx.text_width(&run.text, font, fstyle, size) as i32;
                }
            }

            return Some((x, line.y, line.height));
        }

        // Default: top-left
        if let Some(first_line) = self.layout_lines.first() {
            Some((first_line.base_x, first_line.y, first_line.height))
        } else {
            Some((
                self.theme.padding_horizontal,
                self.theme.padding_vertical,
                self.theme.line_height,
            ))
        }
    }

    /// Determine if a point (widget coordinates) hits a checklist marker
    pub(crate) fn checklist_marker_hit(&self, x: i32, y: i32) -> Option<usize> {
        let adjusted_y = y + self.scroll_offset;
        let doc = self.editor.document();
        let blocks = doc.blocks();

        for line in &self.layout_lines {
            if adjusted_y < line.y || adjusted_y > line.y + line.height {
                continue;
            }

            for run in &line.runs {
                if let Some(checklist) = &run.checklist {
                    if checklist.box_size <= 0 {
                        continue;
                    }

                    let marker_start_x = run.x;
                    let marker_end_x = run.x + checklist.box_size;
                    // Allow a small tolerance around the marker for easier clicking
                    let tolerance = 2;
                    if x >= marker_start_x - tolerance
                        && x <= marker_end_x + tolerance
                        && let Some(block) = blocks.get(line.block_index)
                        && matches!(
                            block.block_type,
                            BlockType::ListItem {
                                checkbox: Some(_),
                                ..
                            }
                        )
                    {
                        return Some(line.block_index);
                    }
                }
            }
        }

        None
    }

    /// Convert x,y screen coordinates to document position
    pub fn xy_to_position(&self, x: i32, y: i32) -> DocumentPosition {
        let adjusted_y = y + self.scroll_offset;

        if self.layout_lines.is_empty() {
            return DocumentPosition::start();
        }

        // Helper to compute offset within a specific line based on x
        fn offset_in_line(line: &LayoutLine, x: i32) -> usize {
            let mut offset = line.char_start;
            for run in &line.runs {
                let run_end_x = run.x + run.width;
                if x >= run.x && x < run_end_x {
                    let click_offset_in_run = x - run.x;
                    let chars_in_run = run.char_range.1 - run.char_range.0;
                    if run.width > 0 && chars_in_run > 0 {
                        let char_pos = ((click_offset_in_run * chars_in_run as i32) / run.width)
                            .clamp(0, chars_in_run as i32 - 1)
                            as usize;
                        return run.char_range.0 + char_pos;
                    } else {
                        return run.char_range.0;
                    }
                }
                if x >= run_end_x {
                    offset = run.char_range.1;
                }
            }
            offset
        }

        // First try: direct hit on a line
        for line in &self.layout_lines {
            if adjusted_y >= line.y && adjusted_y < line.y + line.height {
                let block_index = line.block_index;
                let offset = offset_in_line(line, x);
                return DocumentPosition::new(block_index, offset);
            }
        }

        // No line directly under the cursor. Choose the nearest line vertically.
        // Find the previous line (the last line with y <= adjusted_y)
        let mut prev_idx: Option<usize> = None;
        for (i, line) in self.layout_lines.iter().enumerate() {
            if line.y <= adjusted_y {
                prev_idx = Some(i);
            } else {
                break;
            }
        }

        // Find the next line (first with y > adjusted_y)
        let next_idx = self
            .layout_lines
            .iter()
            .enumerate()
            .find(|(_, line)| line.y > adjusted_y)
            .map(|(i, _)| i);

        let target_idx = match (prev_idx, next_idx) {
            (Some(p), Some(n)) => {
                // Distance to bottom of previous vs top of next
                let prev_dist = adjusted_y - (self.layout_lines[p].y + self.layout_lines[p].height);
                let next_dist = self.layout_lines[n].y - adjusted_y;
                if prev_dist <= next_dist { p } else { n }
            }
            (Some(p), None) => p,
            (None, Some(n)) => n,
            (None, None) => 0,
        };

        let line = &self.layout_lines[target_idx];
        let block_index = line.block_index;
        let offset = offset_in_line(line, x);
        DocumentPosition::new(block_index, offset)
    }

    /// Set cursor visibility
    pub fn set_cursor_visible(&mut self, visible: bool) {
        self.cursor_visible = visible;
    }

    /// Get cursor visibility
    pub fn cursor_visible(&self) -> bool {
        self.cursor_visible
    }

    /// Update blink state based on elapsed ms. Returns true if visual state changed.
    pub fn tick(&mut self, ms_since_start: u64) -> bool {
        self.last_tick_ms = ms_since_start;
        // Compute a simple square-wave blink: 500ms on, 500ms off, measured
        // from the current blink anchor (reset whenever the cursor moves).
        let half_period = (self.blink_period_ms / 2).max(1);
        let elapsed = ms_since_start.saturating_sub(self.blink_anchor_ms);
        let new_on = (elapsed / half_period).is_multiple_of(2);
        if new_on != self.blink_on {
            self.blink_on = new_on;
            return true;
        }
        false
    }

    /// Restart the blink cycle so the caret is shown immediately and stays on
    /// for a full half-period. Call this whenever the cursor moves so it's
    /// always visible at its new position, regardless of the current blink
    /// phase (which might otherwise have the caret hidden right now).
    pub fn reset_blink(&mut self) {
        self.blink_anchor_ms = self.last_tick_ms;
        self.blink_on = true;
    }

    /// Find link at given widget coordinates (relative to widget, not screen)
    /// Returns ((block_index, inline_index), destination) if a link is found
    pub fn find_link_at(&self, x: i32, y: i32) -> Option<((usize, usize), String)> {
        let adjusted_y = y + self.scroll_offset;
        let adjusted_x = x;

        // Find the line at this y position
        for line in &self.layout_lines {
            if adjusted_y >= line.y && adjusted_y < line.y + line.height {
                // Find the run at this x position
                for run in &line.runs {
                    if adjusted_x >= run.x && adjusted_x < run.x + run.width {
                        // Check if this run has an inline_index pointing to a link
                        if let Some(inline_idx) = run.inline_index {
                            let doc = self.editor.document();
                            if run.block_index < doc.block_count() {
                                let block = &doc.blocks()[run.block_index];
                                if inline_idx < block.content.len()
                                    && let InlineContent::Link { link, .. } =
                                        &block.content[inline_idx]
                                {
                                    return Some((
                                        (run.block_index, inline_idx),
                                        link.destination.clone(),
                                    ));
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    /// Set hovered link (for hover highlighting)
    pub fn set_hovered_link(&mut self, link: Option<(usize, usize)>) {
        if self.hovered_link != link {
            self.hovered_link = link;
            // Don't invalidate layout, just trigger redraw
        }
    }

    /// Get hovered link
    pub fn hovered_link(&self) -> Option<(usize, usize)> {
        self.hovered_link
    }

    /// Find a link at or adjacent to the current cursor position.
    ///
    /// Treats the cursor as "inside" the link when its offset lies within the
    /// link's text range, and also when it is exactly at the start (directly
    /// before) or exactly at the end (directly after) of the link.
    ///
    /// Returns ((block_index, inline_index), destination) if a link is found.
    pub fn find_link_near_cursor(&self) -> Option<((usize, usize), String)> {
        let cursor = self.editor.cursor();
        let doc = self.editor.document();

        if cursor.block_index >= doc.block_count() {
            return None;
        }

        let block = &doc.blocks()[cursor.block_index];
        let mut pos = 0usize;

        for (inline_idx, item) in block.content.iter().enumerate() {
            let len = item.text_len();
            if let InlineContent::Link { link, .. } = item {
                let start = pos;
                let end = pos + len; // end is exclusive for text, but we allow equality for adjacency

                // Cursor is within, or exactly at start/end (adjacent)
                if cursor.offset >= start && cursor.offset <= end {
                    return Some(((cursor.block_index, inline_idx), link.destination.clone()));
                }
            }
            pos += len;
        }

        None
    }

    // ==================== Search Methods ====================

    /// Perform a case-insensitive search for the given term.
    /// Updates the internal search state with all matches found.
    /// Returns the number of matches found.
    pub fn search(&mut self, term: &str) -> usize {
        self.search_term = term.to_string();
        self.search_matches.clear();
        self.search_current_index = None;

        if term.is_empty() {
            return 0;
        }

        let term_lower = term.to_lowercase();
        let doc = self.editor.document();

        for (block_idx, block) in doc.blocks().iter().enumerate() {
            let text = block.to_plain_text();
            let text_lower = text.to_lowercase();

            // Find all occurrences in this block
            let mut search_start = 0;
            while let Some(pos) = text_lower[search_start..].find(&term_lower) {
                let start_offset = search_start + pos;
                let end_offset = start_offset + term.len();
                self.search_matches.push(SearchMatch {
                    block_index: block_idx,
                    start_offset,
                    end_offset,
                });
                search_start = start_offset + 1; // Move past this match to find overlapping matches
            }
        }

        // If we found matches, set current index to 0
        if !self.search_matches.is_empty() {
            self.search_current_index = Some(0);
        }

        self.search_matches.len()
    }

    /// Clear the search state
    pub fn clear_search(&mut self) {
        self.search_term.clear();
        self.search_matches.clear();
        self.search_current_index = None;
    }

    /// Get the current search term
    pub fn search_term(&self) -> &str {
        &self.search_term
    }

    /// Get all search matches
    pub fn search_matches(&self) -> &[SearchMatch] {
        &self.search_matches
    }

    /// Get the current match index (0-based)
    pub fn search_current_index(&self) -> Option<usize> {
        self.search_current_index
    }

    /// Get the current search match
    pub fn current_search_match(&self) -> Option<&SearchMatch> {
        self.search_current_index
            .and_then(|idx| self.search_matches.get(idx))
    }

    /// Move to the next search match. Returns true if moved.
    pub fn next_match(&mut self) -> bool {
        if self.search_matches.is_empty() {
            return false;
        }

        let next_idx = match self.search_current_index {
            Some(idx) => (idx + 1) % self.search_matches.len(),
            None => 0,
        };

        self.search_current_index = Some(next_idx);
        true
    }

    /// Move to the previous search match. Returns true if moved.
    pub fn prev_match(&mut self) -> bool {
        if self.search_matches.is_empty() {
            return false;
        }

        let prev_idx = match self.search_current_index {
            Some(idx) => {
                if idx == 0 {
                    self.search_matches.len() - 1
                } else {
                    idx - 1
                }
            }
            None => self.search_matches.len() - 1,
        };

        self.search_current_index = Some(prev_idx);
        true
    }

    /// Scroll to make the current search match visible.
    /// Should be called after search() or next_match()/prev_match().
    pub fn scroll_to_current_match(&mut self, ctx: &mut dyn DrawContext) {
        let Some(current_match) = self.current_search_match().cloned() else {
            return;
        };

        // Ensure layout is up to date
        self.layout(ctx);

        // Find the layout line containing this match
        for line in &self.layout_lines {
            if line.block_index == current_match.block_index
                && current_match.start_offset >= line.char_start
                && current_match.start_offset < line.char_end
            {
                // Calculate the target scroll position to center the match in the viewport
                let line_center_y = line.y + line.height / 2;
                let viewport_center = self.h / 2;
                let target_scroll = (line_center_y - viewport_center).max(0);

                // Clamp to valid scroll range
                let max_scroll = (self.content_height() - self.h).max(0);
                self.scroll_offset = target_scroll.min(max_scroll);
                return;
            }
        }
    }

    /// Check if a visual run intersects with any search match.
    /// Returns Some((start_offset_in_run, end_offset_in_run, is_current)) if there's an intersection.
    fn get_run_search_highlight(&self, run: &VisualRun) -> Option<(usize, usize, bool)> {
        if self.search_matches.is_empty() {
            return None;
        }

        let current_idx = self.search_current_index;

        for (idx, search_match) in self.search_matches.iter().enumerate() {
            // Check if this match is in the same block as the run
            if search_match.block_index != run.block_index {
                continue;
            }

            // Check if match intersects with run's char range
            let run_start = run.char_range.0;
            let run_end = run.char_range.1;
            let match_start = search_match.start_offset;
            let match_end = search_match.end_offset;

            // Check for intersection
            if match_end <= run_start || match_start >= run_end {
                continue;
            }

            // Calculate intersection within the run
            let start_in_run = match_start
                .saturating_sub(run_start)
                .min(run_end - run_start);
            let end_in_run = match_end.saturating_sub(run_start).min(run_end - run_start);

            if end_in_run > start_in_run {
                let is_current = current_idx == Some(idx);
                return Some((start_in_run, end_in_run, is_current));
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::draw_context::{FontStyle, FontType};
    use crate::richtext::structured_document::{
        Block, BlockType, DocumentPosition, InlineContent, StructuredDocument, TableCell, TableRow,
        TextRun,
    };

    #[derive(Default)]
    struct TestDrawContext {
        focus: bool,
        active: bool,
    }

    impl TestDrawContext {
        fn new_with_focus() -> Self {
            Self {
                focus: true,
                active: true,
            }
        }
    }

    impl DrawContext for TestDrawContext {
        fn set_color(&mut self, _color: u32) {}

        fn set_font(&mut self, _font: FontType, _style: FontStyle, _size: u8) {}

        fn draw_text(&mut self, _text: &str, _x: i32, _y: i32) {}

        fn draw_rect_filled(&mut self, _x: i32, _y: i32, _w: i32, _h: i32) {}

        fn draw_line(&mut self, _x1: i32, _y1: i32, _x2: i32, _y2: i32) {}

        fn text_width(&mut self, text: &str, _font: FontType, _style: FontStyle, size: u8) -> f64 {
            // Simplistic width model: proportional to character count and font size
            text.chars().count() as f64 * (size as f64) * 0.6
        }

        fn text_height(&self, _font: FontType, _style: FontStyle, size: u8) -> i32 {
            size as i32
        }

        fn text_descent(&self, _font: FontType, _style: FontStyle, size: u8) -> i32 {
            ((size as f32) * 0.2).round() as i32
        }

        fn push_clip(&mut self, _x: i32, _y: i32, _w: i32, _h: i32) {}

        fn pop_clip(&mut self) {}

        fn color_average(&self, c1: u32, _c2: u32, _weight: f32) -> u32 {
            c1
        }

        fn color_contrast(&self, fg: u32, _bg: u32) -> u32 {
            fg
        }

        fn color_inactive(&self, c: u32) -> u32 {
            c
        }

        fn has_focus(&self) -> bool {
            self.focus
        }

        fn is_active(&self) -> bool {
            self.active
        }
    }

    fn make_display_with_block(block: Block) -> StructuredRichDisplay {
        let mut display = StructuredRichDisplay::new(0, 0, 400, 300);
        {
            let editor = display.editor_mut();
            let mut doc = StructuredDocument::new();
            doc.add_block(block);
            *editor.document_mut() = doc;
            editor.set_cursor(DocumentPosition::new(0, 0));
        }
        display
    }

    fn make_display_with_blocks(blocks: Vec<Block>) -> StructuredRichDisplay {
        let mut display = StructuredRichDisplay::new(0, 0, 400, 300);
        {
            let editor = display.editor_mut();
            let mut doc = StructuredDocument::new();
            for b in blocks {
                doc.add_block(b);
            }
            *editor.document_mut() = doc;
            editor.set_cursor(DocumentPosition::new(0, 0));
        }
        display
    }

    fn table_block(rows: usize) -> Block {
        let rows = (0..rows)
            .map(|r| {
                TableRow::new(vec![TableCell::new(
                    false,
                    vec![InlineContent::Text(TextRun::plain(format!("r{r}")))],
                )])
            })
            .collect();
        Block::table(rows)
    }

    #[test]
    fn vertical_nav_treats_table_as_single_stop() {
        // A multi-row table produces several layout lines; Up/Down must treat
        // the whole table as one stop instead of stepping through each line.
        let mut ctx = TestDrawContext::new_with_focus();
        let mut display = make_display_with_blocks(vec![
            Block::paragraph().with_plain_text("one"),
            table_block(3),
            Block::paragraph().with_plain_text("two"),
        ]);
        // Force layout so the table contributes multiple layout lines.
        display.draw(&mut ctx);
        assert_eq!(display.editor().cursor().block_index, 0);

        // Down: land on the table once.
        display.move_cursor_visual_down(false, &mut ctx);
        assert_eq!(display.editor().cursor().block_index, 1);

        // Down again: skip the entire table to the paragraph below it.
        display.move_cursor_visual_down(false, &mut ctx);
        assert_eq!(display.editor().cursor().block_index, 2);

        // Up: back onto the table once.
        display.move_cursor_visual_up(false, &mut ctx);
        assert_eq!(display.editor().cursor().block_index, 1);

        // Up again: skip the entire table to the first paragraph.
        display.move_cursor_visual_up(false, &mut ctx);
        assert_eq!(display.editor().cursor().block_index, 0);
    }

    #[test]
    fn test_display_creation() {
        let display = StructuredRichDisplay::new(0, 0, 800, 600);
        assert_eq!(display.w(), 800);
        assert_eq!(display.h(), 600);
    }

    #[test]
    fn cursor_in_empty_blockquote_respects_indent() {
        let block = Block::new(BlockType::BlockQuote);
        let mut display = make_display_with_block(block);
        let mut ctx = TestDrawContext::new_with_focus();

        display.layout(&mut ctx);
        let (x, _, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(x, display.theme.padding_horizontal + 20);
    }

    #[test]
    fn cursor_in_empty_unordered_list_respects_content_indent() {
        let block = Block::new(BlockType::ListItem {
            ordered: false,
            number: None,
            checkbox: None,
        });
        let mut display = make_display_with_block(block);
        let mut ctx = TestDrawContext::new_with_focus();

        let bullet_width = ctx.text_width(
            "• ",
            display.theme.plain_text.font_type,
            display.theme.plain_text.font_style,
            display.theme.plain_text.font_size,
        ) as i32;
        let expected_x = display.theme.padding_horizontal
            + display.theme.plain_text.font_size as i32
            + bullet_width;

        display.layout(&mut ctx);
        let (x, _, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(x, expected_x);
    }

    #[test]
    fn cursor_in_empty_ordered_list_respects_content_indent() {
        let block = Block::new(BlockType::ListItem {
            ordered: true,
            number: Some(3),
            checkbox: None,
        });
        let mut display = make_display_with_block(block);
        let mut ctx = TestDrawContext::new_with_focus();

        let label_width = ctx.text_width(
            "3. ",
            display.theme.plain_text.font_type,
            display.theme.plain_text.font_style,
            display.theme.plain_text.font_size,
        ) as i32;
        let expected_x = display.theme.padding_horizontal
            + display.theme.plain_text.font_size as i32
            + label_width;

        display.layout(&mut ctx);
        let (x, _, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(x, expected_x);
    }

    #[test]
    fn cursor_in_empty_checklist_respects_content_indent() {
        let block = Block::new(BlockType::ListItem {
            ordered: false,
            number: None,
            checkbox: Some(false),
        });
        let mut display = make_display_with_block(block);
        let mut ctx = TestDrawContext::new_with_focus();

        let mut checkbox_size = (display.theme.plain_text.font_size as i32).saturating_sub(4);
        if checkbox_size < 8 {
            checkbox_size = 8;
        }
        if checkbox_size > display.theme.line_height {
            checkbox_size = display.theme.line_height;
        }

        let mut space_width = ctx.text_width(
            " ",
            display.theme.plain_text.font_type,
            display.theme.plain_text.font_style,
            display.theme.plain_text.font_size,
        ) as i32;
        if space_width < 4 {
            space_width = 4;
        }

        let expected_x = display.theme.padding_horizontal
            + display.theme.plain_text.font_size as i32
            + checkbox_size
            + space_width;

        display.layout(&mut ctx);
        let (x, _, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(x, expected_x);
    }

    #[test]
    fn cursor_in_empty_code_block_respects_indent() {
        let block = Block::new(BlockType::CodeBlock { language: None });
        let mut display = make_display_with_block(block);
        let mut ctx = TestDrawContext::new_with_focus();

        display.layout(&mut ctx);
        let (x, _, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(x, display.theme.padding_horizontal + 10);
    }

    #[test]
    fn trailing_hard_break_creates_empty_visual_line() {
        let mut block = Block::paragraph();
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Hello")));
        block.content.push(InlineContent::HardBreak);

        let mut display = make_display_with_block(block);

        let mut layout_ctx = TestDrawContext::new_with_focus();
        display.layout(&mut layout_ctx);

        assert_eq!(
            display.layout_lines.len(),
            2,
            "Trailing hard break should produce two visual lines"
        );

        let end_offset = display.editor().document().blocks()[0].text_len();
        {
            let editor = display.editor_mut();
            editor.set_cursor(DocumentPosition::new(0, end_offset));
        }

        let trailing_line = display
            .layout_lines
            .last()
            .expect("Expected trailing layout line for hard break");
        assert_eq!(trailing_line.char_start, end_offset);
        assert_eq!(trailing_line.char_end, end_offset);

        let mut ctx = TestDrawContext::new_with_focus();
        let (cursor_x, cursor_y, _) = display
            .get_cursor_visual_position(&mut ctx)
            .expect("Cursor position should resolve with trailing hard break");
        assert_eq!(cursor_x, trailing_line.base_x);
        assert_eq!(cursor_y, trailing_line.y);
    }

    #[test]
    fn cursor_home_end_respect_visual_lines() {
        let block = Block::paragraph().with_plain_text(
            "This visual line wrapping test ensures Home and End stay within wraps.",
        );
        let mut display = make_display_with_block(block);
        display.resize(0, 0, 160, 200);

        let mut layout_ctx = TestDrawContext::new_with_focus();
        display.layout(&mut layout_ctx);

        assert!(
            display.layout_lines.len() >= 2,
            "Expected wrapped layout to produce multiple visual lines"
        );

        let first_line_start = display.layout_lines[0].char_start;
        let first_line_end = display.layout_lines[0].char_end;
        let second_line_start = display.layout_lines[1].char_start;
        let first_line_base_x = display.layout_lines[0].base_x;
        let first_line_y = display.layout_lines[0].y;
        let second_line_y = display.layout_lines[1].y;
        let second_line_base_x = display.layout_lines[1].base_x;

        {
            let editor = display.editor_mut();
            editor.set_cursor(DocumentPosition::new(0, first_line_start));
        }

        let mut ctx = TestDrawContext::new_with_focus();
        let mut expected_end_offset = first_line_end;
        while expected_end_offset > first_line_start
            && !display.offset_belongs_to_line(0, expected_end_offset)
        {
            expected_end_offset -= 1;
        }

        display.move_cursor_visual_line_end_precise(false, &mut ctx);
        assert_eq!(display.editor().cursor().offset, expected_end_offset);
        let (end_x, end_y, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(end_y, first_line_y);
        assert!(end_x > first_line_base_x);

        {
            let editor = display.editor_mut();
            editor.move_cursor_right();
        }
        let (wrapped_x, wrapped_y, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(display.editor().cursor().offset, second_line_start);
        assert_eq!(wrapped_y, second_line_y);
        assert_eq!(wrapped_x, second_line_base_x);

        let second_line_end = display.layout_lines[1].char_end;
        let sample_offset = (second_line_start + 3).min(second_line_end);
        {
            let editor = display.editor_mut();
            editor.set_cursor(DocumentPosition::new(0, sample_offset));
        }

        display.move_cursor_visual_line_start(false, &mut ctx);
        assert_eq!(display.editor().cursor().offset, second_line_start);
        let (start_x, start_y, _) = display.get_cursor_visual_position(&mut ctx).unwrap();
        assert_eq!(start_y, second_line_y);
        assert_eq!(start_x, second_line_base_x);
    }

    #[test]
    fn hard_break_blank_line_has_nonzero_offset() {
        let mut display = StructuredRichDisplay::new(0, 0, 400, 200);
        let mut doc = StructuredDocument::new();
        let mut block = Block::paragraph();
        block
            .content
            .push(InlineContent::Text(TextRun::plain("Hello")));
        block.content.push(InlineContent::HardBreak);
        block.content.push(InlineContent::HardBreak);
        block
            .content
            .push(InlineContent::Text(TextRun::plain("World")));
        doc.add_block(block);

        {
            let editor = display.editor_mut();
            *editor.document_mut() = doc;
            editor.set_cursor(DocumentPosition::new(0, 0));
        }

        let mut ctx = TestDrawContext::new_with_focus();
        display.layout_valid = false;
        display.layout(&mut ctx);

        assert!(
            display.layout_lines.len() >= 3,
            "expected at least three visual lines, got {}",
            display.layout_lines.len()
        );

        let zero_len_offsets: Vec<usize> = display
            .layout_lines
            .iter()
            .filter(|line| line.char_start == line.char_end)
            .map(|line| line.char_start)
            .collect();

        assert!(
            zero_len_offsets.iter().any(|&offset| offset > 0),
            "expected a zero-length line with non-zero offset, got offsets {:?}",
            zero_len_offsets
        );
    }
}