k2f_idml 0.3.3

K2F lock → IDML exporter
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
use crate::ir::{PageElement, TextAlign, TextBox};
use k2f_core::{Pt, Rect};

/// Neighbor gap (millipt) that unlimited WidthOnly would eat.
/// 8pt pill stacks collide; a 12pt masthead gap still has room to grow.
const GROW_ROOM: i128 = 10_000;
/// NoBreak overset hides the whole line if we are even 1pt short — use the
/// full gap as pad. WidthOnly is still off so growth cannot cross the sibling.
const GAP_KEEP: i128 = 0;
/// Pad below this: host metrics cannot grow, so NoBreak would overset the
/// rest of the story (flush column body beside the next card). Drop NoBreak
/// and HeightOnly-grow instead of hiding lines.
const FLUSH_PAD: i128 = 2_000;
/// Fallback extra millipt when page width is unknown (`clamp_width_autosize`
/// tests): grow a little so host metrics are not 1pt overset.
const HOST_LINE_PAD: i128 = 24_000;
/// Skip the margin-grow path if the open side is thinner than this — wrapping
/// is then the only way leftover glyphs stay visible.
const MIN_OPEN: i128 = 4_000;
/// Lock box center within this many millipt of page center — shrink-wrapped
/// invitation/card lines centered on the sheet.
const PAGE_CENTER_TOL: i128 = 2_000;
/// Verified-badge / avatar-icon width. A 6pt gap to a 14pt icon is not a
/// column sibling: WidthOnly only grows the host-metrics delta. Padding that
/// gap and dropping WidthOnly leaves NoBreak 1pt short, and InDesign hides
/// the whole line. Pills/cards (50pt+) still clamp — see adjacent_label.
const SMALL_SIBLING: i128 = 40_000;
/// Hairline rules / column gutters are not icons. Treating a 0.6pt divider
/// as SMALL_SIBLING enabled WidthOnly and recentered left card columns.
const MIN_ICON_W: i128 = 4_000;
/// Left 2-line display titles wider than this with loose ink keep HeightOnly so
/// WidthOnly shrink does not re-anchor the block toward center.
const WIDE_LOOSE_TITLE_W: i128 = 400_000;
/// Single-line NoBreak without WidthOnly: only auto-enable WidthOnly below
/// this frame width. Wide loose frames (author lines) must not re-anchor.
const NARROW_NOBREAK_W: i128 = 300_000;
/// Side-neighbor Y overlap below this is hairline (shadow-expanded rasters
/// sitting 0.05pt under a subtitle). Treating that as a column sibling
/// blocks open_right, and NoBreak oversets (hides) the line in InDesign.
const Y_TOUCH: i128 = 2_000;

/// NoBreak without WidthOnly oversets (hides) the whole story when host
/// metrics are even 1pt wider than the lock box — 2-line titles, tracked
/// labels. Give those frames WidthOnly first; `clamp_width_autosize` still
/// caps growth against siblings.
pub(crate) fn apply(elements: &mut [PageElement], page_w: i128) {
    enable_widthonly_beside_icons(elements);
    ensure_nobreak_width(elements, page_w);
    clamp_width_autosize_on(elements, Some(page_w));
    repair_nobreak_overset(elements);
    drop_tracking_on_nobreak_multiline(elements);
    pin_lock_height_on_column_body(elements);
    disable_widthonly_inside_cards(elements);
}

/// Column wrap is lock-positioned in a vertical stack. HeightOnly shrinks
/// when InDesign wraps to fewer lines and inflates the gap to the next
/// frame (letter body, paper paragraphs). Keep the lock box. Author `\n`
/// stacks still HeightOnly so affiliation/title lines are not clipped.
fn pin_lock_height_on_column_body(elements: &mut [PageElement]) {
    for el in elements {
        let PageElement::TextBox(tb) = el else {
            continue;
        };
        if tb.vert_center {
            tb.autosize_height = false;
            continue;
        }
        if tb.semantic_newlines {
            continue;
        }
        if tb.lock_line_count >= 3 || tb.full_width_lock_line {
            tb.autosize_height = false;
        }
    }
}

/// Host Roboto + positive Tracking on glued lock lines oversets (hides) the
/// whole story when slack is tight. Drop tracking on multi-line NoBreak frames
/// so InDesign keeps every lock line visible.
fn drop_tracking_on_nobreak_multiline(elements: &mut [PageElement]) {
    for el in elements {
        let PageElement::TextBox(tb) = el else {
            continue;
        };
        if !tb.no_break {
            continue;
        }
        // Padded banners/pills: lock tracking is the designed inset fill, not overset.
        if tb.vert_center || tb.inset_left > 1.0 {
            continue;
        }
        let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
        let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
        if !multi && nbreaks == 0 {
            continue;
        }
        for run in &mut tb.runs {
            if run.tracking > 0 {
                run.tracking = 0;
            }
        }
    }
}

/// Tight NoBreak display lines beside a verified badge / avatar icon need
/// WidthOnly so host Roboto does not overset and hide the whole story.
fn enable_widthonly_beside_icons(elements: &mut [PageElement]) {
    let rects: Vec<Rect> = elements.iter().map(|el| el.rect().clone()).collect();
    for i in 0..elements.len() {
        let PageElement::TextBox(tb) = &mut elements[i] else {
            continue;
        };
        if !tb.no_break || tb.autosize_width {
            continue;
        }
        let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
        let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
        if multi || nbreaks > 0 {
            continue;
        }
        // Same-x column stack (card/grid copy) must keep the lock width.
        // WidthOnly re-anchors about ItemTransform and left ink looks centered.
        if stacked_lock_column_sibling(&rects[i], &rects, i) {
            continue;
        }
        if small_side_blocker(&rects[i], &rects, i, &tb.autosize_refer).is_some_and(is_icon_w) {
            tb.autosize_width = true;
            tb.autosize_no_wrap = true;
        }
    }
}

fn ensure_nobreak_width(elements: &mut [PageElement], page_w: i128) {
    let rects: Vec<Rect> = elements.iter().map(|el| el.rect().clone()).collect();
    for i in 0..elements.len() {
        let PageElement::TextBox(tb) = &elements[i] else {
            continue;
        };
        if !tb.no_break {
            continue;
        }
        // Wide left-aligned frames (authors, ABSTRACT, 2-line display titles
        // that do not fill the box) must not WidthOnly-shrink: InDesign
        // re-anchors about ItemTransform and the line looks centered.
        // Tight lock ink already set autosize_width in textbox_from_draw
        // (48pt slack). Forcing it here would shrink a loose frame. Isolated
        // tight leads still WidthOnly-grow about the center and walk off the
        // left margin — expand the lock rect into the open right instead.
        // Column siblings stay WidthOnly so clamp can wrap in the lock column.
        if matches!(tb.align, TextAlign::Left) {
            if stacked_graphic_caption(&rects[i], &rects, i)
                && !stacked_lock_column_sibling(&rects[i], &rects, i)
            {
                if let PageElement::TextBox(tb) = &mut elements[i] {
                    tb.autosize_width = true;
                    tb.autosize_no_wrap = true;
                    tb.autosize_refer = "CenterPoint";
                }
                continue;
            }
            let stacked_col = stacked_lock_column_sibling(&rects[i], &rects, i);
            let side_col = column_sibling(&rects[i], &rects, i);
            let want_width = tb.autosize_width;
            let full_width = tb.full_width_lock_line;
            let refer = tb.autosize_refer;
            let no_break = tb.no_break;
            let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
            let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
            // Ink-hug card labels (attendee names): keep WidthOnly so host
            // metrics / synthetic stroke cannot overset. Do this before the
            // side-column lock-width pin, which is meant for full-width copy.
            // Parent-wider-than-child alone is not a hug: footer/column lines
            // inside a card have leftover right slack and WidthOnly recenters.
            if want_width && full_width && hug_label_in_wide_parent(&rects[i], &rects, i) {
                continue;
            }
            // Hug title inside a padded card: keep the lock box. open_right
            // would eat the card inset and WidthOnly would recenter the ink.
            // Ink-hug badge labels (dates/names in a pill) fill the frame;
            // dropping WidthOnly then oversets and InDesign hides the story.
            if want_width && padded_inside_card(&rects[i], &rects, i) {
                let hug = tb.full_width_lock_line && tb.lock_line_count <= 1;
                if !hug {
                    if let PageElement::TextBox(tb) = &mut elements[i] {
                        tb.autosize_width = false;
                        tb.autosize_no_wrap = false;
                    }
                }
                continue;
            }
            // Same-left stack: WidthOnly recenters hug lines (eyebrow/title,
            // card labels, checklist). Isolated same-width signatures without
            // a side column keep WidthOnly for host-metric slack.
            if want_width && stacked_col {
                let mixed = stacked_mixed_width_sibling(&rects[i], &rects, i);
                let wide = rects[i].width.0 > NARROW_NOBREAK_W;
                let hug = tb.full_width_lock_line && tb.lock_line_count <= 1;
                // Loose leftover slack: WidthOnly shrinks about ItemTransform
                // and left column copy looks centered (schedule times, venue).
                if !hug {
                    if let PageElement::TextBox(tb) = &mut elements[i] {
                        tb.autosize_width = false;
                        tb.autosize_no_wrap = false;
                        if side_col || mixed || wide {
                            let extra = open_right(&rects[i], &rects, i, Some(page_w));
                            if extra >= MIN_OPEN {
                                tb.rect.width = Pt(tb.rect.width.0 + extra);
                            }
                        }
                    }
                }
            }
            // Single-line hug next to a column (not a grow-side icon): keep
            // the lock left edge. Multi-line still goes through clamp/wrap.
            if want_width && side_col && !stacked_col && !multi && nbreaks == 0 {
                let beside_icon =
                    small_side_blocker(&rects[i], &rects, i, refer).is_some_and(is_icon_w);
                if !beside_icon {
                    if let PageElement::TextBox(tb) = &mut elements[i] {
                        tb.autosize_width = false;
                        tb.autosize_no_wrap = false;
                    }
                }
            }
            if want_width && !side_col {
                // Ink-hug label in a wide card: keep WidthOnly. Growing into
                // open_right eats the card inset; dropping WidthOnly oversets.
                if full_width && hug_label_in_wide_parent(&rects[i], &rects, i) {
                    continue;
                }
                if no_break
                    && !multi
                    && nbreaks == 0
                    && small_side_blocker(&rects[i], &rects, i, refer).is_some_and(is_icon_w)
                {
                    continue;
                }
                if stacked_lock_column_sibling(&rects[i], &rects, i)
                    || stacked_right_edge_sibling(&rects[i], &rects, i)
                {
                    // Hug stacks that fill the lock may WidthOnly-grow. Loose
                    // left ink must keep the lock box — open_right would walk
                    // the longest line past shorter siblings.
                    continue;
                }
                if is_page_centered(&rects[i], page_w) && full_width {
                    if let PageElement::TextBox(tb) = &mut elements[i] {
                        apply_page_center_autosize(tb);
                    }
                    continue;
                }
                let extra = open_right(&rects[i], &rects, i, Some(page_w));
                if let PageElement::TextBox(tb) = &mut elements[i] {
                    tb.autosize_width = false;
                    tb.autosize_no_wrap = false;
                    if extra >= MIN_OPEN {
                        tb.rect.width = Pt(tb.rect.width.0 + extra);
                    }
                    // textbox_from_draw sets autosize_height=false whenever
                    // autosize_width was true. Restoring HeightOnly here keeps
                    // multi-line NoBreak body from oversetting in InDesign.
                    if (multi || nbreaks >= 1) && !tb.vert_center {
                        tb.autosize_height = true;
                    }
                }
            }
            if let PageElement::TextBox(tb) = &mut elements[i] {
                let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
                let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
                // Use the live rect: open_right above may have widened the frame;
                // a stale snapshot still looks "narrow" and wrongly re-enables
                // WidthOnly (letter recipient / closing lines center in InDesign).
                let live_rect = tb.rect.clone();
                repair_left_nobreak(tb, &live_rect, &rects, i, page_w, multi, nbreaks);
            }
            continue;
        }
        // Full-width paper titles with author `\n`: WidthOnly + CenterPoint
        // concatenates semantic paragraphs onto one clipped line in InDesign.
        // HeightOnly + drop NoBreak lets each author line stack using Leading.
        if tb.semantic_newlines
            && tb.lock_line_count >= 2
            && matches!(tb.align, TextAlign::Center)
            && rects[i].width.0 > WIDE_LOOSE_TITLE_W
            && !column_sibling(&rects[i], &rects, i)
        {
            if let PageElement::TextBox(tb) = &mut elements[i] {
                tb.autosize_width = false;
                tb.autosize_no_wrap = false;
                tb.autosize_height = true;
                drop_nobreak(tb);
            }
            continue;
        }
        if tb.autosize_width {
            continue;
        }
        // Center/Right single-line without HeightOnly: WidthOnly-grow so host
        // metrics do not overset and hide the story.
        let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
        if !tb.autosize_height && nbreaks == 0 && !tb.vert_center {
            if let PageElement::TextBox(tb) = &mut elements[i] {
                tb.autosize_width = true;
                tb.autosize_no_wrap = true;
                tb.autosize_height = false;
            }
            continue;
        }
        // UseNoLineBreaks on 2+ lock lines sizes the frame as one unwrapped
        // paragraph. Beside a column sibling that explodes through the gutter.
        if nbreaks >= 1 && column_sibling(&rects[i], &rects, i) {
            continue;
        }
        if let PageElement::TextBox(tb) = &mut elements[i] {
            tb.autosize_width = true;
            // Respect `\n` when sizing: longest lock line, not the unwrapped
            // paragraph. Single-line NoBreak still uses UseNoLineBreaks.
            tb.autosize_no_wrap = nbreaks == 0;
            tb.autosize_height = false;
        }
    }
}

/// Left NoBreak frames that never got WidthOnly: host metrics overset the lock
/// box and InDesign hides the story (letter recipient lines, body paragraphs).
fn repair_left_nobreak(
    tb: &mut crate::ir::TextBox,
    me: &Rect,
    rects: &[Rect],
    my_i: usize,
    page_w: i128,
    multi: bool,
    nbreaks: usize,
) {
    if !tb.no_break {
        return;
    }
    if tb.autosize_height && !tb.autosize_width && tb.lock_line_count >= 2 {
        if (multi || nbreaks >= 1) && !column_sibling(me, rects, my_i) && !tb.semantic_newlines {
            if should_widthonly_two_line_nobreak(tb, nbreaks) {
                tb.autosize_width = true;
                tb.autosize_no_wrap = false;
                tb.autosize_height = false;
            } else {
                drop_nobreak(tb);
                for run in &mut tb.runs {
                    if run.tracking > 0 {
                        run.tracking = 0;
                    }
                }
            }
        }
        return;
    }
    if tb.autosize_width || tb.autosize_height || multi || nbreaks > 0 {
        return;
    }
    if me.width.0 >= NARROW_NOBREAK_W {
        // Wide hug one-liners skip WidthOnly so the frame does not re-anchor,
        // but still need host-metric room when lock ink fills the box.
        // Same-width stacks (signature name/title) keep the lock box.
        // Mixed-width stacks (hero lead under a shorter title) must still
        // grow into open_right: NoBreak + lock width oversets and InDesign
        // hides the whole line.
        if tb.full_width_lock_line && tb.lock_line_count <= 1 {
            let same_width_stack = stacked_lock_column_sibling(me, rects, my_i)
                && !stacked_mixed_width_sibling(me, rects, my_i);
            if !same_width_stack && !stacked_right_edge_sibling(me, rects, my_i) {
                let extra = open_right(me, rects, my_i, Some(page_w));
                if extra >= MIN_OPEN {
                    tb.rect.width = Pt(tb.rect.width.0 + extra);
                } else {
                    drop_nobreak(tb);
                }
            }
        }
        return;
    }
    if stacked_lock_column_sibling(me, rects, my_i) {
        // Same x/width stack: growing one line past the others walks the
        // right edge (signature name/title/org). Keep the lock box.
        // Ink-hug badge labels still need WidthOnly: host metrics overset
        // a 40pt date pill and InDesign hides the whole line.
        if tb.full_width_lock_line && tb.lock_line_count <= 1 && !tb.autosize_height {
            tb.autosize_width = true;
            tb.autosize_no_wrap = true;
        }
        return;
    }
    if stacked_right_edge_sibling(me, rects, my_i) {
        // Page-midline is not centered text: a middle card/column can sit on
        // the sheet center with flush-left ink (3.8×). Grow into open_right
        // instead of flipping Justification to CenterAlign.
        let extra = open_right(me, rects, my_i, Some(page_w));
        if extra >= MIN_OPEN {
            tb.rect.width = Pt(tb.rect.width.0 + extra);
        } else {
            drop_nobreak(tb);
        }
        return;
    }
    let extra = open_right(me, rects, my_i, Some(page_w));
    if extra >= MIN_OPEN {
        tb.rect.width = Pt(tb.rect.width.0 + extra);
    }
}

/// Final pass: HeightOnly + NoBreak without WidthOnly still oversets in InDesign
/// when lock-pinned lines are wider than host metrics expect.
fn repair_nobreak_overset(elements: &mut [PageElement]) {
    let rects: Vec<Rect> = elements.iter().map(|el| el.rect().clone()).collect();
    for i in 0..elements.len() {
        let PageElement::TextBox(tb) = &mut elements[i] else {
            continue;
        };
        if !tb.no_break || tb.autosize_width {
            continue;
        }
        let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
        let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
        // Author affiliation / title stacks: semantic `\n` paragraphs with
        // HeightOnly. NoBreak on every paragraph oversets and hides the story.
        // A side column (hero image) is not a reason to keep NoBreak — the
        // designed `\n` already splits the lines, and InDesign still hides
        // the whole story when NoBreak cannot compose inside the lock width.
        if tb.semantic_newlines && tb.autosize_height && tb.lock_line_count >= 2 {
            drop_nobreak(tb);
            continue;
        }
        if tb.autosize_height
            && tb.lock_line_count >= 2
            && (multi || nbreaks >= 1)
            && !column_sibling(&rects[i], &rects, i)
            && !tb.semantic_newlines
            && !should_widthonly_two_line_nobreak(tb, nbreaks)
        {
            drop_nobreak(tb);
            for run in &mut tb.runs {
                if run.tracking > 0 {
                    run.tracking = 0;
                }
            }
        }
    }
}

/// WidthOnly has no max: a shrink-wrapped label beside a badge grows through
/// the sibling. NoBreak + a too-tight lock box oversets (hides) the whole
/// line. Cap growth by expanding the lock rect into the gap instead.
#[cfg_attr(not(test), allow(dead_code))]
pub(crate) fn clamp_width_autosize(elements: &mut [PageElement]) {
    clamp_width_autosize_on(elements, None);
}

fn clamp_width_autosize_on(elements: &mut [PageElement], page_w: Option<i128>) {
    let rects: Vec<Rect> = elements.iter().map(|el| el.rect().clone()).collect();
    for i in 0..elements.len() {
        let PageElement::TextBox(tb) = &elements[i] else {
            continue;
        };
        if !tb.autosize_width {
            continue;
        }
        let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
        let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
        let me = &rects[i];
        // GROW_ROOM (10pt) misses a 12–16pt two-column gutter. WidthOnly then
        // expands about ItemTransform and the body eats the sidenote (and vice
        // versa). Any-distance side sibling: stay in the lock column.
        if (multi || nbreaks >= 1) && column_sibling(me, &rects, i) {
            // Extra wrap + HeightOnly overprints a stacked sibling a few pt
            // below (grid card body → CTA). Keep lock lines glued and grow
            // into the open right margin instead of dropping NoBreak.
            let stacked = nearest_below_gap(me, &rects, i).is_some_and(|g| g < GROW_ROOM);
            if stacked {
                let extra = open_right(me, &rects, i, page_w);
                if let PageElement::TextBox(tb) = &mut elements[i] {
                    // Grid column copy on the page midline stays left-aligned;
                    // page_center_autosize is for isolated centered pills only.
                    tb.autosize_width = false;
                    tb.autosize_no_wrap = false;
                    tb.autosize_height = false;
                    if extra >= MIN_OPEN {
                        tb.rect.width = Pt(tb.rect.width.0 + extra);
                    }
                }
                continue;
            }
            if let PageElement::TextBox(tb) = &mut elements[i] {
                tb.autosize_width = false;
                tb.autosize_no_wrap = false;
                tb.autosize_height = true;
                if tb.no_break {
                    drop_nobreak(tb);
                }
            }
            continue;
        }
        let (grow_left, grow_right) = grow_dirs(tb.autosize_refer);
        // Measure both sides even when we only grow one way: host WidthOnly
        // can still expand about ItemTransform and collide with a flush
        // neighbor (KEYWORDS: vs the list).
        let right_gap = nearest_right_gap(me, &rects, i);
        let left_gap = nearest_left_gap(me, &rects, i);
        let grow_right_gap = if grow_right { right_gap } else { None };
        let grow_left_gap = if grow_left { left_gap } else { None };
        let other_flush = match (grow_left, grow_right) {
            // Any close neighbor on the non-grow side: WidthOnly can still
            // expand about the frame center and collide (5pt KEYWORDS gap).
            (false, true) => left_gap.is_some(),
            (true, false) => right_gap.is_some(),
            _ => false,
        };
        if grow_right_gap.is_none() && grow_left_gap.is_none() && !other_flush {
            continue;
        }
        // Single lock line beside a small icon: keep WidthOnly. The 6pt gap
        // to a verified badge used to disable it, pad 6pt, and keep NoBreak
        // — host Roboto then overset and hid "KRONOS // NIGHTFALL".
        if tb.no_break && !multi && nbreaks == 0 {
            if small_side_blocker(me, &rects, i, &tb.autosize_refer).is_some_and(is_icon_w) {
                continue;
            }
            if stacked_lock_column_sibling(me, &rects, i)
                || stacked_right_edge_sibling(me, &rects, i)
            {
                continue;
            }
        }
        if let PageElement::TextBox(tb) = &mut elements[i] {
            tb.autosize_width = false;
            tb.autosize_no_wrap = false;
            // Positive Tracking is 1/1000 em extra per gap. On a shrink-wrapped
            // left label it is why the line is wider than the lock box and runs
            // through the badge. Isolated labels keep tracking + WidthOnly.
            let mut pad = 0i128;
            if grow_right && !grow_left {
                for run in &mut tb.runs {
                    if run.tracking > 0 {
                        run.tracking = 0;
                    }
                }
                if let Some(gap) = grow_right_gap {
                    pad = pad_for_gap(gap);
                    tb.rect.width = Pt(tb.rect.width.0 + pad);
                }
            } else if grow_left && !grow_right {
                for run in &mut tb.runs {
                    if run.tracking > 0 {
                        run.tracking = 0;
                    }
                }
                if let Some(gap) = grow_left_gap {
                    pad = pad_for_gap(gap);
                    tb.rect.x = Pt(tb.rect.x.0 - pad);
                    tb.rect.width = Pt(tb.rect.width.0 + pad);
                }
            } else {
                pad = match (grow_left_gap, grow_right_gap) {
                    (Some(l), Some(r)) => pad_for_gap(l).min(pad_for_gap(r)),
                    (Some(l), None) => pad_for_gap(l),
                    (None, Some(r)) => pad_for_gap(r),
                    (None, None) => 0,
                };
            }
            // Flush sibling: expanding 0pt leaves NoBreak lines one host-em
            // over-wide, and InDesign oversets the rest of the story. Multi-line
            // lock-pinned body is the same even with an 8pt pad — that slack
            // fits a short label, not a full-width paragraph. Allow wrap
            // (unglue NBSP) and HeightOnly so leftover words stay visible.
            let multi = tb.runs.iter().any(|r| r.text.contains('\n'));
            if tb.no_break && (pad < FLUSH_PAD || multi || other_flush) {
                let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
                // Single lock line (folio `Page 1 of 2`, article title beside a
                // badge): wrapping overprints the next row. Grow into the open
                // page margin on the unconstrained side and keep NoBreak. Do
                // not WidthOnly — ItemTransform still expands about the center
                // and would eat the pinned sibling. Multi-line lock body still
                // wraps (KEYWORDS, clause columns).
                let single = !multi && nbreaks == 0;
                if single {
                    let extra = if grow_right && !grow_left {
                        open_right(&tb.rect, &rects, i, page_w)
                    } else if grow_left && !grow_right {
                        open_left(&tb.rect, &rects, i, page_w)
                    } else {
                        0
                    };
                    if extra >= MIN_OPEN {
                        if page_w.is_some_and(|pw| is_page_centered(&tb.rect, pw))
                            && tb.full_width_lock_line
                            && !column_sibling(&tb.rect, &rects, i)
                        {
                            apply_page_center_autosize(tb);
                        } else if grow_right && !grow_left {
                            tb.rect.width = Pt(tb.rect.width.0 + extra);
                        } else if grow_left && !grow_right {
                            tb.rect.x = Pt(tb.rect.x.0 - extra);
                            tb.rect.width = Pt(tb.rect.width.0 + extra);
                        }
                        continue;
                    }
                }
                if should_widthonly_two_line_nobreak(tb, nbreaks) {
                    tb.autosize_width = true;
                    tb.autosize_no_wrap = false;
                    tb.autosize_height = false;
                } else {
                    // 2-line display breaks (title / DEPTHS) stay. Column wrap
                    // (full-width or 3+ lock lines) collapses so leftover words
                    // do not wrap *plus* the forced lock break.
                    drop_nobreak(tb);
                    tb.autosize_height = true;
                }
            }
        }
    }
}

fn pad_for_gap(gap: i128) -> i128 {
    if gap <= GAP_KEEP {
        0
    } else {
        gap - GAP_KEEP
    }
}

fn is_page_centered(me: &Rect, page_w: i128) -> bool {
    // Full-width column bodies share the page midpoint but are not centered pills.
    if me.width.0 * 10 >= page_w * 8 {
        return false;
    }
    let cx = me.x.0 + me.width.0 / 2;
    (cx - page_w / 2).abs() <= PAGE_CENTER_TOL
}

/// Shrink-wrapped lines centered on the page: ink fills the lock box so
/// alignment inference says Left, but the box itself is midline. Asymmetric
/// open_right expansion walks ItemTransform off center in InDesign.
fn apply_page_center_autosize(tb: &mut TextBox) {
    tb.align = TextAlign::Center;
    tb.autosize_refer = "CenterPoint";
    tb.autosize_width = true;
    tb.autosize_no_wrap = true;
    tb.autosize_height = false;
}

/// Two-line NoBreak display copy: keep WidthOnly so host metrics size to the
/// longest lock line instead of HeightOnly re-wrapping inside a line.
fn should_widthonly_two_line_nobreak(tb: &TextBox, nbreaks: usize) -> bool {
    if tb.lock_line_count != 2 || nbreaks != tb.lock_line_count.saturating_sub(1) {
        return false;
    }
    // Wrapped bibliography / column body: first lock line fills the frame.
    // WidthOnly re-anchors and misaligns the entry (academic-serif-classic ref3).
    if tb.full_width_lock_line {
        return false;
    }
    if !tb.semantic_newlines {
        return true;
    }
    // Author `\n` in a wide frame must not WidthOnly-shrink (re-anchors centered).
    tb.rect.width.0 <= WIDE_LOOSE_TITLE_W
}

/// Drop NoBreak and flatten lock-pinned wrap breaks so the host reflows at
/// the actual frame width. Semantic `\n` (titles, seal stacks) stay.
fn drop_nobreak(tb: &mut TextBox) {
    let nbreaks: usize = tb.runs.iter().map(|r| r.text.matches('\n').count()).sum();
    tb.no_break = false;
    unglue_nbsp(&mut tb.runs);
    if should_collapse_lock_newlines(tb, nbreaks) {
        collapse_lock_newlines(&mut tb.runs);
    }
}

/// Flatten lock-pinned wrap breaks when the host is allowed to reflow.
/// Keep a designed 2-line display break (title / DEPTHS). Collapse column
/// wrap — including left-aligned body whose `\n` count matches lock lines —
/// so a narrower IDML frame does not wrap *and* keep the old break points.
fn should_collapse_lock_newlines(tb: &TextBox, nbreaks: usize) -> bool {
    if tb.semantic_newlines || nbreaks == 0 {
        return false;
    }
    if has_midword_newline(&tb.runs) {
        return false;
    }
    if nbreaks == 1 && !tb.full_width_lock_line {
        return false;
    }
    true
}

/// A newline on a spaceless line is a pinned mid-word wrap.
/// Column wrap like abyss/extinguishes has spaces on the previous line.
fn has_midword_newline(runs: &[crate::ir::TextRun]) -> bool {
    let full: String = runs.iter().map(|r| r.text.as_str()).collect();
    let chars: Vec<char> = full.chars().collect();
    let mut line_start = 0usize;
    for (i, &ch) in chars.iter().enumerate() {
        if ch != '\n' {
            continue;
        }
        let mid = i > 0
            && i + 1 < chars.len()
            && !chars[i - 1].is_whitespace()
            && !chars[i + 1].is_whitespace()
            && !chars[line_start..i].iter().any(|c| c.is_whitespace());
        if mid {
            return true;
        }
        line_start = i + 1;
    }
    false
}

fn unglue_nbsp(runs: &mut [crate::ir::TextRun]) {
    for run in runs {
        if run.auto_page_number {
            continue;
        }
        if run.text.contains('\u{00A0}') {
            run.text = run.text.replace('\u{00A0}', " ");
        }
    }
}

fn collapse_lock_newlines(runs: &mut [crate::ir::TextRun]) {
    for run in runs.iter_mut() {
        if run.auto_page_number {
            continue;
        }
        if run.text.contains('\n') {
            run.text = run.text.replace('\n', " ");
        }
    }
    // `insert_lock_breaks` puts `\n` before the next line's first glyph, so
    // "lock \ntypefaces" is common. Replacing `\n` with a space would leave
    // a double word-gap in the reflowed paragraph.
    let mut prev_space = false;
    for run in runs.iter_mut() {
        if run.auto_page_number {
            continue;
        }
        let mut out = String::with_capacity(run.text.len());
        for ch in run.text.chars() {
            let is_space = ch == ' ' || ch == '\u{00A0}';
            if is_space {
                if prev_space {
                    continue;
                }
                out.push(' ');
                prev_space = true;
            } else {
                prev_space = false;
                out.push(ch);
            }
        }
        run.text = out;
    }
}

fn small_side_blocker(me: &Rect, rects: &[Rect], my_i: usize, refer: &str) -> Option<i128> {
    let (grow_left, grow_right) = grow_dirs(refer);
    match (grow_left, grow_right) {
        (false, true) => nearest_right_blocker_w(me, rects, my_i),
        (true, false) => nearest_left_blocker_w(me, rects, my_i),
        (true, true) => nearest_right_blocker_w(me, rects, my_i)
            .or_else(|| nearest_left_blocker_w(me, rects, my_i)),
        (false, false) => None,
    }
}

fn grow_dirs(refer: &str) -> (bool, bool) {
    match refer {
        "CenterRightPoint" | "TopRightPoint" => (true, false),
        "CenterPoint" | "TopCenterPoint" => (true, true),
        _ => (false, true),
    }
}

fn is_icon_w(w: i128) -> bool {
    w > MIN_ICON_W && w <= SMALL_SIBLING
}

fn covers(outer: &Rect, inner: &Rect) -> bool {
    outer.x.0 <= inner.x.0
        && outer.y.0 <= inner.y.0
        && outer.x.0 + outer.width.0 >= inner.x.0 + inner.width.0
        && outer.y.0 + outer.height.0 >= inner.y.0 + inner.height.0
}

fn y_overlap(a: &Rect, b: &Rect) -> bool {
    y_overlap_at(a, b, 1)
}

fn y_overlap_at(a: &Rect, b: &Rect, min: i128) -> bool {
    let a0 = a.y.0;
    let a1 = a.y.0 + a.height.0;
    let b0 = b.y.0;
    let b1 = b.y.0 + b.height.0;
    a1.min(b1) - a0.max(b0) >= min
}

fn x_overlap(a: &Rect, b: &Rect) -> bool {
    let a0 = a.x.0;
    let a1 = a.x.0 + a.width.0;
    let b0 = b.x.0;
    let b1 = b.x.0 + b.width.0;
    a0 < b1 && b0 < a1
}

fn vertical_stack_gap(a: &Rect, b: &Rect) -> Option<i128> {
    if a.y.0 + a.height.0 <= b.y.0 {
        Some(b.y.0 - (a.y.0 + a.height.0))
    } else if b.y.0 + b.height.0 <= a.y.0 {
        Some(a.y.0 - (b.y.0 + b.height.0))
    } else {
        None
    }
}

/// Stacked frames that share the same right edge (x+width) but may differ in
/// left edge / width — common in right-aligned signature blocks. Growing one
/// tight NoBreak line into the page margin shifts ItemTransform right and walks
/// past the lines above.
fn stacked_right_edge_sibling(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    let my_right = me.x.0 + me.width.0;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || other.x.0 + other.width.0 != my_right {
            continue;
        }
        if !x_overlap(me, other) {
            continue;
        }
        if vertical_stack_gap(me, other).is_some_and(|g| g < GROW_ROOM) {
            return true;
        }
    }
    false
}

/// Stacked frames that share the same lock column (x/width). Growing one tight
/// NoBreak line into the page margin would walk its right edge past siblings
/// (signature name/title/org in one end block).
/// Short label stacked under a taller graphic with the same horizontal center
/// (QR caption, image footnotes). WidthOnly + CenterPoint keeps host metrics
/// centered; expanding the lock rect leaves left-aligned ink off-center.
fn stacked_graphic_caption(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    if me.height.0 > 12_000 {
        return false;
    }
    let my_cx = me.x.0 + me.width.0 / 2;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || other.height.0 < me.height.0 * 3 {
            continue;
        }
        let other_cx = other.x.0 + other.width.0 / 2;
        if (other_cx - my_cx).abs() > 2_000 {
            continue;
        }
        if other.y.0 + other.height.0 <= me.y.0
            && vertical_stack_gap(other, me).is_some_and(|g| g < GROW_ROOM)
        {
            return true;
        }
    }
    false
}

/// Nested title inside a stroked/filled card: extra width is padding, not a
/// page sheet. WidthOnly about ItemTransform recenters the title in the card.
const CARD_PAD_MIN: i128 = 6_000;
const CARD_PAD_MAX: i128 = 80_000;
const CARD_PAD_LEFT: i128 = 4_000;

fn hug_label_in_wide_parent(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !covers(other, me) {
            continue;
        }
        let extra_w = other.width.0.saturating_sub(me.width.0);
        if extra_w.saturating_mul(3) > me.width.0 {
            return true;
        }
    }
    false
}

fn padded_inside_card(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !covers(other, me) {
            continue;
        }
        let extra_w = other.width.0 - me.width.0;
        let extra_left = me.x.0 - other.x.0;
        // Hug labels (attendee names) sit in a much wider card; leftover is
        // not title padding. WidthOnly must stay so host/stroke cannot overset.
        // Pills are only a few pt taller than the label (date/name badges);
        // treating them as cards drops WidthOnly and InDesign hides the text.
        if extra_w >= CARD_PAD_MIN
            && extra_w <= CARD_PAD_MAX
            && extra_left >= CARD_PAD_LEFT
            && extra_w.saturating_mul(3) <= me.width.0
            && other.height.0 >= me.height.0.saturating_mul(3)
        {
            return true;
        }
    }
    false
}

fn disable_widthonly_inside_cards(elements: &mut [PageElement]) {
    let rects: Vec<Rect> = elements.iter().map(|el| el.rect().clone()).collect();
    for i in 0..elements.len() {
        let PageElement::TextBox(tb) = &mut elements[i] else {
            continue;
        };
        if !matches!(tb.align, TextAlign::Left) || !tb.autosize_width {
            continue;
        }
        if padded_inside_card(&rects[i], &rects, i)
            && !(tb.full_width_lock_line && tb.lock_line_count <= 1)
        {
            tb.autosize_width = false;
            tb.autosize_no_wrap = false;
        }
    }
}

fn stacked_mixed_width_sibling(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    const COL_X_TOL: i128 = 2_000;
    const COL_STACK_GAP: i128 = 16_000;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || (me.x.0 - other.x.0).abs() > COL_X_TOL {
            continue;
        }
        if me.width.0 == other.width.0 {
            continue;
        }
        if covers(other, me) || covers(me, other) {
            continue;
        }
        if other.height.0 >= me.height.0.saturating_mul(3)
            || me.height.0 >= other.height.0.saturating_mul(3)
        {
            continue;
        }
        if vertical_stack_gap(me, other).is_some_and(|g| g <= COL_STACK_GAP) {
            return true;
        }
    }
    false
}

fn stacked_lock_column_sibling(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    const COL_X_TOL: i128 = 2_000;
    const COL_STACK_GAP: i128 = 16_000;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || (me.x.0 - other.x.0).abs() > COL_X_TOL {
            continue;
        }
        if covers(other, me) || covers(me, other) {
            continue;
        }
        if other.height.0 >= me.height.0.saturating_mul(3)
            || me.height.0 >= other.height.0.saturating_mul(3)
        {
            continue;
        }
        if !x_overlap(me, other) {
            continue;
        }
        if vertical_stack_gap(me, other).is_some_and(|g| g <= COL_STACK_GAP) {
            return true;
        }
    }
    false
}

/// Gap to the nearest stacked sibling (not containing chrome). `None` if the
/// rest of the column below `me` is empty.
fn nearest_below_gap(me: &Rect, rects: &[Rect], my_i: usize) -> Option<i128> {
    let my_bottom = me.y.0 + me.height.0;
    let mut best: Option<i128> = None;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !x_overlap(me, other) || covers(other, me) || covers(me, other) {
            continue;
        }
        let o_top = other.y.0;
        if o_top >= my_bottom {
            let gap = o_top - my_bottom;
            best = Some(best.map_or(gap, |g| g.min(gap)));
        }
    }
    best
}

/// Strictly left or right, any distance. Containing chrome is not a sibling.
fn column_sibling(me: &Rect, rects: &[Rect], my_i: usize) -> bool {
    let my_left = me.x.0;
    let my_right = me.x.0 + me.width.0;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !y_overlap_at(me, other, Y_TOUCH) || covers(other, me) || covers(me, other)
        {
            continue;
        }
        let o_left = other.x.0;
        let o_right = other.x.0 + other.width.0;
        if o_left >= my_right || o_right <= my_left {
            return true;
        }
    }
    false
}

fn blocks_grow_right(me: &Rect, other: &Rect) -> bool {
    if !y_overlap(me, other) || covers(other, me) || covers(me, other) {
        return false;
    }
    let my_right = me.x.0 + me.width.0;
    let other_left = other.x.0;
    // Gap < 0 is shadow-bleed / underlay spanning this frame, not a 10pt
    // sibling on the growth side (card rasters that clip the footer band).
    other_left >= my_right && other_left < my_right + GROW_ROOM
}

fn blocks_grow_left(me: &Rect, other: &Rect) -> bool {
    if !y_overlap(me, other) || covers(other, me) || covers(me, other) {
        return false;
    }
    let my_left = me.x.0;
    let other_right = other.x.0 + other.width.0;
    other_right <= my_left && other_right + GROW_ROOM > my_left
}

fn nearest_right_gap(me: &Rect, rects: &[Rect], my_i: usize) -> Option<i128> {
    let my_right = me.x.0 + me.width.0;
    let mut best: Option<i128> = None;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !blocks_grow_right(me, other) {
            continue;
        }
        let gap = other.x.0 - my_right;
        best = Some(best.map_or(gap, |g| g.min(gap)));
    }
    best
}

fn nearest_right_blocker_w(me: &Rect, rects: &[Rect], my_i: usize) -> Option<i128> {
    let my_right = me.x.0 + me.width.0;
    let mut best: Option<(i128, i128)> = None;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !blocks_grow_right(me, other) {
            continue;
        }
        let gap = other.x.0 - my_right;
        let w = other.width.0;
        best = Some(match best {
            None => (gap, w),
            Some((g, _)) if gap < g => (gap, w),
            Some((g, ow)) if gap == g => (g, ow.min(w)),
            Some(prev) => prev,
        });
    }
    best.map(|(_, w)| w)
}

fn nearest_left_blocker_w(me: &Rect, rects: &[Rect], my_i: usize) -> Option<i128> {
    let my_left = me.x.0;
    let mut best: Option<(i128, i128)> = None;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !blocks_grow_left(me, other) {
            continue;
        }
        let gap = my_left - (other.x.0 + other.width.0);
        let w = other.width.0;
        best = Some(match best {
            None => (gap, w),
            Some((g, _)) if gap < g => (gap, w),
            Some((g, ow)) if gap == g => (g, ow.min(w)),
            Some(prev) => prev,
        });
    }
    best.map(|(_, w)| w)
}

fn nearest_left_gap(me: &Rect, rects: &[Rect], my_i: usize) -> Option<i128> {
    let my_left = me.x.0;
    let mut best: Option<i128> = None;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !blocks_grow_left(me, other) {
            continue;
        }
        let gap = my_left - (other.x.0 + other.width.0);
        best = Some(best.map_or(gap, |g| g.min(gap)));
    }
    best
}

/// Room to the right at any distance (not just GROW_ROOM). Page-fill boxes
/// that contain `me` are skipped via `covers`.
fn open_right(me: &Rect, rects: &[Rect], my_i: usize, page_w: Option<i128>) -> i128 {
    let my_right = me.x.0 + me.width.0;
    let mut limit = page_w.unwrap_or(my_right + HOST_LINE_PAD);
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !y_overlap_at(me, other, Y_TOUCH) || covers(other, me) || covers(me, other)
        {
            continue;
        }
        if other.x.0 >= my_right {
            limit = limit.min(other.x.0);
        }
    }
    (limit - my_right).max(0)
}

fn open_left(me: &Rect, rects: &[Rect], my_i: usize, page_w: Option<i128>) -> i128 {
    let my_left = me.x.0;
    let mut limit = 0i128;
    let _ = page_w;
    for (j, other) in rects.iter().enumerate() {
        if j == my_i || !y_overlap_at(me, other, Y_TOUCH) || covers(other, me) || covers(me, other)
        {
            continue;
        }
        let other_right = other.x.0 + other.width.0;
        if other_right <= my_left {
            limit = limit.max(other_right);
        }
    }
    (my_left - limit).max(0)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ir::{TextAlign, TextBox};
    use k2f_core::{Pt, Rect};

    fn tracked_run() -> crate::ir::TextRun {
        crate::ir::TextRun {
            text: "LABEL".into(),
            font_name: "Roboto".into(),
            size_pt: 8.5,
            bold: false,
            italic: false,
            underline: false,
            strike: false,
            color_hex: "FFFFFF".into(),
            hyperlink: None,
            script: crate::ir::ScriptPos::Baseline,
            leading_pt: None,
            auto_page_number: false,
            tracking: 176,
            face_style: "Regular".into(),
        }
    }

    fn tb(id: &str, x: i128, w: i128, autosize: bool, refer: &'static str) -> PageElement {
        PageElement::TextBox(TextBox {
            node_id: id.into(),
            rect: Rect {
                x: Pt(x),
                y: Pt(0),
                width: Pt(w),
                height: Pt(16_000),
            },
            runs: vec![tracked_run()],
            align: TextAlign::Left,
            inset_top: 0.0,
            inset_left: 0.0,
            inset_bottom: 0.0,
            inset_right: 0.0,
            first_line_indent_pt: 0.0,
            left_indent_pt: 0.0,
            vert_center: false,
            autosize_width: autosize,
            autosize_refer: refer,
            autosize_no_wrap: autosize,
            autosize_height: false,
            no_break: true,
            semantic_newlines: false,
            lock_line_count: 1,
            first_baseline_leading_offset: false,
            full_width_lock_line: false,
        })
    }

    fn shape(x: i128, y: i128, w: i128, h: i128) -> PageElement {
        PageElement::Shape(crate::ir::ShapeBox {
            node_id: "card".into(),
            rect: Rect {
                x: Pt(x),
                y: Pt(y),
                width: Pt(w),
                height: Pt(h),
            },
            fill_hex: None,
            fill_alpha: 255,
            gradient: None,
            corner_pt: 0.0,
            line_hex: None,
            line_alpha: 255,
            line_w_pt: 0.0,
            line_dash: crate::ir::LineDash::Solid,
        })
    }

    fn is_width(el: &PageElement) -> bool {
        matches!(el, PageElement::TextBox(t) if t.autosize_width)
    }

    fn width(el: &PageElement) -> i128 {
        el.rect().width.0
    }

    #[test]
    fn tight_line_beside_icon_keeps_widthonly() {
        // Glow-feed profile name: 149pt ink-tight line, 6pt gap, 14pt badge.
        // Padding the gap and dropping WidthOnly oversets (hides) the name.
        let mut els = vec![
            tb("profile.name", 102_000, 149_342, true, "CenterLeftPoint"),
            shape(257_342, 0, 14_000, 14_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "KRONOS\u{00A0}//\u{00A0}NIGHTFALL".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 14.5;
            t.runs[0].bold = true;
        }
        apply(&mut els, 600_000);
        assert!(
            is_width(&els[0]),
            "icon sibling must not disable WidthOnly on a tight display name"
        );
        assert_eq!(
            width(&els[0]),
            149_342,
            "lock rect stays; InDesign WidthOnly grows only the host delta"
        );
        let PageElement::TextBox(name) = &els[0] else {
            panic!("textbox")
        };
        assert!(name.no_break, "name must stay one glued line");
        assert!(
            !name.autosize_height,
            "must not HeightOnly-wrap onto the handle row"
        );
    }

    #[test]
    fn adjacent_label_pads_into_gap_not_through_badge() {
        // 8pt gap — same class as horizontal pill stacks.
        let mut els = vec![
            tb("eyebrow", 0, 106_000, true, "CenterLeftPoint"),
            tb("badge", 114_000, 58_000, true, "CenterPoint"),
        ];
        clamp_width_autosize(&mut els);
        assert!(!is_width(&els[0]), "must not WidthOnly through the badge");
        assert!(
            !is_width(&els[1]),
            "badge CenterPoint must not grow into the label"
        );
        assert_eq!(
            width(&els[0]),
            114_000,
            "left label should expand through the 8pt gap, not past the badge"
        );
        assert_eq!(
            width(&els[1]),
            58_000,
            "centered pill chrome stays lock-sized"
        );
        let PageElement::TextBox(left) = &els[0] else {
            panic!("textbox")
        };
        assert_eq!(
            left.runs[0].tracking, 0,
            "tight stack must drop overflowing tracking"
        );
        assert!(
            left.no_break,
            "8pt gap still NoBreak (pad is enough for a short label)"
        );
        let PageElement::TextBox(badge) = &els[1] else {
            panic!("textbox")
        };
        assert_eq!(badge.runs[0].tracking, 176, "centered pill keeps tracking");
    }

    #[test]
    fn isolated_tight_line_keeps_widthonly() {
        let mut els = vec![tb("title", 0, 200_000, true, "CenterLeftPoint")];
        clamp_width_autosize(&mut els);
        assert!(is_width(&els[0]));
        assert_eq!(width(&els[0]), 200_000);
    }

    #[test]
    fn parent_card_does_not_block() {
        let mut els = vec![
            shape(0, 0, 300_000, 200_000),
            tb("title", 20_000, 200_000, true, "CenterLeftPoint"),
        ];
        clamp_width_autosize(&mut els);
        assert!(is_width(&els[1]), "containing chrome is not a sibling");
    }

    #[test]
    fn twelve_pt_masthead_gap_keeps_widthonly() {
        let mut els = vec![
            tb("tag", 0, 200_000, true, "CenterLeftPoint"),
            tb("live", 212_000, 70_000, true, "CenterPoint"),
        ];
        clamp_width_autosize(&mut els);
        assert!(is_width(&els[0]), "12pt gap must still WidthOnly");
        assert_eq!(width(&els[0]), 200_000);
    }

    #[test]
    fn wide_gutter_keeps_widthonly() {
        // 24pt gap (hero column): host slack still has room.
        let mut els = vec![
            tb("lead", 0, 520_000, true, "CenterLeftPoint"),
            tb("hero", 544_000, 300_000, false, "CenterLeftPoint"),
        ];
        clamp_width_autosize(&mut els);
        assert!(is_width(&els[0]));
        assert_eq!(width(&els[0]), 520_000);
    }

    #[test]
    fn flush_neighbor_drops_nobreak_instead_of_overset() {
        // 0pt gap — column body flush with the next card (poster metrics).
        let mut els = vec![
            tb("body", 0, 180_000, true, "CenterLeftPoint"),
            shape(180_000, 0, 80_000, 90_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "endures\u{00A0}is\u{00A0}an\u{00A0}immense".into();
        }
        clamp_width_autosize(&mut els);
        assert!(!is_width(&els[0]), "must not WidthOnly through the card");
        assert_eq!(width(&els[0]), 180_000, "zero gap adds no pad");
        let PageElement::TextBox(body) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !body.no_break,
            "flush sibling must allow wrap instead of overset"
        );
        assert!(
            body.autosize_height,
            "extra wrap must HeightOnly rather than clip"
        );
        assert!(
            !body.runs[0].text.contains('\u{00A0}'),
            "NBSP glue must undo so host can wrap"
        );
    }

    #[test]
    fn multiline_body_beside_card_drops_nobreak() {
        // 8pt gap is enough for a short pill, not a lock-pinned paragraph.
        let mut els = vec![
            tb("body", 0, 174_000, true, "CenterLeftPoint"),
            shape(182_000, 0, 80_000, 90_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text =
                "In the oceanic abyss\nextinguishes completely\nthreshold what endures"
                    .replace(' ', "\u{00A0}");
        }
        clamp_width_autosize(&mut els);
        assert!(!is_width(&els[0]));
        assert_eq!(
            width(&els[0]),
            174_000,
            "multi-line column body stays lock-width; padding into the gutter is not required"
        );
        let PageElement::TextBox(body) = &els[0] else {
            panic!("textbox")
        };
        assert!(!body.no_break, "pinned body must wrap, not overset");
        assert!(body.autosize_height);
        assert!(
            !body.runs[0].text.contains('\u{00A0}'),
            "NBSP glue must undo so host can wrap"
        );
        assert!(
            !body.runs[0].text.contains('\n'),
            "3+ lock wraps collapse so host reflows as one paragraph"
        );
    }

    #[test]
    fn left_column_body_with_matching_lock_lines_collapses() {
        // Production lock_line_count matches wrap lines. The old exception
        // kept those `\n` so InDesign wrapped at the lock points *and* at the
        // (different) frame width.
        let mut els = vec![
            tb("body", 0, 174_000, true, "CenterLeftPoint"),
            shape(182_000, 0, 80_000, 90_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.lock_line_count = 3;
            t.full_width_lock_line = true;
            t.runs[0].text =
                "In the oceanic abyss\nextinguishes completely\nthreshold what endures"
                    .replace(' ', "\u{00A0}");
        }
        clamp_width_autosize(&mut els);
        let PageElement::TextBox(body) = &els[0] else {
            panic!("textbox")
        };
        assert!(!body.no_break, "column body must wrap, not overset");
        assert!(
            !body.runs[0].text.contains('\n'),
            "matching lock-line wraps must still collapse, got {:?}",
            body.runs[0].text
        );
        assert!(
            !body.runs[0].text.contains("  "),
            "collapsed lock breaks must not leave double spaces, got {:?}",
            body.runs[0].text
        );
    }

    #[test]
    fn collapsed_lock_breaks_squeeze_space_before_newline() {
        // Pin inserts `\n` at the next line's first glyph, so the lock space
        // stays: "lock \ntypefaces". Collapse must not become "lock  typefaces".
        let mut els = vec![
            tb("body", 0, 174_000, true, "CenterLeftPoint"),
            shape(182_000, 0, 80_000, 90_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text =
                "Deterministic micro-increments lock \ntypefaces and containers into \nharmonious"
                    .into();
        }
        clamp_width_autosize(&mut els);
        let PageElement::TextBox(body) = &els[0] else {
            panic!("textbox")
        };
        assert!(!body.runs[0].text.contains('\n'), "3+ lock wraps collapse");
        assert!(
            !body.runs[0].text.contains("  "),
            "must squeeze space+newline, got {:?}",
            body.runs[0].text
        );
        assert!(
            body.runs[0].text.contains("lock typefaces"),
            "got {:?}",
            body.runs[0].text
        );
    }

    #[test]
    fn two_line_title_keeps_display_break() {
        let mut els = vec![
            tb("title", 0, 174_000, true, "CenterLeftPoint"),
            shape(182_000, 0, 80_000, 40_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "RESONANCE BEYOND THE PHOTIC\nDEPTHS".into();
        }
        clamp_width_autosize(&mut els);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert!(!title.no_break);
        assert!(
            title.runs[0].text.contains('\n'),
            "2-line display break must not collapse"
        );
    }

    #[test]
    fn midword_lock_wrap_does_not_collapse() {
        let mut els = vec![
            tb("hero.title_2", 0, 437_000, true, "CenterLeftPoint"),
            shape(450_000, 0, 64_000, 90_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.lock_line_count = 2;
            t.full_width_lock_line = true;
            t.autosize_height = true;
            t.runs[0].text = "RECONSTRUCTIO\nN".into();
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        let joined: String = title.runs.iter().map(|r| r.text.as_str()).collect();
        assert!(
            joined.contains('\n') && joined.starts_with("RECONSTRUCTIO") && joined.ends_with('N'),
            "mid-word Br must survive autosize, got {joined:?}"
        );
    }

    #[test]
    fn overlapping_card_shadow_is_not_a_side_neighbor() {
        // Effect raster bleeds into the footer band and spans across the label.
        // Negative gap is underlay, not a 10pt sibling on the growth side.
        let mut els = vec![
            shape(-50_000, 0, 300_000, 20_000),
            tb("footer", 0, 200_000, true, "CenterLeftPoint"),
        ];
        clamp_width_autosize(&mut els);
        assert!(
            is_width(&els[1]),
            "overlapping chrome must not turn off WidthOnly"
        );
        assert_eq!(width(&els[1]), 200_000);
    }

    #[test]
    fn semantic_two_line_title_beside_column_drops_nobreak() {
        // editorial-story slide.01.title: "THE ESSENCE\nOF STILLNESS." in the
        // left column beside the figure. NoBreak+HeightOnly hid both lines.
        let mut els = vec![
            tb("slide.01.title", 46_000, 416_000, false, "TopLeftPoint"),
            shape(516_000, 88_775, 380_000, 342_000),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.y = Pt(166_200);
            t.rect.height = Pt(114_400);
            t.no_break = true;
            t.autosize_height = true;
            t.semantic_newlines = true;
            t.lock_line_count = 2;
            t.runs[0].text = "THE ESSENCE\nOF STILLNESS.".into();
            t.runs[0].size_pt = 52.0;
        }
        apply(&mut els, 960_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !title.no_break,
            "2-line semantic title beside a figure must not NoBreak-overset"
        );
        assert!(
            title.runs[0].text.contains('\n'),
            "author newline must stay, got {:?}",
            title.runs[0].text
        );
        assert!(title.autosize_height);
        assert!(
            !title.autosize_width,
            "must not WidthOnly through the figure gutter"
        );
        assert_eq!(title.rect.x.0, 46_000, "left edge stays");
        assert_eq!(title.rect.width.0, 416_000, "lock column width stays");
    }

    #[test]
    fn center_semantic_two_line_title_keeps_heightonly() {
        // academic-serif-classic paper.title: two semantic paragraphs, center.
        let mut els = vec![tb("paper.title", 0, 499_000, false, "TopCenterPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.no_break = true;
            t.autosize_height = true;
            t.semantic_newlines = true;
            t.lock_line_count = 2;
            t.align = TextAlign::Center;
            t.runs[0].text =
                "Deterministic Semantic Layout Compilation\nfor Academic Publishing Systems".into();
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !title.autosize_width,
            "WidthOnly concatenates the two title lines into one overflow"
        );
        assert!(title.autosize_height);
        assert!(
            !title.no_break,
            "NoBreak+HeightOnly oversets and hides the title"
        );
        assert!(
            title.runs[0].text.contains('\n'),
            "author newline must stay"
        );
    }

    #[test]
    fn affiliation_stack_drops_nobreak() {
        let mut els = vec![tb("paper.affiliations", 0, 499_000, false, "TopLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.no_break = true;
            t.autosize_height = true;
            t.semantic_newlines = true;
            t.lock_line_count = 4;
            t.runs[0].text =
                "1 Department of Computer Science\n2 Laboratory for Information\n3 Institute for Automated Reasoning\n*Correspondence: a@b.c"
                    .into();
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(aff) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !aff.no_break,
            "4-line affiliation stack must not NoBreak+HeightOnly overset"
        );
        assert!(aff.autosize_height);
    }

    #[test]
    fn wide_two_line_left_does_not_widthonly_shrink() {
        // Social-snap / paper display title: 2 semantic lines in a wide
        // left-aligned frame. WidthOnly shrinks to ink and InDesign re-anchors
        // about ItemTransform, so the title looks centered.
        let mut els = vec![tb("title", 0, 488_000, false, "TopLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.no_break = true;
            t.autosize_height = true;
            t.semantic_newlines = true;
            t.runs[0].text = "THE NEXT GENERATION\nAI DESIGN CANVAS".into();
        }
        apply(&mut els, 600_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !title.autosize_width,
            "loose left 2-line must not WidthOnly-shrink and look centered"
        );
        assert!(title.no_break, "isolated title keeps NoBreak");
        assert!(
            title.autosize_height,
            "HeightOnly stays so extra host wrap is not clipped"
        );
    }

    #[test]
    fn center_two_line_nobreak_gets_widthonly() {
        // Center shrink toward CenterPoint is correct; host metrics still
        // need WidthOnly so HeightOnly+NoBreak does not overset.
        let mut els = vec![tb("title", 0, 499_000, false, "CenterPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.no_break = true;
            t.autosize_height = true;
            t.align = TextAlign::Center;
            t.runs[0].text = "The Architecture of Thought:\nHuman-Centric Reasoning".into();
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            title.autosize_width,
            "isolated Center NoBreak must WidthOnly so host metrics do not hide the title"
        );
        assert!(
            title.no_break,
            "isolated title keeps NoBreak with WidthOnly"
        );
        assert!(!title.autosize_height, "WidthOnly replaces HeightOnly");
        assert!(
            !title.autosize_no_wrap,
            "2-line title must size to the longest line, not the unwrapped paragraph"
        );
    }

    #[test]
    fn wide_single_line_does_not_widthonly_shrink() {
        let mut els = vec![tb("authors", 0, 499_000, false, "TopLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.no_break = true;
            t.runs[0].text = "Dr. Julian Vance".into();
        }
        apply(&mut els, 595_000);
        assert!(
            !is_width(&els[0]),
            "wide authors line must not WidthOnly-shrink and re-anchor"
        );
    }

    #[test]
    fn tight_letter_recipient_line_grows_not_widthonly() {
        // blush-floral-letterhead: ink-tight recipient name at the left margin.
        // open_right widens the frame; WidthOnly on that wide box re-anchors
        // the line to the page center in InDesign.
        let mut els = vec![tb(
            "letter.recipient.name",
            54_000,
            102_090,
            true,
            "CenterLeftPoint",
        )];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "Dr. Evelyn Montgomery".into();
            t.runs[0].tracking = 0;
            t.runs[0].bold = true;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(name) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !name.autosize_width,
            "margin-grown recipient line must not WidthOnly-shrink"
        );
        assert!(
            name.rect.width.0 > 102_090,
            "frame grows into the open right margin for host metrics"
        );
        assert!(name.no_break, "single-line salutation keeps NoBreak");
    }

    #[test]
    fn flush_left_neighbor_stops_widthonly_from_eating_label() {
        // KEYWORDS: 5pt gap (lock) then the list. List WidthOnly from
        // CenterLeftPoint must not grow through the label.
        let mut els = vec![
            tb("label", 0, 42_806, false, "CenterLeftPoint"),
            tb("list", 47_806, 367_760, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.runs[0].text = "systems\narchitecture\nlayout".into();
        }
        apply(&mut els, 595_000);
        assert!(
            !is_width(&els[1]),
            "close left sibling must disable WidthOnly on the list"
        );
        let PageElement::TextBox(list) = &els[1] else {
            panic!("textbox")
        };
        assert!(
            !list.no_break,
            "list beside a label must wrap instead of collide"
        );
        assert!(
            list.autosize_height,
            "wrapped keyword list must HeightOnly so the second line is not clipped"
        );
    }

    #[test]
    fn flush_right_folio_grows_into_page_margin_not_wrap() {
        // Tight "Page 1 of 2" ink box flush with the left footer. WidthOnly
        // would expand about ItemTransform into that footer; wrapping makes
        // two lines. Grow into the open right margin instead.
        let mut els = vec![
            shape(0, 0, 595_000, 842_000),
            tb("footer.left", 48_000, 462_666, false, "CenterLeftPoint"),
            tb("footer.right", 510_666, 36_334, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[2] {
            t.runs[0].text = "Page\u{00A0}1\u{00A0}of\u{00A0}2".into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(folio) = &els[2] else {
            panic!("textbox")
        };
        assert!(folio.no_break, "folio must stay one glued line");
        assert!(
            !folio.autosize_height,
            "folio must not HeightOnly-wrap onto two lines"
        );
        assert!(
            !folio.autosize_width,
            "must not WidthOnly into the left footer"
        );
        assert!(
            folio.rect.width.0 > 36_334,
            "must grow into the page margin, got {}",
            folio.rect.width.0
        );
        assert_eq!(folio.rect.x.0, 510_666, "left edge (glyph start) stays");
        assert!(
            folio.rect.x.0 + folio.rect.width.0 <= 595_000,
            "must not grow past the page"
        );
        assert!(
            folio.runs[0].text.contains('\u{00A0}'),
            "NBSP glue must stay so the folio cannot wrap"
        );
    }

    #[test]
    fn single_line_heading_beside_badge_grows_into_open_margin() {
        // Ink-tight article title (~194pt) flush with a left badge. The rest of
        // A4 is empty. Old SHORT_LINE cap (100pt) dropped NoBreak and wrapped
        // the heading onto the clause grid. Grow into the open right margin.
        let mut els = vec![
            tb("badge", 45_000, 60_000, false, "CenterLeftPoint"),
            tb("title", 105_000, 193_774, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.runs[0].text = "ENGAGEMENT\u{00A0}&\u{00A0}SCOPE\u{00A0}OF\u{00A0}SERVICES".into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[1] else {
            panic!("textbox")
        };
        assert!(
            title.no_break,
            "single lock line must not wrap beside a badge"
        );
        assert!(
            !title.autosize_height,
            "heading must not HeightOnly onto the next row"
        );
        assert!(
            !title.autosize_width,
            "must not WidthOnly through the badge"
        );
        assert_eq!(title.rect.x.0, 105_000, "left edge (glyph start) stays");
        assert!(
            title.rect.width.0 > 193_774,
            "must grow into the page margin, got {}",
            title.rect.width.0
        );
        assert!(
            title.rect.x.0 + title.rect.width.0 <= 595_000,
            "must not grow past the page"
        );
        assert!(
            title.runs[0].text.contains('\u{00A0}'),
            "NBSP glue must stay so the heading cannot wrap"
        );
    }

    #[test]
    fn wide_hug_subtitle_grows_past_hairline_card_raster() {
        // aurora-data slide.02.desc: 532pt ink-tight NoBreak one-liner. A
        // shadow-expanded card raster sits 0.05pt under it, which used to
        // count as a column sibling and freeze the lock width. Host metrics
        // then overset and InDesign hides the subtitle.
        let mut desc = tb("slide.02.desc", 56_000, 532_052, false, "CenterLeftPoint");
        if let PageElement::TextBox(t) = &mut desc {
            t.rect.y = Pt(89_600);
            t.rect.height = Pt(14_950);
            t.runs[0].text = "Real-time\u{00A0}diffusion\u{00A0}sampling\u{00A0}across\u{00A0}38,000\u{00A0}ligand-target\u{00A0}pairs\u{00A0}with\u{00A0}physical\u{00A0}thermodynamic\u{00A0}constraints.".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 11.5;
            t.full_width_lock_line = true;
            t.lock_line_count = 1;
        }
        let mut els = vec![
            desc,
            shape(56_000, 104_500, 268_000, 310_000),
            shape(342_000, 104_500, 268_000, 310_000),
            shape(628_000, 104_500, 268_000, 310_000),
        ];
        apply(&mut els, 960_000);
        let PageElement::TextBox(desc) = &els[0] else {
            panic!("textbox")
        };
        assert!(desc.no_break, "subtitle must stay one glued line");
        assert!(
            !desc.autosize_width,
            "wide hug line must not WidthOnly-reanchor"
        );
        assert_eq!(desc.rect.x.0, 56_000, "left edge stays");
        assert!(
            desc.rect.width.0 > 532_052,
            "must grow into the open header band, got {}",
            desc.rect.width.0
        );
        assert!(
            desc.rect.x.0 + desc.rect.width.0 <= 960_000,
            "must not grow past the page"
        );
    }

    #[test]
    fn multiline_column_gutter_does_not_widthonly_through_sibling() {
        // 14.5pt gutter — wider than GROW_ROOM (10pt). WidthOnly +
        // UseNoLineBreaks sized the sidenote as one unwrapped line and ate
        // the body column. Stay in the lock width; HeightOnly for extra wrap.
        let mut els = vec![
            tb("sidenote", 46_500, 116_000, true, "CenterLeftPoint"),
            tb("body", 177_000, 376_000, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text =
                "Establishes canonical definitions,\ntechnical specifications, and\narchitectural boundaries"
                    .into();
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.runs[0].text =
                "Licensed Blueprint Architecture signifies\nthe modular software kernels".into();
        }
        apply(&mut els, 595_000);
        assert!(
            !is_width(&els[0]),
            "sidenote must not WidthOnly through body"
        );
        assert!(
            !is_width(&els[1]),
            "body must not WidthOnly through sidenote"
        );
        assert_eq!(width(&els[0]), 116_000, "sidenote lock width stays");
        assert_eq!(width(&els[1]), 376_000, "body lock width stays");
        let PageElement::TextBox(sn) = &els[0] else {
            panic!("textbox")
        };
        let PageElement::TextBox(body) = &els[1] else {
            panic!("textbox")
        };
        assert!(sn.autosize_height);
        assert!(body.autosize_height);
        assert!(!sn.no_break);
        assert!(!body.no_break);
        assert_eq!(sn.rect.x.0, 46_500);
        assert_eq!(body.rect.x.0, 177_000);
    }

    #[test]
    fn semantic_newlines_beside_sibling_are_not_collapsed() {
        // Seal stack: author `\n` matching lock lines. A left icon is a column
        // sibling. Flattening `\n` makes one long line in a short box.
        let mut els = vec![
            tb("icon", 50_000, 30_000, false, "CenterLeftPoint"),
            tb("seal", 92_500, 187_500, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.runs[0].text =
                "OFFICIAL CORPORATE SEAL\nAETHERIA SYSTEMS CORP.\nDELAWARE REGISTRATION".into();
            t.semantic_newlines = true;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(seal) = &els[1] else {
            panic!("textbox")
        };
        assert!(!is_width(&els[1]));
        assert!(seal.autosize_height);
        assert!(
            seal.runs[0].text.contains('\n'),
            "author newlines must survive, got {:?}",
            seal.runs[0].text
        );
        assert_eq!(seal.rect.width.0, 187_500);
    }

    #[test]
    fn isolated_left_tight_lead_grows_right_not_widthonly() {
        // Tight single-line lead (editorial hero). WidthOnly grows about
        // ItemTransform and the line walks off the left page margin.
        let mut els = vec![tb("hero.lead", 26_000, 454_000, true, "CenterLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text =
                "A serialized field guide exploring mathematical proportion, deliberate whitespace"
                    .into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, 600_000);
        let PageElement::TextBox(lead) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !lead.autosize_width,
            "isolated left lead must not WidthOnly-reanchor"
        );
        assert!(lead.no_break, "lead must stay one glued line");
        assert_eq!(lead.rect.x.0, 26_000, "left margin stays");
        assert!(
            lead.rect.width.0 > 454_000,
            "must grow into the open page, got {}",
            lead.rect.width.0
        );
        assert!(
            lead.rect.x.0 + lead.rect.width.0 <= 600_000,
            "must not grow past the page"
        );
        assert!(!lead.autosize_height);
    }

    #[test]
    fn mixed_width_stacked_lead_grows_right_not_hidden() {
        // editorial-grid hero: title 357pt and lead 454pt share x, 4pt gap.
        // ink_tighter_than skips WidthOnly on 400pt+ nearly-full lines, so
        // the lead is NoBreak in the lock box. Host Roboto oversets and
        // InDesign hides the whole story unless the frame grows right.
        let mut els = vec![
            tb("hero.title", 26_000, 356_648, true, "CenterLeftPoint"),
            tb("hero.lead", 26_000, 453_906, false, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.y = Pt(65_400);
            t.rect.height = Pt(28_750);
            t.runs[0].text = "THE ARCHITECTURE OF SILENCE".into();
            t.runs[0].size_pt = 28.75;
            t.full_width_lock_line = true;
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(98_150);
            t.rect.height = Pt(13_300);
            t.runs[0].text = "A serialized field guide exploring mathematical proportion, deliberate whitespace, and unified modular grids.".into();
            t.runs[0].size_pt = 9.5;
            t.full_width_lock_line = true;
        }
        apply(&mut els, 600_000);
        let PageElement::TextBox(lead) = &els[1] else {
            panic!("textbox")
        };
        assert_eq!(lead.rect.x.0, 26_000, "left margin stays");
        assert!(
            lead.rect.width.0 > 453_906,
            "mixed-width stacked lead must grow into the open page, got {}",
            lead.rect.width.0
        );
        assert!(
            lead.rect.x.0 + lead.rect.width.0 <= 600_000,
            "must not grow past the page"
        );
        assert!(
            !lead.autosize_width,
            "must not WidthOnly-reanchor under the title"
        );
        assert!(lead.no_break, "lead stays one glued line after growing");
    }

    #[test]
    fn stacked_right_edge_block_keeps_lock_width() {
        // Right-aligned end block: each line has a different width but the
        // same right edge. open_right would shift ItemTransform right.
        let right = 384_000i128;
        let mut els = vec![
            tb("closing", right - 238_686, 238_686, true, "CenterLeftPoint"),
            tb(
                "signature",
                right - 243_061,
                243_061,
                true,
                "CenterLeftPoint",
            ),
            tb("meta", right - 194_842, 194_842, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.y = Pt(488_800);
            t.rect.height = Pt(17_250);
            t.runs[0].text = "With our warmest love & heartfelt appreciation,".into();
            t.full_width_lock_line = true;
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(511_050);
            t.rect.height = Pt(24_700);
            t.runs[0].text = "Julian & Vivienne Sterling".into();
            t.runs[0].bold = true;
            t.full_width_lock_line = true;
        }
        if let PageElement::TextBox(t) = &mut els[2] {
            t.rect.y = Pt(540_750);
            t.rect.height = Pt(13_300);
            t.runs[0].text = "The Sterling Celebration · Autumn 2026".into();
            t.full_width_lock_line = true;
        }
        apply(&mut els, 420_000);
        for (i, (id, w)) in [
            ("closing", 238_686),
            ("signature", 243_061),
            ("meta", 194_842),
        ]
        .iter()
        .enumerate()
        {
            let PageElement::TextBox(tb) = &els[i] else {
                panic!("textbox")
            };
            assert_eq!(tb.node_id, *id);
            assert_eq!(tb.rect.width.0, *w, "{id} lock width");
            assert_eq!(tb.rect.x.0 + tb.rect.width.0, right, "{id} right edge");
            assert!(tb.autosize_width, "{id} keeps WidthOnly for host slack");
        }
    }

    #[test]
    fn stacked_signature_meta_keeps_lock_width() {
        // End-block stack: name/title/org share one lock column. The longest
        // line must not grow into the page margin or its right edge walks past
        // the lines above.
        let w = 232_259i128;
        let x = 310_741i128;
        let mut els = vec![
            tb("sig.name", x, w, true, "CenterLeftPoint"),
            tb("sig.title", x, w, true, "CenterLeftPoint"),
            tb("sig.org", x, w, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.y = Pt(657_150);
            t.rect.height = Pt(17_550);
            t.runs[0].text = "Arthur C. Pendelton".into();
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(678_700);
            t.rect.height = Pt(14_000);
            t.runs[0].text = "Executive Creative Director & Founder".into();
            t.runs[0].tracking = 30;
        }
        if let PageElement::TextBox(t) = &mut els[2] {
            t.rect.y = Pt(696_700);
            t.rect.height = Pt(13_300);
            t.runs[0].text = "The Heritage Botanical Studio · September 15, 2026".into();
            t.runs[0].tracking = 31;
        }
        apply(&mut els, 595_000);
        for (i, id) in ["sig.name", "sig.title", "sig.org"].iter().enumerate() {
            let PageElement::TextBox(tb) = &els[i] else {
                panic!("textbox")
            };
            assert_eq!(tb.node_id, *id);
            assert_eq!(tb.rect.x.0, x, "{id} left edge");
            assert_eq!(tb.rect.width.0, w, "{id} lock width");
            assert!(
                !tb.autosize_width,
                "{id} must not WidthOnly-shrink leftover slack and look centered"
            );
        }
    }

    #[test]
    fn multiline_nobreak_drops_tracking() {
        let mut els = vec![tb("letter.p2", 42_000, 510_000, false, "CenterLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "line one\nline two".into();
            t.runs[0].tracking = 13;
            t.no_break = true;
            t.autosize_height = true;
            t.lock_line_count = 2;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(body) = &els[0] else {
            panic!("textbox")
        };
        assert_eq!(body.runs[0].tracking, 0);
        assert!(
            body.no_break,
            "2-line lock-pinned display copy must keep NoBreak so host cannot extra-wrap"
        );
        assert!(
            body.autosize_width,
            "must WidthOnly-grow to the longest lock line"
        );
    }

    #[test]
    fn lock_pinned_article_title_keeps_nobreak_widthonly() {
        let mut els = vec![tb("doc.title", 0, 499_000, false, "TopLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.no_break = true;
            t.autosize_height = true;
            t.lock_line_count = 2;
            t.runs[0].text =
                "The Architecture of Thought: Foundations of Latent\nRepresentation and Human-Centric Reasoning"
                    .into();
            t.runs[0].size_pt = 19.0;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            title.no_break,
            "lock-pinned title must keep NoBreak, got unglued {:?}",
            title.runs[0].text
        );
        assert!(
            title.autosize_width,
            "must WidthOnly so host metrics do not insert a third wrap"
        );
        assert!(
            !title.autosize_height,
            "WidthOnly replaces HeightOnly on 2-line titles"
        );
        assert!(title.runs[0].text.contains('\n'), "lock break must stay");
    }

    #[test]
    fn wide_multiline_left_restores_heightonly_when_widthonly_cleared() {
        // Letter body: tight ink triggers WidthOnly, then ensure_nobreak_width
        // grows into the page margin and drops WidthOnly. Keep the lock
        // height so a shorter host wrap cannot inflate the gap to the next
        // stacked paragraph.
        let mut els = vec![tb("letter.p2", 42_000, 510_000, true, "CenterLeftPoint")];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text =
                "Your thoughtful advice and gentle encouragement arrived\nat the exact moment they were most needed.\nIt is a rare and precious gift to have someone who listens\nwith such sincere empathy and offers wisdom with such grace."
                    .into();
            t.autosize_height = false;
            t.no_break = true;
            t.lock_line_count = 4;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(body) = &els[0] else {
            panic!("textbox")
        };
        assert!(
            !body.autosize_width,
            "wide left body must not WidthOnly-shrink"
        );
        assert!(
            !body.autosize_height,
            "stacked column body must keep lock height"
        );
        assert!(
            !body.no_break,
            "full-width lock-pinned body must wrap so InDesign does not hide the story"
        );
    }

    #[test]
    fn card_title_keeps_lock_width() {
        let mut els = vec![
            shape(0, 0, 595_000, 842_000),
            shape(405_372, 436_025, 165_628, 109_200),
            tb("col3.spec_head", 413_372, 149_628, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[2] {
            t.rect.y = Pt(444_025);
            t.rect.height = Pt(13_200);
            t.runs[0].text = "PUBLICATION METRICS".into();
            t.runs[0].tracking = 27;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[2] else {
            panic!("textbox")
        };
        assert!(
            !title.autosize_width,
            "card title must not WidthOnly-recenter"
        );
        assert_eq!(title.rect.x.0, 413_372);
        assert_eq!(title.rect.width.0, 149_628);
    }

    #[test]
    fn ink_hug_date_pill_in_grid_keeps_widthonly() {
        // Nested table cells export as box+text. Date/name text is an ink-hug
        // frame inside a short pill, stacked with the next row and beside the
        // owner column. Treating the pill as a padded card used to drop
        // WidthOnly; host Roboto then overset and hid every date.
        let mut els = vec![
            shape(419_000, 359_700, 52_388, 15_600),
            tb("t2.r0c3.txt", 425_000, 40_388, true, "CenterLeftPoint"),
            tb("t2.r1c3.txt", 425_000, 40_388, true, "CenterLeftPoint"),
            tb("t2.r0c4.txt", 499_000, 30_750, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(362_700);
            t.rect.height = Pt(9_600);
            t.runs[0].text = "2026-08-14".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 8.0;
            t.full_width_lock_line = true;
        }
        if let PageElement::TextBox(t) = &mut els[2] {
            t.rect.y = Pt(388_300);
            t.rect.height = Pt(9_600);
            t.runs[0].text = "2026-08-20".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 8.0;
            t.full_width_lock_line = true;
        }
        if let PageElement::TextBox(t) = &mut els[3] {
            t.rect.y = Pt(362_700);
            t.rect.height = Pt(9_600);
            t.runs[0].text = "E. Vance".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 8.0;
            t.full_width_lock_line = true;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(date) = &els[1] else {
            panic!("textbox")
        };
        assert!(
            date.autosize_width,
            "ink-hug date in a pill must WidthOnly so host metrics do not hide it"
        );
        assert!(date.no_break, "date stays one unbreakable token");
    }

    #[test]
    fn hug_name_inside_card_keeps_widthonly() {
        let mut els = vec![
            shape(42_000, 200_000, 120_000, 110_000),
            tb(
                "doc.attendee.name1",
                71_000,
                62_000,
                true,
                "CenterLeftPoint",
            ),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(268_000);
            t.rect.height = Pt(11_250);
            t.runs[0].text = "Dr. Elena Vance".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 9.0;
            t.full_width_lock_line = true;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(name) = &els[1] else {
            panic!("textbox")
        };
        assert!(
            name.autosize_width,
            "ink-hug names inside a card must WidthOnly, not overset"
        );
    }

    #[test]
    fn right_edge_hug_name_keeps_widthonly() {
        // David Miller: lock width ~47pt inside a ~70pt attendee cell.
        let mut els = vec![
            shape(166_000, 200_000, 70_000, 110_000),
            tb("doc.attendee.name4", 178_000, 47_000, true, "CenterPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(268_000);
            t.rect.height = Pt(11_250);
            t.align = TextAlign::Left;
            t.runs[0].text = "David Miller".into();
            t.runs[0].tracking = 0;
            t.runs[0].size_pt = 9.0;
            t.full_width_lock_line = true;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(name) = &els[1] else {
            panic!("textbox")
        };
        assert!(
            name.autosize_width,
            "right-edge hug names must WidthOnly, not overset"
        );
    }

    #[test]
    fn tracked_title_beside_left_icon_keeps_lock_left() {
        let mut els = vec![
            shape(163_424, 67_800, 26_000, 26_000),
            tb(
                "doc.header.title",
                205_424,
                226_152,
                true,
                "CenterLeftPoint",
            ),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(68_000);
            t.rect.height = Pt(26_400);
            t.runs[0].text = "DAILY CHECKLIST".into();
            t.runs[0].tracking = 159;
            t.runs[0].size_pt = 22.0;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[1] else {
            panic!("textbox")
        };
        assert_eq!(title.rect.x.0, 205_424, "gap to the plus must stay");
        assert!(
            !title.autosize_width,
            "tracked title must not WidthOnly-recenter"
        );
    }

    #[test]
    fn padded_banner_keeps_letter_spacing() {
        let mut els = vec![tb(
            "notice.banner",
            42_000,
            511_000,
            false,
            "CenterLeftPoint",
        )];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "MANDATORY COMPLIANCE\nSCALES IS REQUIRED".into();
            t.runs[0].tracking = 47;
            t.no_break = true;
            t.inset_left = 12.0;
            t.vert_center = true;
            t.lock_line_count = 2;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(banner) = &els[0] else {
            panic!("textbox")
        };
        assert_eq!(
            banner.runs[0].tracking, 47,
            "padded banner must keep tracking"
        );
    }

    #[test]
    fn stacked_graphic_caption_keeps_centerpoint_widthonly() {
        let mut els = vec![
            shape(202_000, 53_865, 36_000, 36_000),
            tb("caption", 202_393, 37_214, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(91_865);
            t.rect.height = Pt(4_620);
            t.runs[0].text = "SCAN TO VERIFY".into();
        }
        apply(&mut els, 252_000);
        let PageElement::TextBox(cap) = &els[1] else {
            panic!("textbox")
        };
        assert!(cap.autosize_width, "caption under graphic keeps WidthOnly");
        assert_eq!(cap.autosize_refer, "CenterPoint");
    }

    #[test]
    fn page_centered_label_keeps_centerpoint_widthonly() {
        // Invitation monogram: tight ink, box centered on A5-width page.
        let page_w = 360_000i128;
        let mut els = vec![tb(
            "card.front.header.monogram",
            158_087,
            43_825,
            true,
            "CenterLeftPoint",
        )];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "E\u{00A0}·\u{00A0}L".into();
            t.runs[0].tracking = 0;
            t.full_width_lock_line = true;
        }
        apply(&mut els, page_w);
        let PageElement::TextBox(mono) = &els[0] else {
            panic!("textbox")
        };
        assert_eq!(mono.align, TextAlign::Center);
        assert_eq!(mono.autosize_refer, "CenterPoint");
        assert!(
            mono.autosize_width,
            "page-centered label must keep WidthOnly, not open_right expand"
        );
        assert_eq!(mono.rect.width.0, 43_825, "lock width must stay");
        assert_eq!(mono.rect.x.0, 158_087, "lock left edge must stay");
    }

    #[test]
    fn page_centered_grid_column_stays_left_aligned() {
        // bauhaus-geometric card2: middle column sits on the page midline but
        // ink is flush-left. page_center_autosize must not promote to Center.
        let page_w = 595_000i128;
        let col_w = 148_333i128;
        let col_x = (page_w - col_w) / 2;
        let mut els = vec![
            tb(
                "card1.tag",
                col_x - col_w - 10_000,
                col_w,
                true,
                "CenterLeftPoint",
            ),
            tb("card2.tag", col_x, col_w, true, "CenterLeftPoint"),
            tb(
                "card3.tag",
                col_x + col_w + 10_000,
                col_w,
                true,
                "CenterLeftPoint",
            ),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.runs[0].text = "WERKSTATT 02 / TYPO".into();
        }
        apply(&mut els, page_w);
        let PageElement::TextBox(mid) = &els[1] else {
            panic!("textbox")
        };
        assert_eq!(
            mid.align,
            TextAlign::Left,
            "middle grid column must stay left-aligned"
        );
        assert_ne!(
            mid.autosize_refer, "CenterPoint",
            "column label must not re-anchor about center"
        );
    }

    #[test]
    fn stacked_left_column_beside_hairline_stays_lock_width() {
        // color-block card.back.person_*: 136pt left column, 6pt gap, 0.6pt
        // divider. WidthOnly about ItemTransform centers the delegate block.
        let mut els = vec![
            tb("person_tag", 12_000, 136_000, false, "CenterLeftPoint"),
            tb("person_name", 12_000, 136_000, true, "CenterLeftPoint"),
            shape(154_000, 0, 600, 94_200),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.runs[0].text = "DELEGATE SPECIFICATION".into();
            t.runs[0].tracking = 0;
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(17_000);
            t.runs[0].text = "DR. AVERY CHEN".into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, 252_000);
        for el in &els[..2] {
            let PageElement::TextBox(t) = el else {
                panic!("textbox")
            };
            assert_eq!(t.align, TextAlign::Left);
            assert!(
                !t.autosize_width,
                "{} must keep lock width, not WidthOnly-shrink",
                t.node_id
            );
            assert_eq!(t.rect.x.0, 12_000, "left edge must stay");
            assert!(
                t.rect.width.0 >= 136_000 && t.rect.width.0 <= 142_000,
                "{} width {} should stay in the column (maybe 6pt gutter pad)",
                t.node_id,
                t.rect.width.0
            );
        }
    }

    #[test]
    fn stacked_cta_below_column_body_keeps_nobreak() {
        // 3-col grid: lock-pinned body beside another card, CTA 4pt below.
        // Dropping NoBreak + HeightOnly extra-wraps the first lock line and
        // overprints the CTA.
        let mut els = vec![
            tb("col", 0, 140_000, true, "CenterLeftPoint"),
            tb("body", 300_000, 140_000, true, "CenterLeftPoint"),
            tb("cta", 300_000, 90_000, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.height = Pt(40_000);
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.runs[0].text = "Continue to Part 04: Typographic Color\n& Serial Rhythm.".into();
            t.rect.height = Pt(21_000);
        }
        if let PageElement::TextBox(t) = &mut els[2] {
            t.runs[0].text = "EXPLORE ESSAY 10 >>".into();
            t.rect.y = Pt(25_000);
            t.rect.height = Pt(10_000);
        }
        apply(&mut els, 500_000);
        let PageElement::TextBox(body) = &els[1] else {
            panic!("textbox")
        };
        assert!(
            body.no_break,
            "body above a CTA must not extra-wrap into it"
        );
        assert!(
            !body.autosize_height,
            "must not HeightOnly through the CTA, got height autosize"
        );
        assert!(
            !body.autosize_width,
            "must not WidthOnly through the column"
        );
        assert_eq!(body.rect.x.0, 300_000, "column left edge stays");
        assert!(
            body.rect.width.0 > 140_000,
            "must grow into the open page, got {}",
            body.rect.width.0
        );
        assert!(
            body.rect.x.0 + body.rect.width.0 <= 500_000,
            "must not grow past the page"
        );
        assert!(
            body.runs[0].text.contains('\n'),
            "lock wrap before the CTA must stay"
        );
        assert_eq!(
            body.rect.y.0 + body.rect.height.0,
            21_000,
            "lock height stays"
        );
    }

    #[test]
    fn vert_center_folio_keeps_lock_height_beside_sibling() {
        let mut els = vec![
            tb("footer.left", 52_000, 417_455, false, "CenterLeftPoint"),
            tb("footer.right", 469_455, 73_545, true, "CenterPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.y = Pt(776_600);
            t.rect.height = Pt(20_400);
            t.vert_center = true;
            t.runs[0].text = "CONFIDENTIAL RECORD".into();
            t.runs[0].tracking = 0;
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(776_600);
            t.rect.height = Pt(20_400);
            t.vert_center = true;
            t.align = TextAlign::Center;
            t.runs[0].text = "PAGE 1 OF 1".into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(folio) = &els[1] else {
            panic!("textbox")
        };
        assert!(!folio.autosize_height, "CenterAlign needs lock height");
        assert_eq!(folio.rect.height.0, 20_400);
    }

    #[test]
    fn page_centered_middle_card_stat_stays_left_aligned() {
        // editorial-story 3.8×: tall number over a short kicker (3× height
        // skip) sharing a right edge, box on the page midline. Must not flip
        // to CenterAlign + WidthOnly.
        let page_w = 960_000i128;
        let card_w = 244_000i128;
        let mid_x = 358_000i128;
        let mut els = vec![
            tb("card1.num", 62_000, card_w, false, "CenterLeftPoint"),
            tb("card2.num", mid_x, card_w, false, "CenterLeftPoint"),
            tb("card2.kicker", mid_x, card_w, false, "CenterLeftPoint"),
            tb("card3.num", 654_000, card_w, false, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(219_625);
            t.rect.height = Pt(46_200);
            t.runs[0].text = "3.8×".into();
            t.runs[0].tracking = 0;
        }
        if let PageElement::TextBox(t) = &mut els[2] {
            t.rect.y = Pt(273_825);
            t.rect.height = Pt(12_000);
            t.runs[0].text = "BRAND RECALL".into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, page_w);
        let PageElement::TextBox(num) = &els[1] else {
            panic!("textbox")
        };
        assert_eq!(num.align, TextAlign::Left, "middle card stat stays Left");
        assert_ne!(num.autosize_refer, "CenterPoint");
        assert!(!num.autosize_width, "must not WidthOnly-recenter 3.8×");
        assert_eq!(num.rect.x.0, mid_x, "left edge stays");
    }

    #[test]
    fn loose_stacked_schedule_titles_keep_left_lock() {
        // gallery-noir col3 session titles: leftover right slack, same-width
        // stack, no y-overlapping side column. WidthOnly recenters them.
        let mut els = vec![
            tb("s1_time", 395_334, 167_666, true, "CenterLeftPoint"),
            tb("s1_desc", 395_334, 167_666, false, "CenterLeftPoint"),
            tb("s2_time", 395_334, 167_666, true, "CenterLeftPoint"),
        ];
        if let PageElement::TextBox(t) = &mut els[0] {
            t.rect.y = Pt(413_616);
            t.rect.height = Pt(10_140);
            t.runs[0].text = "11:00 - ACOUSTIC CALIBRATION".into();
            t.runs[0].tracking = 0;
        }
        if let PageElement::TextBox(t) = &mut els[1] {
            t.rect.y = Pt(425_756);
            t.rect.height = Pt(18_200);
            t.runs[0].text = "Low-frequency resonant testing.".into();
            t.runs[0].tracking = 0;
        }
        if let PageElement::TextBox(t) = &mut els[2] {
            t.rect.y = Pt(489_008);
            t.rect.height = Pt(10_140);
            t.runs[0].text = "14:00 - CURATORIAL WALKTHROUGH".into();
            t.runs[0].tracking = 0;
        }
        apply(&mut els, 595_000);
        let PageElement::TextBox(title) = &els[0] else {
            panic!("textbox")
        };
        assert_eq!(title.align, TextAlign::Left);
        assert!(
            !title.autosize_width,
            "loose schedule title must not WidthOnly-recenter"
        );
        assert_eq!(title.rect.x.0, 395_334, "left edge stays");
        assert_eq!(title.rect.width.0, 167_666, "lock width stays");
    }
}