reinhardt-admin-cli 0.1.0-rc.20

Command-line tool for Reinhardt project management
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
//! AST-based page! macro formatter implementation.
//!
//! This module provides formatting for `page!` macro DSL using proper AST parsing.
//! Unlike the text-based approach, this implementation:
//!
//! - Uses `syn::parse_file()` to parse the entire Rust source file
//! - Uses `syn::visit` to accurately detect `page!` macro invocations
//! - Ignores content in comments and strings (guaranteed by AST)
//! - Uses `reinhardt-pages-ast` for parsing the macro DSL
//!
//! ## Architecture
//!
//! ```mermaid
//! flowchart TB
//!     A["Rust source file"] --> B["syn::parse_file()<br/>Parse entire file to AST"]
//!     B --> C["PageMacroVisitor<br/>Walk AST to find page! macros"]
//!     C --> D["reinhardt_pages::ast::PageMacro<br/>Parse macro tokens to DSL AST"]
//!     D --> E["format_macro()<br/>Generate formatted code from AST"]
//!     E --> F["replace by span<br/>Replace original text"]
//!     F --> G["Formatted source file"]
//! ```

use quote::ToTokens;
use regex::Regex;
use reinhardt_pages::ast::{
	PageAttr, PageBody, PageComponent, PageElement, PageElse, PageEvent, PageExpression, PageFor,
	PageIf, PageMacro, PageNode, PageParam, PageText,
};
use std::path::PathBuf;
use std::process::Command;
use std::sync::LazyLock;
use syn::visit::Visit;
use syn::{ExprMacro, Macro, parse_file};

/// Reason why formatting was skipped for a file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum SkipReason {
	/// File-wide ignore-all marker detected
	FileWideMarker,
	/// All page! macros were individually ignored
	AllMacrosIgnored,
}

impl std::fmt::Display for SkipReason {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			SkipReason::FileWideMarker => write!(f, "file-wide ignore marker"),
			SkipReason::AllMacrosIgnored => write!(f, "all macros ignored"),
		}
	}
}

/// Options to pass to rustfmt.
///
/// These options mirror rustfmt's command-line arguments and allow
/// customizing formatting behavior.
#[derive(Clone, Debug, Default)]
pub(crate) struct RustfmtOptions {
	/// Path to rustfmt.toml configuration file
	pub config_path: Option<PathBuf>,
	/// Rust edition to use (e.g., "2021", "2024")
	pub edition: Option<String>,
	/// Style edition to use
	pub style_edition: Option<String>,
	/// Inline config options (e.g., "max_width=120,hard_tabs=false")
	pub config: Option<String>,
	/// Color output setting (e.g., "auto", "always", "never")
	pub color: Option<String>,
}

impl RustfmtOptions {
	/// Apply these options to a rustfmt Command.
	pub(crate) fn apply_to_command(&self, cmd: &mut Command) {
		if let Some(ref path) = self.config_path {
			cmd.arg("--config-path").arg(path);
		}
		if let Some(ref edition) = self.edition {
			cmd.arg("--edition").arg(edition);
		}
		if let Some(ref style_edition) = self.style_edition {
			cmd.arg("--style-edition").arg(style_edition);
		}
		if let Some(ref config) = self.config {
			cmd.arg("--config").arg(config);
		}
		if let Some(ref color) = self.color {
			cmd.arg("--color").arg(color);
		}
	}
}

/// Result of formatting operation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct FormatResult {
	/// Formatted content
	pub content: String,
	/// Whether the file contains page! macros
	pub contains_page_macro: bool,
	/// If set, formatting was skipped for this reason
	pub skipped: Option<SkipReason>,
}

/// Information about a detected page! macro invocation.
#[derive(Debug)]
struct MacroInfo {
	/// Start byte offset in the source
	start: usize,
	/// End byte offset in the source
	end: usize,
	/// The macro's tokens (content inside page!(...))
	tokens: proc_macro2::TokenStream,
	/// Whether this macro should be skipped during formatting
	should_skip: bool,
}

/// Backup information for a protected page! macro.
///
/// Used during the protect/restore cycle to preserve page! macros
/// while rustfmt processes the surrounding Rust code.
#[derive(Debug, Clone)]
pub(crate) struct PageMacroBackup {
	/// Unique identifier for this macro (used in placeholder)
	pub id: usize,
	/// Original page! macro text (including "page!(...)")
	pub original: String,
}

/// Result of protecting page! macros in source code.
#[derive(Debug)]
pub(crate) struct ProtectResult {
	/// Source code with page! macros replaced by placeholders
	pub protected_content: String,
	/// Backup information for each replaced macro
	pub backups: Vec<PageMacroBackup>,
}

/// Visitor that walks the AST to find page! macro invocations.
struct PageMacroVisitor<'a> {
	/// Collected macro information
	macros: Vec<MacroInfo>,
	/// Original source code for offset calculation
	source: &'a str,
}

impl<'a> PageMacroVisitor<'a> {
	fn new(source: &'a str) -> Self {
		Self {
			macros: Vec::new(),
			source,
		}
	}

	/// Extract macro info from a Macro node.
	fn extract_macro_info(&mut self, mac: &Macro) {
		if mac.path.is_ident("page") {
			// Get span information
			// Note: proc_macro2::Span in non-procedural-macro context doesn't
			// give us byte offsets directly. We need to find the macro in source.
			let tokens_str = mac.tokens.to_string();

			// Find this macro in the source by searching for "page!("
			// We use the token stream content to verify we found the right one
			if let Some(info) = self.find_macro_in_source(&tokens_str) {
				self.macros.push(info);
			}
		}
	}

	/// Find the page! macro in source and return its position info.
	fn find_macro_in_source(&self, _tokens_content: &str) -> Option<MacroInfo> {
		// This is a simplified approach - we search for "page!(" patterns
		// and verify by comparing token content
		let pattern = "page!(";
		let mut search_start = 0;

		// Skip already found macros
		for found in &self.macros {
			if found.end > search_start {
				search_start = found.end;
			}
		}

		while let Some(pos) = self.source[search_start..].find(pattern) {
			let abs_start = search_start + pos;
			let content_start = abs_start + pattern.len();

			// Find matching closing paren
			if let Some(end_pos) = find_matching_paren(self.source, content_start) {
				let macro_content = &self.source[content_start..end_pos];

				// Parse the content to get tokens
				if let Ok(tokens) = syn::parse_str::<proc_macro2::TokenStream>(macro_content) {
					return Some(MacroInfo {
						start: abs_start,
						end: end_pos + 1, // Include closing paren
						tokens,
						should_skip: false,
					});
				}
			}

			search_start = abs_start + 1;
		}

		None
	}
}

impl<'ast, 'a> Visit<'ast> for PageMacroVisitor<'a> {
	fn visit_expr_macro(&mut self, expr: &'ast ExprMacro) {
		self.extract_macro_info(&expr.mac);
		syn::visit::visit_expr_macro(self, expr);
	}

	fn visit_macro(&mut self, mac: &'ast Macro) {
		self.extract_macro_info(mac);
		syn::visit::visit_macro(self, mac);
	}
}

/// Find the matching closing parenthesis, handling strings and nested parens.
///
/// Uses char_indices() to properly handle UTF-8 multi-byte characters.
fn find_matching_paren(source: &str, start: usize) -> Option<usize> {
	let substring = &source[start..];
	let mut depth = 1;
	let mut in_string = false;
	let mut in_char = false;
	let mut escape_next = false;
	let chars: Vec<(usize, char)> = substring.char_indices().collect();
	let mut i = 0;

	while i < chars.len() {
		let (offset, ch) = chars[i];

		if escape_next {
			escape_next = false;
			i += 1;
			continue;
		}

		if in_string {
			match ch {
				'\\' => escape_next = true,
				'"' => in_string = false,
				_ => {}
			}
			i += 1;
			continue;
		}

		if in_char {
			match ch {
				'\\' => escape_next = true,
				'\'' => in_char = false,
				_ => {}
			}
			i += 1;
			continue;
		}

		match ch {
			'"' => {
				// Check for raw strings: r#"..."# or r"..."
				// Look back to see if preceded by 'r' and optional '#'s
				let raw_start = detect_raw_string_start(substring, offset);
				if let Some(hash_count) = raw_start {
					// Skip raw string content until closing "###
					if let Some(end_offset) = skip_raw_string(substring, offset + 1, hash_count) {
						// Find the index in chars that corresponds to end_offset
						while i < chars.len() && chars[i].0 < end_offset {
							i += 1;
						}
						i += 1; // skip past end
						continue;
					}
				}
				in_string = true;
			}
			'\'' => {
				// Distinguish char literal from lifetime annotation:
				// Char literal: 'a', '\n', '\\'
				// Lifetime: 'a (letter not followed by closing quote in char-literal pattern)
				if is_char_literal(&chars, i) {
					in_char = true;
				}
				// Otherwise it's a lifetime, just skip the tick
			}
			'(' => depth += 1,
			')' => {
				depth -= 1;
				if depth == 0 {
					return Some(start + offset);
				}
			}
			_ => {}
		}
		i += 1;
	}

	None
}

/// Detect if a '"' at the given offset is the start of a raw string.
/// Returns Some(hash_count) if so (0 for r"...", 1 for r#"..."#, etc.).
fn detect_raw_string_start(s: &str, quote_offset: usize) -> Option<usize> {
	// Walk backwards from the quote to find r followed by optional #s
	let before = &s[..quote_offset];
	let trimmed = before.trim_end_matches('#');
	let hash_count = before.len() - trimmed.len();
	if trimmed.ends_with('r') {
		// Verify the 'r' is not part of an identifier
		let r_pos = trimmed.len() - 1;
		if r_pos == 0 || !before.as_bytes()[r_pos - 1].is_ascii_alphanumeric() {
			return Some(hash_count);
		}
	}
	None
}

/// Skip past the contents of a raw string starting after the opening '"'.
/// Returns the byte offset just past the closing '"' + hashes.
fn skip_raw_string(s: &str, start_after_quote: usize, hash_count: usize) -> Option<usize> {
	let closing_pattern: String = std::iter::once('"')
		.chain(std::iter::repeat_n('#', hash_count))
		.collect();
	s[start_after_quote..]
		.find(&closing_pattern)
		.map(|pos| start_after_quote + pos + closing_pattern.len())
}

/// Check if a `'\''` at `chars\[idx\]` starts a char literal (not a lifetime).
/// A char literal has the pattern: 'x' or '\x' or '\xx'
fn is_char_literal(chars: &[(usize, char)], idx: usize) -> bool {
	// After the opening quote, check if we see a closing quote pattern
	let remaining = &chars[idx + 1..];

	if remaining.is_empty() {
		return false;
	}

	// Pattern: '\...' (escaped char literal)
	if remaining[0].1 == '\\' {
		// Look for closing quote within the next few chars
		for item in remaining.iter().take(remaining.len().min(5)).skip(2) {
			if item.1 == '\'' {
				return true;
			}
		}
		return false;
	}

	// Pattern: 'x' (single char literal) - must have closing quote at position +2
	if remaining.len() >= 2 && remaining[1].1 == '\'' {
		return true;
	}

	// Otherwise, it's a lifetime ('a in type position, no closing quote)
	false
}

/// Maximum recursion depth for formatting nested nodes.
///
/// Prevents stack overflow from deeply nested or maliciously crafted
/// page! macro content. 128 levels is far more than any realistic
/// template would need.
const MAX_FORMAT_DEPTH: usize = 128;

/// Line length threshold for triggering rustfmt on expression blocks.
/// Expressions (including indentation and braces) shorter than this are kept on a single line.
const EXPRESSION_LINE_LENGTH_THRESHOLD: usize = 100;

/// AST-based page! macro formatter.
pub(crate) struct AstPageFormatter {
	/// Indentation string (tab by default)
	indent: String,
	/// Options to pass to rustfmt
	rustfmt_options: RustfmtOptions,
}

impl Default for AstPageFormatter {
	fn default() -> Self {
		Self::new()
	}
}

impl AstPageFormatter {
	/// Create a new formatter with default settings.
	pub(crate) fn new() -> Self {
		Self {
			indent: "\t".to_string(),
			rustfmt_options: RustfmtOptions::default(),
		}
	}

	/// Create a new formatter with the specified rustfmt options.
	// Allow dead_code: reserved for future use when full rustfmt options support is needed
	#[allow(dead_code)]
	pub(crate) fn with_options(rustfmt_options: RustfmtOptions) -> Self {
		Self {
			indent: "\t".to_string(),
			rustfmt_options,
		}
	}

	/// Create a new formatter with a specific config path.
	pub(crate) fn with_config(config_path: PathBuf) -> Self {
		Self {
			indent: "\t".to_string(),
			rustfmt_options: RustfmtOptions {
				config_path: Some(config_path),
				..Default::default()
			},
		}
	}

	/// Calculate the base indentation level for a macro at the given position.
	///
	/// Returns the number of tabs from the start of the line to the macro position.
	fn calculate_base_indent(content: &str, macro_start: usize) -> usize {
		// Find the start of the line containing the macro
		let line_start = content[..macro_start]
			.rfind('\n')
			.map(|pos| pos + 1)
			.unwrap_or(0);

		// Count tabs in the indentation
		let indent_str = &content[line_start..macro_start];
		indent_str.chars().filter(|&c| c == '\t').count()
	}

	/// Format the content of a Rust source file.
	///
	/// Uses AST parsing for accurate macro detection. Falls back to returning
	/// the original content if parsing fails.
	pub(crate) fn format(&self, content: &str) -> Result<FormatResult, String> {
		// Safety check FIRST: If no page! pattern exists, return unchanged.
		// This is a successful no-op, not an intentional skip β€” skipped stays None.
		if !content.contains("page!(") {
			return Ok(FormatResult {
				content: content.to_string(),
				contains_page_macro: false,
				skipped: None,
			});
		}

		// Then check for file-wide ignore marker
		if self.has_ignore_all_marker(content) {
			return Ok(FormatResult {
				content: content.to_string(),
				contains_page_macro: true, // Contains page! but ignored
				skipped: Some(SkipReason::FileWideMarker),
			});
		}

		// Collect all page! macro locations
		let macros = self.find_page_macros(content)?;

		if macros.is_empty() {
			// Substring matched but AST found no real invocation (e.g., inside
			// a comment or string literal). Successful no-op, not a skip.
			return Ok(FormatResult {
				content: content.to_string(),
				contains_page_macro: false,
				skipped: None,
			});
		}

		// Sort macros by position (they should already be in order)
		let mut macros = macros;
		macros.sort_by_key(|m| m.start);

		// Apply ignore markers to determine which macros to skip
		self.apply_ignore_markers(content, &mut macros);

		// Check if all macros are individually ignored
		if macros.iter().all(|m| m.should_skip) {
			return Ok(FormatResult {
				content: content.to_string(),
				contains_page_macro: true,
				skipped: Some(SkipReason::AllMacrosIgnored),
			});
		}

		// Build result by replacing each macro
		let mut result = String::with_capacity(content.len() * 2);
		let mut last_end = 0;

		for macro_info in &macros {
			// Skip if marked for ignore
			if macro_info.should_skip {
				// Copy the original macro as-is
				result.push_str(&content[last_end..macro_info.end]);
				last_end = macro_info.end;
				continue;
			}

			// Copy content before this macro
			result.push_str(&content[last_end..macro_info.start]);

			// Calculate base indentation for this macro
			let base_indent = Self::calculate_base_indent(content, macro_info.start);

			// Try to parse and format the macro
			match self.format_macro_tokens(&macro_info.tokens, base_indent) {
				Ok(formatted) => {
					result.push_str("page!(");
					result.push_str(&formatted);
					result.push(')');
				}
				Err(_) => {
					// If formatting fails, keep original
					result.push_str(&content[macro_info.start..macro_info.end]);
				}
			}

			last_end = macro_info.end;
		}

		// Copy remaining content
		result.push_str(&content[last_end..]);

		Ok(FormatResult {
			content: result,
			contains_page_macro: true,
			skipped: None,
		})
	}

	/// Find all page! macros in the source.
	fn find_page_macros(&self, content: &str) -> Result<Vec<MacroInfo>, String> {
		// Try to parse as a complete Rust file first
		match parse_file(content) {
			Ok(file) => {
				let mut visitor = PageMacroVisitor::new(content);
				visitor.visit_file(&file);
				Ok(visitor.macros)
			}
			Err(_) => {
				// If file parsing fails, fall back to text-based detection
				self.find_page_macros_text_based(content)
			}
		}
	}

	/// Text-based fallback for finding page! macros.
	fn find_page_macros_text_based(&self, content: &str) -> Result<Vec<MacroInfo>, String> {
		let mut macros = Vec::new();
		let pattern = "page!(";
		let mut search_start = 0;

		while let Some(pos) = content[search_start..].find(pattern) {
			let abs_start = search_start + pos;

			// Check if we're in a comment or string
			if self.is_in_comment_or_string(content, abs_start) {
				search_start = abs_start + 1;
				continue;
			}

			let content_start = abs_start + pattern.len();

			if let Some(end_pos) = find_matching_paren(content, content_start) {
				let macro_content = &content[content_start..end_pos];

				if let Ok(tokens) = syn::parse_str::<proc_macro2::TokenStream>(macro_content) {
					macros.push(MacroInfo {
						start: abs_start,
						end: end_pos + 1,
						tokens,
						should_skip: false,
					});
				}

				search_start = end_pos + 1;
			} else {
				search_start = abs_start + 1;
			}
		}

		Ok(macros)
	}

	/// Check if a position is inside a comment or string literal.
	///
	/// Uses char_indices() to properly handle UTF-8 multi-byte characters.
	fn is_in_comment_or_string(&self, content: &str, pos: usize) -> bool {
		let mut chars = content.char_indices().peekable();
		let mut in_string = false;
		let mut in_line_comment = false;
		let mut in_block_comment = false;
		let mut escape_next = false;

		while let Some((offset, ch)) = chars.next() {
			if offset >= pos {
				break;
			}

			if escape_next {
				escape_next = false;
				continue;
			}

			// Check for two-character sequences
			if !in_string
				&& !in_block_comment
				&& ch == '/' && let Some(&(_, next_ch)) = chars.peek()
			{
				if next_ch == '/' {
					in_line_comment = true;
					chars.next(); // consume second '/'
					continue;
				} else if next_ch == '*' {
					in_block_comment = true;
					chars.next(); // consume '*'
					continue;
				}
			}

			// Check for end of line comment
			if in_line_comment && ch == '\n' {
				in_line_comment = false;
				continue;
			}

			// Check for end of block comment
			if in_block_comment
				&& ch == '*' && let Some(&(_, next_ch)) = chars.peek()
				&& next_ch == '/'
			{
				in_block_comment = false;
				chars.next(); // consume '/'
				continue;
			}

			// Handle strings
			if !in_line_comment && !in_block_comment {
				match ch {
					'\\' if in_string => escape_next = true,
					'"' => in_string = !in_string,
					_ => {}
				}
			}
		}

		in_string || in_line_comment || in_block_comment
	}

	/// Format macro tokens to formatted string.
	fn format_macro_tokens(
		&self,
		tokens: &proc_macro2::TokenStream,
		base_indent: usize,
	) -> Result<String, String> {
		// Parse tokens as PageMacro
		let page_macro: PageMacro =
			syn::parse2(tokens.clone()).map_err(|e| format!("Parse error: {}", e))?;

		// Format the macro
		self.format_page_macro(&page_macro, base_indent)
	}

	/// Check if a page macro body is simple and can be formatted on a single line.
	fn is_simple_body(body: &PageBody) -> bool {
		// Simple if it has exactly one element with no attributes, events, or children
		if body.nodes.len() == 1
			&& let PageNode::Element(elem) = &body.nodes[0]
		{
			return elem.attrs.is_empty() && elem.events.is_empty() && elem.children.is_empty();
		}
		false
	}

	/// Format a PageMacro AST to string.
	fn format_page_macro(
		&self,
		macro_ast: &PageMacro,
		base_indent: usize,
	) -> Result<String, String> {
		let mut output = String::new();

		// Format closure parameters
		self.format_params(&mut output, &macro_ast.params);

		// Check if body is simple enough for single-line format
		if Self::is_simple_body(&macro_ast.body) {
			// Single-line format: || { div {} }
			output.push_str(" { ");
			if let PageNode::Element(elem) = &macro_ast.body.nodes[0] {
				output.push_str(&elem.tag.to_string());
				output.push_str(" {}");
			}
			output.push_str(" }");
		} else {
			// Multi-line format
			output.push_str(" {\n");
			self.format_body(&mut output, &macro_ast.body, base_indent + 1, 0);
			output.push_str(&self.make_indent(base_indent));
			output.push('}');
		}

		Ok(output)
	}

	/// Format closure parameters: |param: Type, ...|
	fn format_params(&self, output: &mut String, params: &[PageParam]) {
		output.push('|');
		for (i, param) in params.iter().enumerate() {
			if i > 0 {
				output.push_str(", ");
			}

			let param_name = param.name.to_string();
			let ty_str = param.ty.to_token_stream().to_string();

			output.push_str(&param_name);

			// Skip type annotation for underscore-only parameters with type inference
			// to preserve |_| format instead of |_: _|
			if param_name == "_" && ty_str.trim() == "_" {
				// No type annotation added
			} else {
				// Normal parameters or explicit type annotations
				output.push_str(": ");
				let cleaned = Self::clean_expression_spaces(&ty_str);
				output.push_str(&cleaned);
			}
		}
		output.push('|');
	}

	/// Format the page body.
	fn format_body(&self, output: &mut String, body: &PageBody, indent: usize, depth: usize) {
		for node in &body.nodes {
			self.format_node(output, node, indent, depth);
		}
	}

	/// Format a single node.
	///
	/// The `depth` parameter tracks recursion depth to prevent stack overflow
	/// from deeply nested templates. When the maximum depth is exceeded,
	/// the node is rendered as a raw token stream instead.
	fn format_node(&self, output: &mut String, node: &PageNode, indent: usize, depth: usize) {
		if depth > MAX_FORMAT_DEPTH {
			// Prevent stack overflow: emit a comment indicating depth limit
			let ind = self.make_indent(indent);
			output.push_str(&ind);
			output.push_str("/* formatting depth limit exceeded */\n");
			return;
		}

		match node {
			PageNode::Element(elem) => self.format_element(output, elem, indent, depth),
			PageNode::Text(text) => self.format_text(output, text, indent),
			PageNode::Expression(expr) => self.format_expression(output, expr, indent),
			PageNode::If(if_node) => self.format_if(output, if_node, indent, depth),
			PageNode::For(for_node) => self.format_for(output, for_node, indent, depth),
			PageNode::Component(comp) => self.format_component(output, comp, indent, depth),
			PageNode::Watch(watch_node) => self.format_watch(output, watch_node, indent, depth),
		}
	}

	/// Format an element node.
	fn format_element(&self, output: &mut String, elem: &PageElement, indent: usize, depth: usize) {
		let ind = self.make_indent(indent);

		// Check if element is empty (no attrs, events, or children)
		let is_empty = elem.attrs.is_empty() && elem.events.is_empty() && elem.children.is_empty();

		// Element tag
		output.push_str(&ind);
		output.push_str(&elem.tag.to_string());

		if is_empty {
			// Empty element: single line format
			output.push_str(" {}\n");
		} else {
			// Non-empty element: multi-line format
			output.push_str(" {\n");

			// Attributes (one per line)
			for attr in &elem.attrs {
				self.format_attr(output, attr, indent + 1);
			}

			// Event handlers (one per line)
			for event in &elem.events {
				self.format_event(output, event, indent + 1);
			}

			// Children
			for child in &elem.children {
				self.format_node(output, child, indent + 1, depth + 1);
			}

			// Closing brace
			output.push_str(&ind);
			output.push_str("}\n");
		}
	}

	/// Format an attribute.
	fn format_attr(&self, output: &mut String, attr: &PageAttr, indent: usize) {
		let ind = self.make_indent(indent);
		let value_str = Self::clean_expression_spaces(&attr.value.to_token_stream().to_string());
		output.push_str(&ind);
		output.push_str(&attr.name.to_string());
		output.push_str(": ");
		output.push_str(&value_str);
		output.push_str(",\n");
	}

	/// Format an event handler.
	///
	/// Uses rustfmt to format complex closures for better readability.
	/// Empty closures (e.g., `|_| {}`) are kept as-is.
	fn format_event(&self, output: &mut String, event: &PageEvent, indent: usize) {
		let ind = self.make_indent(indent);

		// Format handler with rustfmt (empty closures are kept as-is)
		let handler_str = self.format_handler_expression(&event.handler, indent + 1);

		output.push_str(&ind);
		output.push('@');
		output.push_str(&event.event_type.to_string());
		output.push_str(": ");
		output.push_str(&handler_str);
		output.push_str(",\n");
	}

	/// Format a text node.
	fn format_text(&self, output: &mut String, text: &PageText, indent: usize) {
		let ind = self.make_indent(indent);
		output.push_str(&ind);
		// Escape and quote the text
		let escaped = text.content.replace('\\', "\\\\").replace('"', "\\\"");
		output.push('"');
		output.push_str(&escaped);
		output.push_str("\"\n");
	}

	/// Clean up extra spaces in expression strings.
	fn clean_expression_spaces(s: &str) -> String {
		// Static regex compilation (compiled once, reused)
		// [\w:]+ matches identifiers and path-qualified names (e.g., Vec::new, std::iter::once)
		static IDENT_PAREN: LazyLock<Regex> = LazyLock::new(|| {
			Regex::new(r"([\w:]+) \(").expect("Failed to compile IDENT_PAREN regex")
		});
		static IDENT_MACRO: LazyLock<Regex> = LazyLock::new(|| {
			Regex::new(r"([\w:]+) !").expect("Failed to compile IDENT_MACRO regex")
		});
		// Match generic type opening: Result <T> -> Result<T>
		// Only matches when followed by an identifier (not =, <, > which indicate operators)
		static IDENT_ANGLE: LazyLock<Regex> = LazyLock::new(|| {
			Regex::new(r"([\w:>)]+) <([A-Za-z_&'\[(\*])")
				.expect("Failed to compile IDENT_ANGLE regex")
		});
		// Match generic type closing: String > -> String>
		// Only matches when preceded by an identifier/closing bracket and not followed by =, >, <
		static ANGLE_CLOSE: LazyLock<Regex> = LazyLock::new(|| {
			Regex::new(r"([\w>)]) >([\s,;)}\]>])").expect("Failed to compile ANGLE_CLOSE regex")
		});

		let s = s
			// Existing: Dot and method chaining
			.replace(" . ", ".")

			// Existing: Parentheses (function calls, tuples)
			.replace(" ( ", "(")
			.replace(" )", ")")
			.replace("( ", "(")
			.replace(" )", ")")
			.replace(" ()", "()")

			// Path separator must be processed before angle brackets
			// to avoid leaving a space before :: (e.g., collect ::<Vec<_>>)
			.replace(" :: ", "::")
			.replace(" ::", "::")

			// Generic type angle brackets: Vec < String > -> Vec<String>
			// These handle spaces around < and > in generic type parameters
			// Note: We don't use ".replace("> ", ">")" because it would incorrectly
			// affect arrow operators like "-> Result" turning them into "->Result"
			.replace("< ", "<")
			.replace(" <", "<")
			.replace(" >", ">")

			// New: Arrays and slices
			.replace("[ ", "[")
			.replace(" ]", "]")
			.replace(" ; ", "; ")  // Array size separator (preserve space after semicolon)

			// New: Reference types
			.replace("& ", "&")

			// New: Pointer types
			.replace("* const ", "*const ")
			.replace("* mut ", "*mut ")

			// New: Lifetime syntax
			.replace("for < ", "for<")
			.replace(" > fn", ">fn")

			// New: Comma in generics (Result<T, E>)
			.replace(" , ", ", ") // Note: Preserve space after comma

			// New: Macro calls (format! macro, etc.)
			.replace("! (", "!(") // Macro symbol before parenthesis
			.replace("! [", "![") // Macro with brackets
			.replace("! {", "!{") // Macro with braces

			// New: Closure parameter pipes
			// Handle closure syntax: | param | -> |param|
			// Note: OR operator (a | b) has different context and should be preserved
			.replace("| }", "|}") // Closing of empty closure before brace
			;

		// Apply regex replacements for identifier patterns
		let s = IDENT_PAREN.replace_all(&s, "$1("); // identifier ( -> identifier(
		let s = IDENT_MACRO.replace_all(&s, "$1!"); // identifier ! -> identifier!
		let s = IDENT_ANGLE.replace_all(&s, "$1<$2"); // identifier <T -> identifier<T (for generics)
		// Apply closing angle bracket repeatedly for nested generics like Option<String >
		let s = ANGLE_CLOSE.replace_all(&s, "$1>$2");

		// Handle closure pipes: | x | -> |x|, | x, y | -> |x, y|, || -> ||
		// This regex matches closure parameter lists between pipes
		static CLOSURE_PARAMS: LazyLock<Regex> = LazyLock::new(|| {
			Regex::new(r"\| ([^|]*?) \|").expect("Failed to compile CLOSURE_PARAMS regex")
		});
		let s = CLOSURE_PARAMS.replace_all(&s, |caps: &regex::Captures| {
			let inner = &caps[1];
			// Clean up spaces around commas in closure params
			let cleaned = inner.trim();
			format!("|{}|", cleaned)
		});

		s.into_owned()
	}

	/// Check if the expression is an empty closure (e.g., `|_| {}`, `|| {}`)
	///
	/// Empty closures are kept as-is without rustfmt formatting.
	fn is_empty_closure(expr: &syn::Expr) -> bool {
		if let syn::Expr::Closure(closure) = expr
			&& let syn::Expr::Block(block) = closure.body.as_ref()
		{
			return block.block.stmts.is_empty();
		}
		false
	}

	/// Format Rust code with rustfmt
	///
	/// Falls back to the input code if rustfmt is not available or fails.
	fn format_with_rustfmt(&self, code: &str) -> String {
		use std::io::Write;
		use std::process::Stdio;

		let mut cmd = Command::new("rustfmt");
		self.rustfmt_options.apply_to_command(&mut cmd);

		// Fallback to default edition if no config is specified
		if self.rustfmt_options.config_path.is_none() && self.rustfmt_options.edition.is_none() {
			cmd.arg("--edition=2024");
		}

		let child = cmd
			.stdin(Stdio::piped())
			.stdout(Stdio::piped())
			.stderr(Stdio::piped())
			.spawn();

		match child {
			Ok(mut child_process) => {
				if let Some(stdin) = child_process.stdin.as_mut() {
					let _ = stdin.write_all(code.as_bytes());
				}
				match child_process.wait_with_output() {
					Ok(output) if output.status.success() => {
						String::from_utf8(output.stdout).unwrap_or_else(|_| code.to_string())
					}
					_ => code.to_string(),
				}
			}
			Err(_) => code.to_string(),
		}
	}

	/// Find the end of an expression considering nested braces
	fn find_expression_end(s: &str) -> Option<usize> {
		let mut brace_depth = 0;
		let mut paren_depth = 0;
		let mut in_string = false;
		let mut escape_next = false;

		for (i, c) in s.chars().enumerate() {
			if escape_next {
				escape_next = false;
				continue;
			}

			match c {
				'\\' if in_string => escape_next = true,
				'"' if !in_string => in_string = true,
				'"' if in_string => in_string = false,
				'{' if !in_string => brace_depth += 1,
				'}' if !in_string => brace_depth -= 1,
				'(' if !in_string => paren_depth += 1,
				')' if !in_string => paren_depth -= 1,
				';' if !in_string && brace_depth == 0 && paren_depth == 0 => return Some(i),
				_ => {}
			}
		}
		None
	}

	/// Extract the handler expression from the wrapper code
	///
	/// Pattern: `let _handler = <expr>;`
	fn extract_handler_from_wrapper(formatted: &str) -> Option<String> {
		let start_marker = "let _handler = ";
		let start = formatted.find(start_marker)? + start_marker.len();
		let handler_part = &formatted[start..];
		let end = Self::find_expression_end(handler_part)?;
		Some(handler_part[..end].trim().to_string())
	}

	/// Apply base indentation to each line of a multi-line handler
	fn apply_base_indent(&self, handler: &str, base_indent: usize) -> String {
		let lines: Vec<&str> = handler.lines().collect();

		if lines.len() == 1 {
			return handler.to_string();
		}

		// First line has no additional indent (format_event adds the base indent)
		// Subsequent lines get the base indent applied
		let indent_str = self.make_indent(base_indent);
		let mut result = lines[0].to_string();

		for line in &lines[1..] {
			result.push('\n');
			if !line.trim().is_empty() {
				result.push_str(&indent_str);
			}
			result.push_str(line);
		}

		result
	}

	/// Format an event handler expression with rustfmt
	///
	/// Empty closures are kept as-is, complex closures are formatted with rustfmt.
	fn format_handler_expression(&self, expr: &syn::Expr, base_indent: usize) -> String {
		// Empty closures are kept as-is
		if Self::is_empty_closure(expr) {
			return Self::clean_expression_spaces(&expr.to_token_stream().to_string());
		}

		// Wrap the expression in a valid Rust file
		let wrapper_code = format!(
			"fn _wrapper() {{ let _handler = {}; }}",
			expr.to_token_stream()
		);

		// Parse with syn
		let Ok(file) = syn::parse_file(&wrapper_code) else {
			return Self::clean_expression_spaces(&expr.to_token_stream().to_string());
		};

		// Format with prettyplease + rustfmt
		let prettyplease_output = prettyplease::unparse(&file);
		let formatted = self.format_with_rustfmt(&prettyplease_output);

		// Extract the formatted handler
		let Some(handler_str) = Self::extract_handler_from_wrapper(&formatted) else {
			return Self::clean_expression_spaces(&expr.to_token_stream().to_string());
		};

		// Apply base indentation
		self.apply_base_indent(&handler_str, base_indent)
	}

	/// Format a Rust expression with rustfmt when it exceeds the line length threshold.
	///
	/// Returns `(formatted_string, is_multiline)`.
	/// Short expressions are returned as-is. Long expressions are wrapped in a
	/// temporary function, formatted with prettyplease + rustfmt, and then extracted.
	fn format_rust_expression(&self, expr: &syn::Expr, base_indent: usize) -> (String, bool) {
		let cleaned = Self::clean_expression_spaces(&expr.to_token_stream().to_string());

		// Estimate the total line length: indent + "{ " + expr + " }"
		// Use 4 as the display width per indent level (tab = 4 spaces equivalent)
		let indent_width = base_indent * 4;
		let total_len = indent_width + 2 + cleaned.len() + 2; // "{ " and " }"

		if total_len <= EXPRESSION_LINE_LENGTH_THRESHOLD {
			return (cleaned, false);
		}

		// Wrap in a valid Rust file for formatting
		let wrapper_code = format!(
			"fn _wrapper() {{ let _handler = {}; }}",
			expr.to_token_stream()
		);

		// Protect nested page! macros before formatting
		let protect_result = self.protect_page_macros(&wrapper_code);

		// Parse with syn
		let Ok(file) = syn::parse_file(&protect_result.protected_content) else {
			return (cleaned, false);
		};

		// Format with prettyplease + rustfmt
		let prettyplease_output = prettyplease::unparse(&file);
		let formatted = self.format_with_rustfmt(&prettyplease_output);

		// Restore nested page! macros
		let restored = Self::restore_page_macros(&formatted, &protect_result.backups);

		// Extract the expression from the wrapper
		let Some(expr_str) = Self::extract_handler_from_wrapper(&restored) else {
			return (cleaned, false);
		};

		// Apply base indentation
		let indented = self.apply_base_indent(&expr_str, base_indent);
		let is_multiline = indented.contains('\n');
		(indented, is_multiline)
	}

	/// Format an expression node.
	///
	/// Short expressions are kept on a single line. Long expressions are formatted
	/// with rustfmt and rendered as a multiline braced block.
	fn format_expression(&self, output: &mut String, expr: &PageExpression, indent: usize) {
		let ind = self.make_indent(indent);
		output.push_str(&ind);

		let (formatted, is_multiline) = self.format_rust_expression(&expr.expr, indent + 1);

		if expr.braced {
			if is_multiline {
				let inner_ind = self.make_indent(indent + 1);
				output.push_str("{\n");
				output.push_str(&inner_ind);
				output.push_str(&formatted);
				output.push('\n');
				output.push_str(&ind);
				output.push_str("}\n");
			} else {
				output.push_str("{ ");
				output.push_str(&formatted);
				output.push_str(" }\n");
			}
		} else {
			output.push_str(&formatted);
			output.push('\n');
		}
	}

	/// Format an if node.
	fn format_if(&self, output: &mut String, if_node: &PageIf, indent: usize, depth: usize) {
		let ind = self.make_indent(indent);

		// if condition {
		output.push_str(&ind);
		output.push_str("if ");
		output.push_str(&Self::clean_expression_spaces(
			&if_node.condition.to_token_stream().to_string(),
		));
		output.push_str(" {\n");

		// then branch
		for node in &if_node.then_branch {
			self.format_node(output, node, indent + 1, depth + 1);
		}

		// else branch
		match &if_node.else_branch {
			Some(PageElse::Block(nodes)) => {
				output.push_str(&ind);
				output.push_str("} else {\n");
				for node in nodes {
					self.format_node(output, node, indent + 1, depth + 1);
				}
				output.push_str(&ind);
				output.push_str("}\n");
			}
			Some(PageElse::If(nested_if)) => {
				output.push_str(&ind);
				output.push_str("} else ");
				// Format the nested if without initial indent
				self.format_if_inline(output, nested_if, indent, depth + 1);
			}
			None => {
				output.push_str(&ind);
				output.push_str("}\n");
			}
		}
	}

	/// Format an if node inline (for else if chains).
	fn format_if_inline(&self, output: &mut String, if_node: &PageIf, indent: usize, depth: usize) {
		if depth > MAX_FORMAT_DEPTH {
			output.push_str("/* else-if chain depth limit exceeded */ {}\n");
			return;
		}

		let ind = self.make_indent(indent);

		output.push_str("if ");
		output.push_str(&Self::clean_expression_spaces(
			&if_node.condition.to_token_stream().to_string(),
		));
		output.push_str(" {\n");

		for node in &if_node.then_branch {
			self.format_node(output, node, indent + 1, depth + 1);
		}

		match &if_node.else_branch {
			Some(PageElse::Block(nodes)) => {
				output.push_str(&ind);
				output.push_str("} else {\n");
				for node in nodes {
					self.format_node(output, node, indent + 1, depth + 1);
				}
				output.push_str(&ind);
				output.push_str("}\n");
			}
			Some(PageElse::If(nested_if)) => {
				output.push_str(&ind);
				output.push_str("} else ");
				self.format_if_inline(output, nested_if, indent, depth + 1);
			}
			None => {
				output.push_str(&ind);
				output.push_str("}\n");
			}
		}
	}

	/// Format a for node.
	fn format_for(&self, output: &mut String, for_node: &PageFor, indent: usize, depth: usize) {
		let ind = self.make_indent(indent);

		output.push_str(&ind);
		output.push_str("for ");
		output.push_str(&Self::clean_expression_spaces(
			&for_node.pat.to_token_stream().to_string(),
		));
		output.push_str(" in ");
		output.push_str(&Self::clean_expression_spaces(
			&for_node.iter.to_token_stream().to_string(),
		));
		output.push_str(" {\n");

		for node in &for_node.body {
			self.format_node(output, node, indent + 1, depth + 1);
		}

		output.push_str(&ind);
		output.push_str("}\n");
	}

	/// Format a watch node.
	fn format_watch(
		&self,
		output: &mut String,
		watch_node: &reinhardt_pages::ast::PageWatch,
		indent: usize,
		depth: usize,
	) {
		let ind = self.make_indent(indent);

		output.push_str(&ind);
		output.push_str("watch {\n");

		self.format_node(output, &watch_node.expr, indent + 1, depth + 1);

		output.push_str(&ind);
		output.push_str("}\n");
	}

	/// Format a component call.
	fn format_component(
		&self,
		output: &mut String,
		comp: &PageComponent,
		indent: usize,
		depth: usize,
	) {
		let ind = self.make_indent(indent);

		output.push_str(&ind);
		output.push_str(&comp.name.to_string());
		output.push('(');

		// Arguments
		for (i, arg) in comp.args.iter().enumerate() {
			if i > 0 {
				output.push_str(", ");
			}
			output.push_str(&arg.name.to_string());
			output.push_str(": ");
			output.push_str(&Self::clean_expression_spaces(
				&arg.value.to_token_stream().to_string(),
			));
		}

		output.push(')');

		// Children
		if let Some(children) = &comp.children {
			output.push_str(" {\n");
			for child in children {
				self.format_node(output, child, indent + 1, depth + 1);
			}
			output.push_str(&ind);
			output.push('}');
		}

		output.push('\n');
	}

	/// Create indentation string.
	fn make_indent(&self, level: usize) -> String {
		self.indent.repeat(level)
	}

	/// Check if the file has an ignore-all marker at the beginning.
	///
	/// This checks the first 50 lines of the file for a comment containing
	/// `reinhardt-fmt:ignore-all`. The marker must appear before any code line.
	pub(crate) fn has_ignore_all_marker(&self, source: &str) -> bool {
		const MARKER: &str = "reinhardt-fmt:ignore-all";

		// Check only the first 50 lines for performance
		for line in source.lines().take(50) {
			let trimmed = line.trim();

			// Check comment lines only
			if let Some(comment) = trimmed.strip_prefix("//") {
				let comment_content = comment.trim();
				// Remove spaces for flexible matching
				if comment_content.replace(' ', "").contains(MARKER) {
					return true;
				}
			}

			// Stop at first code line (non-comment, non-empty)
			if !trimmed.is_empty() && !trimmed.starts_with("//") {
				break;
			}
		}
		false
	}

	/// Find all ignore ranges (off/on pairs) in the source code.
	///
	/// Returns a list of byte offset ranges where formatting should be skipped.
	/// Warns if there are nested 'off' markers or unmatched markers.
	fn find_ignore_ranges(&self, source: &str) -> Vec<(usize, usize)> {
		const OFF_MARKER: &str = "reinhardt-fmt:off";
		const ON_MARKER: &str = "reinhardt-fmt:on";

		let mut ranges = Vec::new();
		let mut current_off_start: Option<usize> = None;
		let mut byte_offset = 0;
		let total_len = source.len();

		for line in source.lines() {
			let trimmed = line.trim();

			if let Some(comment) = trimmed.strip_prefix("//") {
				let comment_content = comment.trim().replace(' ', "");

				if comment_content.contains(OFF_MARKER) {
					if current_off_start.is_some() {
						eprintln!(
							"Warning: Nested 'reinhardt-fmt: off' at byte {}",
							byte_offset
						);
						// Don't update current_off_start if already set (nested case)
					} else {
						current_off_start = Some(byte_offset);
					}
				} else if comment_content.contains(ON_MARKER) {
					if let Some(start) = current_off_start.take() {
						ranges.push((start, byte_offset));
					} else {
						eprintln!(
							"Warning: 'reinhardt-fmt: on' without matching 'off' at byte {}",
							byte_offset
						);
					}
				}
			}

			byte_offset += line.len() + 1; // +1 for newline
		}

		// Handle unclosed range - extend to end of file
		if let Some(start) = current_off_start {
			eprintln!("Warning: Unclosed 'reinhardt-fmt: off' at end of file");
			ranges.push((start, total_len));
		}

		ranges
	}

	/// Check if an individual macro has an ignore marker on the previous line.
	///
	/// The marker must be on the line immediately before the macro (no blank lines).
	fn has_individual_ignore_marker(&self, source: &str, macro_start: usize) -> bool {
		const MARKER: &str = "reinhardt-fmt:ignore";

		// If macro is at the start of the file, no previous line exists
		if macro_start == 0 {
			return false;
		}

		// Find the start of the current line (where the macro is)
		let line_start = source[..macro_start]
			.rfind('\n')
			.map(|pos| pos + 1)
			.unwrap_or(0);

		// If this is the first line, no previous line exists
		if line_start == 0 {
			return false;
		}

		// Find the end of the previous line (newline character position)
		let prev_line_end = line_start - 1; // This is the '\n' character

		// Find the start of the previous line
		let prev_line_start = source[..prev_line_end]
			.rfind('\n')
			.map(|pos| pos + 1)
			.unwrap_or(0);

		// Extract the previous line
		let prev_line = &source[prev_line_start..prev_line_end];
		let trimmed = prev_line.trim();

		// Check if it's a comment with the ignore marker
		if let Some(comment) = trimmed.strip_prefix("//") {
			let comment_content = comment.trim().replace(' ', "");
			return comment_content.contains(MARKER);
		}

		false
	}

	/// Apply ignore markers to macros, setting their should_skip flags.
	///
	/// Priority order:
	/// 1. Individual macro ignore (highest) - implemented in Phase 3
	/// 2. Range ignore (medium) - implemented in Phase 2
	/// 3. File-wide ignore (lowest) - handled in format() method
	fn apply_ignore_markers(&self, source: &str, macros: &mut [MacroInfo]) {
		// Find all ignore ranges
		let ignore_ranges = self.find_ignore_ranges(source);

		// Apply markers to each macro
		for macro_info in macros.iter_mut() {
			// Priority 1: Individual macro ignore (highest priority)
			if self.has_individual_ignore_marker(source, macro_info.start) {
				macro_info.should_skip = true;
				continue;
			}

			// Priority 2: Range ignore (medium priority)
			for (range_start, range_end) in &ignore_ranges {
				if macro_info.start >= *range_start && macro_info.start < *range_end {
					macro_info.should_skip = true;
					break;
				}
			}

			// Priority 3: File-wide ignore is already handled in format()
		}
	}

	/// Protect page! macros by replacing them with placeholders.
	///
	/// This allows rustfmt to process the surrounding Rust code without
	/// modifying the page! macro contents. The macros can be restored
	/// using `restore_page_macros`.
	///
	/// # Placeholder Format
	///
	/// Each page! macro is replaced with:
	/// ```text
	/// __reinhardt_placeholder__!(/*n*/)
	/// ```
	/// where `n` is a unique identifier.
	///
	/// # Example
	///
	/// ```text
	/// // Before:
	/// let view = page!(|| { div { "hello" } })(props);
	///
	/// // After:
	/// let view = __reinhardt_placeholder__!(/*0*/)(props);
	/// ```
	pub(crate) fn protect_page_macros(&self, content: &str) -> ProtectResult {
		// Quick check: if no page! pattern exists, return unchanged
		if !content.contains("page!(") {
			return ProtectResult {
				protected_content: content.to_string(),
				backups: Vec::new(),
			};
		}

		// Find all page! macros
		let macros = match self.find_page_macros(content) {
			Ok(m) => m,
			Err(_) => {
				return ProtectResult {
					protected_content: content.to_string(),
					backups: Vec::new(),
				};
			}
		};

		if macros.is_empty() {
			return ProtectResult {
				protected_content: content.to_string(),
				backups: Vec::new(),
			};
		}

		// Sort macros by position
		let mut macros = macros;
		macros.sort_by_key(|m| m.start);

		// Build result by replacing each macro with placeholder
		let mut result = String::with_capacity(content.len());
		let mut backups = Vec::with_capacity(macros.len());
		let mut last_end = 0;

		for (id, macro_info) in macros.iter().enumerate() {
			// Copy content before this macro
			result.push_str(&content[last_end..macro_info.start]);

			// Save original macro text
			let original = content[macro_info.start..macro_info.end].to_string();
			backups.push(PageMacroBackup { id, original });

			// Insert placeholder (macro format so rustfmt doesn't touch it)
			result.push_str(&format!("__reinhardt_placeholder__!(/*{}*/)", id));

			last_end = macro_info.end;
		}

		// Copy remaining content
		result.push_str(&content[last_end..]);

		ProtectResult {
			protected_content: result,
			backups,
		}
	}

	/// Restore page! macros from placeholders.
	///
	/// This reverses the effect of `protect_page_macros`, replacing
	/// placeholders with the original page! macro content.
	pub(crate) fn restore_page_macros(content: &str, backups: &[PageMacroBackup]) -> String {
		if backups.is_empty() {
			return content.to_string();
		}

		let mut result = content.to_string();

		// Replace placeholders in reverse order to maintain correct positions
		for backup in backups.iter().rev() {
			let placeholder = format!("__reinhardt_placeholder__!(/*{}*/)", backup.id);
			result = result.replace(&placeholder, &backup.original);
		}

		result
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use rstest::rstest;

	#[rstest]
	fn test_format_simple_element() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { "hello" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("div {"));
		assert!(result.content.contains("\"hello\""));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_with_attributes() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div class="foo" { "hello" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("div"));
		assert!(result.content.contains("class"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_no_change_non_page() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = "fn main() { println!(\"hello\"); }";

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(input, result.content);
		assert!(!result.contains_page_macro);
	}

	#[rstest]
	fn test_skip_page_in_string() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"fn main() { let s = "page!(|| { div { } })"; }"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("page!(|| { div { } })"));
		assert!(!result.contains_page_macro);
	}

	#[rstest]
	fn test_skip_page_in_comment() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// page!(|| { div { } })
fn main() {}"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("// page!(|| { div { } })"));
		assert!(!result.contains_page_macro);
	}

	#[rstest]
	fn test_format_with_params() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|name: String| { div { { name } } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("name: String"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_nested_elements() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { p { "hello" } } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("div {"));
		assert!(result.content.contains("p {"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_if_node() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { @if true { div { } } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("@if"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_for_node() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { @for item in items { div { } } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("@for"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_component() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { <MyComponent /> })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("<MyComponent"));
		assert!(result.content.contains("/>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_event_handler() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { button { @click: |_| {}, "Click" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("@click"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_safety_complex_non_page_file() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"
//! Module documentation

use std::collections::HashMap;

/// A complex struct
#[derive(Debug, Clone)]
pub struct MyStruct<T> {
	field: T,
}

impl<T> MyStruct<T> {
	pub fn new(field: T) -> Self {
		Self { field }
	}
}

// Some comment about the function
fn complex_function(x: i32, y: i32) -> i32 {
	x + y
}

#[cfg(test)]
mod tests {
	#[test]
	fn test_something() {
		assert_eq!(2 + 2, 4);
	}
}
"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(input, result.content);
		assert!(!result.contains_page_macro);
	}

	// ========================================
	// Tests for generic type formatting
	// ========================================

	#[rstest]
	fn test_format_params_with_vec() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|items: Vec<String>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("items: Vec<String>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_option() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|value: Option<i32>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("value: Option<i32>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_result() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|res: Result<String, Error>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("res: Result<String, Error>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_nested_generics() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|items: Vec<Option<String>>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("items: Vec<Option<String>>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_multiple_generics() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|map: HashMap<String, i32>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("map: HashMap<String, i32>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_references() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|s: &str| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("s: &str"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_arrays() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|arr: [i32; 5]| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("arr: [i32; 5]"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_tuples() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|t: (String, i32)| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("t: (String, i32)"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_path_types() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|v: std::vec::Vec<String>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("v: std::vec::Vec<String>"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_with_complex_types() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|f: Box<dyn Fn() -> Result<(), Error>>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(
			result
				.content
				.contains("f: Box<dyn Fn() -> Result<(), Error>>")
		);
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_params_types_idempotent() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|vec: Vec<String>, opt: Option<i32>, res: Result<String, Error>| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();
		// Format again to ensure idempotency
		let result2 = formatter.format(&result.content).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, result2.content);
		assert!(result2.contains_page_macro);
	}

	#[rstest]
	fn test_format_macro_calls() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| {
			div { { format!("Hello {}", name) } }
		})"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("format!"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_function_calls() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| {
			div { { get_message() } }
		})"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("get_message()"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_method_calls() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| {
			div { { user.get_name() } }
		})"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("user.get_name()"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_format_complex_event_handler() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| {
			button {
				@click: |event| {
					prevent_default(event);
					handle_click();
				},
				"Click Me"
			}
		})"#;

		// Act
		let result = formatter.format(input).unwrap();
		// Format should be idempotent
		let result2 = formatter.format(&result.content).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.content.contains("button"));
		assert!(result.content.contains("@click"));
		assert!(result.content.contains("|event|"));
		assert!(result.content.contains("prevent_default(event)"));
		assert!(result.content.contains("handle_click()"));
		assert!(result.content.contains("\"Click Me\""));
		assert_eq!(result.content, result2.content);
		assert!(result2.contains_page_macro);
	}

	#[rstest]
	fn test_format_function_macro_calls_idempotent() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| {
			div {
				{ format!("Count: {}", count) }
				{ get_user().name() }
				{ vec![1, 2, 3].len() }
			}
		})"#;

		// Act
		let result = formatter.format(input).unwrap();
		let result2 = formatter.format(&result.content).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, result2.content);
		assert!(result2.contains_page_macro);
	}

	// ==================== Ignore Marker Tests ====================

	#[rstest]
	fn test_ignore_all_at_file_start() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-all

page!(|| {
div{badly}
})"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert_eq!(input, result.content);
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_all_after_module_doc() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"//! Module documentation
// reinhardt-fmt: ignore-all

page!(|| {
div{badly}
})"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert_eq!(input, result.content);
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_all_not_at_start() {
		// When ignore-all marker appears AFTER code lines, it should NOT be recognized
		// because the marker must appear BEFORE any code line (as documented).

		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"use foo;

// reinhardt-fmt: ignore-all

page!(|| {
div{badly}
})"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.contains_page_macro);
		assert!(result.content.contains("div {"));
		assert!(result.content.contains("badly"));
	}

	#[rstest]
	fn test_ignore_range_basic() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-on
page!(|| {
div{badly}
})
// reinhardt-fmt: ignore-off

page!(|| { div { "formatted" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{badly}"));
		assert!(result.content.contains("div {"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_range_nested_warning() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-on
page!(|| { div { "first" } })
// reinhardt-fmt: ignore-on
page!(|| { div { "second" } })
// reinhardt-fmt: ignore-off
page!(|| { div { "third" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("first"));
		assert!(result.content.contains("second"));
		assert!(result.content.contains("third"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_range_unmatched_on() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-on
page!(|| { div { "first" } })
page!(|| { div { "second" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("first"));
		assert!(result.content.contains("second"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_range_unclosed() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { "before" } })
// reinhardt-fmt: ignore-on
page!(|| { div{badly} })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{badly}"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_multiple_ignore_ranges() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { "formatted1" } })
// reinhardt-fmt: ignore-on
page!(|| { div{ignored1} })
// reinhardt-fmt: ignore-off
page!(|| { div { "formatted2" } })
// reinhardt-fmt: ignore-on
page!(|| { div{ignored2} })
// reinhardt-fmt: ignore-off
page!(|| { div { "formatted3" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{ignored1}"));
		assert!(result.content.contains("div{ignored2}"));
		assert!(result.content.contains("div {"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_individual_ignore_basic() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { "formatted" } })

// reinhardt-fmt: ignore
page!(|| { div{ignored} })

page!(|| { div { "formatted" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{ignored}"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_individual_ignore_with_blank_line() {
		// When there's a blank line between the ignore marker and the macro,
		// the marker should NOT be recognized (as documented: marker must be on
		// the line immediately before the macro, with no blank lines).

		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore

page!(|| { div{ignored} })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.contains_page_macro);
		assert!(result.content.contains("div {"));
		assert!(result.content.contains("ignored"));
	}

	#[rstest]
	fn test_individual_ignore_multiple() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore
page!(|| { div{ignored1} })

page!(|| { div { "formatted" } })

// reinhardt-fmt: ignore
page!(|| { div{ignored2} })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{ignored1}"));
		assert!(result.content.contains("div{ignored2}"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_individual_ignore_mixed_with_format() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { "formatted1" } })

// reinhardt-fmt: ignore
page!(|| { div{ignored} })

page!(|| { div { "formatted2" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{ignored}"));
		assert!(result.content.contains("div {"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_individual_ignore_with_range() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-on
page!(|| { div{range_ignored} })
// reinhardt-fmt: ignore-off

// reinhardt-fmt: ignore
page!(|| { div{individual_ignored} })

page!(|| { div { "formatted" } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{range_ignored}"));
		assert!(result.content.contains("div{individual_ignored}"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_individual_ignore_priority() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-on
// reinhardt-fmt: ignore
page!(|| { div{ignored} })
// reinhardt-fmt: ignore-off"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{ignored}"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_individual_ignore_at_file_start() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore
page!(|| { div{ignored} })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.content.contains("div{ignored}"));
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_contains_page_macro_field_with_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|| { div { } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_contains_page_macro_field_without_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"fn main() { println!("test"); }"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert!(!result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_all_with_page_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-all
page!(|| { div { bad } })"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert_eq!(result.content, input);
		assert!(result.contains_page_macro);
	}

	#[rstest]
	fn test_ignore_all_without_page_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"// reinhardt-fmt: ignore-all
fn main() {}"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert_eq!(result.content, input);
		assert!(!result.contains_page_macro);
	}

	// ==================== Protect/Restore Tests ====================

	#[rstest]
	fn test_protect_no_page_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = "fn main() { println!(\"hello\"); }";

		// Act
		let result = formatter.protect_page_macros(input);

		// Assert
		assert_eq!(result.protected_content, input);
		assert!(result.backups.is_empty());
	}

	#[rstest]
	fn test_protect_single_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"let view = page!(|| { div { "hello" } });"#;

		// Act
		let result = formatter.protect_page_macros(input);

		// Assert
		assert!(
			result
				.protected_content
				.contains("__reinhardt_placeholder__!(/*0*/)")
		);
		assert!(!result.protected_content.contains("page!("));
		assert_eq!(result.backups.len(), 1);
		assert_eq!(result.backups[0].id, 0);
		assert!(result.backups[0].original.starts_with("page!("));
	}

	#[rstest]
	fn test_protect_multiple_macros() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"
let view1 = page!(|| { div { "first" } });
let view2 = page!(|| { div { "second" } });
"#;

		// Act
		let result = formatter.protect_page_macros(input);

		// Assert
		assert!(
			result
				.protected_content
				.contains("__reinhardt_placeholder__!(/*0*/)")
		);
		assert!(
			result
				.protected_content
				.contains("__reinhardt_placeholder__!(/*1*/)")
		);
		assert!(!result.protected_content.contains("page!("));
		assert_eq!(result.backups.len(), 2);
	}

	#[rstest]
	fn test_protect_preserves_surrounding_code() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"use foo::bar;

fn render() -> View {
    page!(|| { div { "hello" } })
}

fn main() {}"#;

		// Act
		let result = formatter.protect_page_macros(input);

		// Assert
		assert!(result.protected_content.contains("use foo::bar;"));
		assert!(result.protected_content.contains("fn render() -> View"));
		assert!(result.protected_content.contains("fn main() {}"));
		assert!(
			result
				.protected_content
				.contains("__reinhardt_placeholder__!(/*0*/)")
		);
	}

	#[rstest]
	fn test_restore_single_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let original = r#"let view = page!(|| { div { "hello" } });"#;

		// Act
		let protected = formatter.protect_page_macros(original);
		let restored =
			AstPageFormatter::restore_page_macros(&protected.protected_content, &protected.backups);

		// Assert
		assert_eq!(restored, original);
	}

	#[rstest]
	fn test_restore_multiple_macros() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let original = r#"
let view1 = page!(|| { div { "first" } });
let view2 = page!(|| { div { "second" } });
"#;

		// Act
		let protected = formatter.protect_page_macros(original);
		let restored =
			AstPageFormatter::restore_page_macros(&protected.protected_content, &protected.backups);

		// Assert
		assert_eq!(restored, original);
	}

	#[rstest]
	fn test_protect_restore_roundtrip_complex() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let original = r#"use reinhardt::pages::page;

fn header() -> View {
    page!(|| {
        div {
            class: "header",
            h1 { "Title" }
        }
    })
}

fn footer() -> View {
    page!(|year: i32| {
        div {
            class: "footer",
            { format!("Copyright {}", year) }
        }
    })
}

fn main() {
    let _h = header();
    let _f = footer();
}"#;

		// Act
		let protected = formatter.protect_page_macros(original);
		let restored =
			AstPageFormatter::restore_page_macros(&protected.protected_content, &protected.backups);

		// Assert
		assert_eq!(protected.backups.len(), 2);
		assert!(!protected.protected_content.contains("page!("));
		assert_eq!(restored, original);
	}

	#[rstest]
	fn test_protect_empty_backups_restore() {
		// Arrange
		let content = "fn main() {}";
		let backups: Vec<PageMacroBackup> = Vec::new();

		// Act
		let restored = AstPageFormatter::restore_page_macros(content, &backups);

		// Assert
		assert_eq!(restored, content);
	}

	#[rstest]
	fn test_protect_with_trailing_call() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"let view = page!(|props: Props| { div { } })(props);"#;

		// Act
		let result = formatter.protect_page_macros(input);
		let restored =
			AstPageFormatter::restore_page_macros(&result.protected_content, &result.backups);

		// Assert
		assert!(
			result
				.protected_content
				.contains("__reinhardt_placeholder__!(/*0*/)(props)")
		);
		assert_eq!(result.backups.len(), 1);
		assert_eq!(restored, input);
	}

	// ==================== Unicode Character Tests ====================

	#[rstest]
	fn test_find_matching_paren_with_emoji() {
		// Arrange
		let source = r#"(div { "πŸ˜€" })"#;

		// Act
		let result = find_matching_paren(source, 1);

		// Assert
		assert_eq!(result, Some(source.len() - 1));
	}

	#[rstest]
	fn test_find_matching_paren_with_cjk() {
		// Arrange
		let source = r#"(div { "ζ—₯本θͺž" })"#;

		// Act
		let result = find_matching_paren(source, 1);

		// Assert
		assert_eq!(result, Some(source.len() - 1));
	}

	#[rstest]
	fn test_find_matching_paren_nested_with_unicode() {
		// Arrange
		let source = r#"(outer { (inner { "μ•ˆλ…•" }) })"#;

		// Act
		let result = find_matching_paren(source, 1);

		// Assert
		assert_eq!(result, Some(source.len() - 1));
	}

	#[rstest]
	fn test_find_matching_paren_mixed() {
		// Arrange
		let source = r#"(div { "Hello δΈ–η•Œ Ω…Ψ±Ψ­Ψ¨Ψ§" })"#;

		// Act
		let result = find_matching_paren(source, 1);

		// Assert
		assert_eq!(result, Some(source.len() - 1));
	}

	#[rstest]
	fn test_is_in_comment_or_string_unicode_in_string() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let content = r#"let s = "πŸ˜€πŸŽ‰ζ—₯本θͺž";"#;
		let pos_in_string = content.find("ζ—₯").unwrap();

		// Act & Assert
		assert!(formatter.is_in_comment_or_string(content, pos_in_string));
	}

	#[rstest]
	fn test_is_in_comment_or_string_unicode_in_comment() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let content = r#"// This is a comment with ζ—₯本θͺž"#;
		let pos_in_comment = content.find("ζ—₯").unwrap();

		// Act & Assert
		assert!(formatter.is_in_comment_or_string(content, pos_in_comment));
	}

	#[rstest]
	fn test_protect_restore_with_unicode_content() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let original = r#"let view = page!(|| { div { "πŸ˜€πŸŽ‰ζ—₯本θͺž" } });"#;

		// Act
		let protected = formatter.protect_page_macros(original);
		let restored =
			AstPageFormatter::restore_page_macros(&protected.protected_content, &protected.backups);

		// Assert
		assert_eq!(protected.backups.len(), 1);
		assert!(
			protected
				.protected_content
				.contains("__reinhardt_placeholder__")
		);
		assert_eq!(restored, original);
	}

	// ========================================
	// Tests for expression formatting with rustfmt
	// ========================================

	// Short expressions: stay on a single line

	#[rstest]
	fn test_format_expression_short_braced() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter.format(r#"page!(|| { { some_value } })"#).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ some_value }\n})");
	}

	#[rstest]
	fn test_format_expression_short_unbraced() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter.format(r#"page!(|| { some_value })"#).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\tsome_value\n})");
	}

	#[rstest]
	fn test_format_expression_short_method_call() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter
			.format(r#"page!(|| { { items.len() } })"#)
			.unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ items.len() }\n})");
	}

	#[rstest]
	fn test_format_expression_short_string_literal() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter
			.format(r#"page!(|| { { "hello world" } })"#)
			.unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ \"hello world\" }\n})");
	}

	#[rstest]
	fn test_format_expression_empty_braced() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter.format(r#"page!(|| { { () } })"#).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ () }\n})");
	}

	#[rstest]
	fn test_format_expression_numeric_literal() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter.format(r#"page!(|| { { 42 } })"#).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ 42 }\n})");
	}

	#[rstest]
	fn test_format_expression_boolean() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter.format(r#"page!(|| { { true } })"#).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ true }\n})");
	}

	#[rstest]
	fn test_format_expression_binary_op() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter.format(r#"page!(|| { { x + y } })"#).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(result.content, "page!(|| {\n\t{ x + y }\n})");
	}

	#[rstest]
	fn test_format_expression_with_closure_under_threshold() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter
			.format(
				r#"page!(|| { { items.iter().map(|item| item.render()).collect::<Vec<_>>() } })"#,
			)
			.unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\t{ items.iter().map(|item| item.render()).collect::<Vec<_>>() }\n})"
		);
	}

	#[rstest]
	fn test_format_expression_with_if_condition() {
		// Arrange
		let formatter = AstPageFormatter::new();

		// Act
		let result = formatter
			.format("page!(|| {\n\tif condition {\n\t\t{ short_val }\n\t}\n})")
			.unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\tif condition {\n\t\t{ short_val }\n\t}\n})"
		);
	}

	#[rstest]
	fn test_format_expression_exactly_at_threshold() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let expr = "a".repeat(90);
		let input = format!("page!(|| {{ {{ {} }} }})", expr);

		// Act
		let result = formatter.format(&input);

		// Assert
		assert!(result.is_ok());
	}

	// Long expressions: multiline formatting via rustfmt

	#[rstest]
	fn test_format_expression_long_view_fragment() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = format!(
			"page!(|| {{ {{ {} }} }})",
			"View::fragment(signal.result().unwrap_or_default().iter().map(|item| View::text(item.clone())).collect::<Vec<_>>())"
		);

		// Act
		let result = formatter.format(&input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\t{\n\t\tView::fragment(\n\t\t\t\tsignal\n\t\t\t\t\t.result()\n\t\t\t\t\t.unwrap_or_default()\n\t\t\t\t\t.iter()\n\t\t\t\t\t.map(|item| View::text(item.clone()))\n\t\t\t\t\t.collect::<Vec<_>>(),\n\t\t\t)\n\t}\n})"
		);
	}

	#[rstest]
	fn test_format_expression_long_chained_methods() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = format!(
			"page!(|| {{ {{ {} }} }})",
			r#"data.iter().filter(|x| x.is_active()).map(|x| x.name.clone()).collect::<Vec<String>>().join(", ")"#
		);

		// Act
		let result = formatter.format(&input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\t{\n\t\tdata\n\t\t\t\t.iter()\n\t\t\t\t.filter(|x| x.is_active())\n\t\t\t\t.map(|x| x.name.clone())\n\t\t\t\t.collect::<Vec<String>>()\n\t\t\t\t.join(\", \")\n\t}\n})"
		);
	}

	#[rstest]
	fn test_format_expression_long_nested_function_calls() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = format!(
			"page!(|| {{ {{ {} }} }})",
			r#"format!("User: {} ({})", user.display_name().unwrap_or_default(), user.email().unwrap_or("no email".to_string()))"#
		);

		// Act
		let result = formatter.format(&input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\t{\n\t\tformat!(\n\t\t\t\t\"User: {} ({})\",\n\t\t\t\tuser.display_name().unwrap_or_default(),\n\t\t\t\tuser.email().unwrap_or(\"no email\".to_string())\n\t\t\t)\n\t}\n})"
		);
	}

	#[rstest]
	fn test_format_expression_deeply_nested_in_elements() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = format!(
			r#"page!(|| {{ div {{ span {{ {{ {} }} }} }} }})"#,
			"View::fragment(signal.result().unwrap_or_default().iter().map(|item| View::text(item.clone())).collect::<Vec<_>>())"
		);

		// Act
		let result = formatter.format(&input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\tdiv {\n\t\tspan {\n\t\t\t{\n\t\t\t\tView::fragment(\n\t\t\t\t\t\tsignal\n\t\t\t\t\t\t\t.result()\n\t\t\t\t\t\t\t.unwrap_or_default()\n\t\t\t\t\t\t\t.iter()\n\t\t\t\t\t\t\t.map(|item| View::text(item.clone()))\n\t\t\t\t\t\t\t.collect::<Vec<_>>(),\n\t\t\t\t\t)\n\t\t\t}\n\t\t}\n\t}\n})"
		);
	}

	#[rstest]
	fn test_format_expression_multiple_in_page() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = format!(
			"page!(|| {{ {{ {} }} {{ {} }} }})",
			"count",
			"View::fragment(signal.result().unwrap_or_default().iter().map(|item| View::text(item.clone())).collect::<Vec<_>>())"
		);

		// Act
		let result = formatter.format(&input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|| {\n\t{ count }\n\t{\n\t\tView::fragment(\n\t\t\t\tsignal\n\t\t\t\t\t.result()\n\t\t\t\t\t.unwrap_or_default()\n\t\t\t\t\t.iter()\n\t\t\t\t\t.map(|item| View::text(item.clone()))\n\t\t\t\t\t.collect::<Vec<_>>(),\n\t\t\t)\n\t}\n})"
		);
	}

	// Complex DSL formatting tests

	#[rstest]
	fn test_format_complex_dsl_nested_page_macro() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|signal: Action<Vec<Item>, String>| {
	div {
		{ View::fragment(signal.result().unwrap_or_default().iter().map(|item| { let text = item.text.clone(); page!(|text: String| { span { { text } } })(text) }).collect::<Vec<_>>()) }
	}
})(signal)"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|signal: Action<Vec<Item>, String>| {\n\tdiv {\n\t\t{\n\t\t\tView::fragment(\n\t\t\t\t\tsignal\n\t\t\t\t\t\t.result()\n\t\t\t\t\t\t.unwrap_or_default()\n\t\t\t\t\t\t.iter()\n\t\t\t\t\t\t.map(|item| {\n\t\t\t\t\t\t\tlet text = item.text.clone();\n\t\t\t\t\t\t\tpage!(| text : String | { span { { text } } })(text)\n\t\t\t\t\t\t})\n\t\t\t\t\t\t.collect::<Vec<_>>(),\n\t\t\t\t)\n\t\t}\n\t}\n})(signal)"
		);
	}

	#[rstest]
	fn test_format_complex_dsl_conditional() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|signal: Action<Vec<Item>, String>| {
	div {
		if signal.result().is_some() {
			{ View::fragment(signal.result().unwrap_or_default().iter().map(|item| { let text = item.text.clone(); page!(|text: String| { div class="item" { { text } } })(text) }).collect::<Vec<_>>()) }
		} else {
			p { "Loading..." }
		}
	}
})(signal)"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|signal: Action<Vec<Item>, String>| {\n\tdiv {\n\t\tif signal.result().is_some() {\n\t\t\t{\n\t\t\t\tView::fragment(\n\t\t\t\t\t\tsignal\n\t\t\t\t\t\t\t.result()\n\t\t\t\t\t\t\t.unwrap_or_default()\n\t\t\t\t\t\t\t.iter()\n\t\t\t\t\t\t\t.map(|item| {\n\t\t\t\t\t\t\t\tlet text = item.text.clone();\n\t\t\t\t\t\t\t\tpage!(| text : String | { div class = \"item\" { { text } } })(text)\n\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t.collect::<Vec<_>>(),\n\t\t\t\t\t)\n\t\t\t}\n\t\t} else {\n\t\t\tp {\n\t\t\t\t\"Loading...\"\n\t\t\t}\n\t\t}\n\t}\n})(signal)"
		);
	}

	#[rstest]
	fn test_format_complex_dsl_for_loop() {
		// Arrange
		let formatter = AstPageFormatter::new();
		let input = r#"page!(|items: Vec<Item>| {
	div class="list" {
		for item in items {
			div class="card" {
				{ View::fragment(item.tags.iter().map(|tag| { let t = tag.clone(); page!(|t: String| { span class="tag" { { t } } })(t) }).collect::<Vec<_>>()) }
			}
		}
	}
})(items)"#;

		// Act
		let result = formatter.format(input).unwrap();

		// Assert
		assert!(result.skipped.is_none(), "formatting should not be skipped");
		assert_eq!(
			result.content,
			"page!(|items: Vec<Item>| {\n\tdiv class=\"list\" {\n\t\tfor item in items {\n\t\t\tdiv class=\"card\" {\n\t\t\t\t{ View::fragment(item.tags.iter().map(|tag| { let t = tag.clone(); page!(|t: String| { span class=\"tag\" { { t } } })(t) }).collect::<Vec<_>>()) }\n\t\t\t}\n\t\t}\n\t}\n})(items)"
		);
	}
}