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
package main

import (
	"bytes"
	"context"
	"crypto/sha256"
	"flag"
	"fmt"
	"log"
	"math"
	"os"
	"os/exec"
	"path/filepath"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	tea "github.com/charmbracelet/bubbletea"
	"github.com/charmbracelet/lipgloss"
	"github.com/charmbracelet/x/ansi"
)

var debugLog *os.File
var programStart time.Time
var lastViewOutput string
var logBuffer bytes.Buffer
var viewDurations []time.Duration // Last 10 View() call durations for debug metrics

const helpMarkdown = `# git-blimey Help

## Overview

**git-blimey** is an interactive TUI for browsing git blame information
with syntax highlighting (powered by bat) and commit details.

## Table Columns

- **Commit**: Short commit hash (8 characters)
- ` + "`+`" + `: Extended message indicator
  - Shows ` + "`+`" + ` when commit has descriptive body text
    (beyond git attributes like Signed-off-by)
  - Press **Enter** to view full commit details
- **Author**: Commit author name
  - The emoji is a “hash” of the committer name, for easy distinction
- **Age**: Relative time since commit
  - Color-coded: green (newest) → dim (oldest)
  - Formats: "42 (seconds), '23 (minutes), 5h (hours), 3d (days), 2w (weeks),
    6mo (months), 15y (years)
- **Line #**: Source file line number
- **Content**: Syntax-highlighted code from source file

## Bottom Border

The bottom border displays the **commit subject line** for the currently
selected line:

` + "```" + `
╰─────feat(project): add new feature──────╯
` + "```" + `

When no subject is available, it shows a plain border.

## Navigation

### Main View

  ↑ / k          Move selection up
  ↓ / j          Move selection down
  PgUp           Scroll page up
  PgDown         Scroll page down
  Home / g       Go to first line
  End / G        Go to last line
  Mouse wheel    Scroll up/down
  Left click     Select line

Scrolling (mouse wheel and PgUp/PgDown) moves the viewport independently of
the selection. The selection stays where it is and is only pulled along once
it would leave the visible area: it sticks to the top row when scrolling down
and to the bottom row when scrolling up.

### Detail/Help View

  ↑ / k          Scroll up
  ↓ / j          Scroll down
  PgUp           Scroll page up
  PgDown         Scroll page down
  Home / g       Scroll to top
  End / G        Scroll to bottom
  Mouse wheel    Scroll up/down
  q              Close detail/help view

## Actions

  Enter          Show commit details for selected line
  a              Show git log for author of selected line
  e              Open file at current line in $EDITOR
                 (defaults to micro: https://github.com/zyedidia/micro)
  r              Refresh blame data
  h / F1         Show this help screen
  q              Quit, or return from current view
  Ctrl+C/Ctrl+Q  Force quit
  Ctrl+U         Toggle debug UI (shows update counter and tick rate)

## Features

### Syntax Highlighting

- Source code is highlighted using **bat** with the appropriate
  language syntax
- Commit details are formatted and colorized for readability

### Commit Details

Press **Enter** on any line to view:
- Full commit hash
- Author name and email
- Commit date
- Complete commit message (subject + body)

Scroll through long commit messages using the same navigation keys.

### File Line Targeting

Launch with a line number to position the cursor:

` + "```bash" + `
git-blimey main.go:42
` + "```" + `

Or use ` + "`--viewport-offset`" + ` for editor integration with soft wrapping:

` + "```bash" + `
git-blimey --viewport-offset=71 main.go:100
` + "```" + `

Editor calculates offset accounting for wrapped lines (using micro's Diff API).
Git-blimey adds +3 for its header, preserving cursor's exact screen position.

### Performance

- Asynchronous blame loading with progress indicator
- Extended message detection cached to avoid redundant git calls
- Efficient viewport rendering for large files

## Tips

- Use ` + "`+`" + ` indicator to find commits with detailed explanations
- Commit subject in bottom border provides context while browsing
- Refresh (` + "`r`" + `) after making new commits to update blame data
- Open in editor (` + "`e`" + `) to quickly edit the current line
- git-blimey captures the mouse, so your terminal's own click-drag text
  selection is disabled. Hold **Shift** while dragging to select and copy
  text as usual.

## Tools that improve git-blimey

If you install these tools, git-blimey gets cool extra features!

**bat** - Source code will have syntax hilighting!
          For any format bat supports.

**micro** - Modern, easy-to-use terminal text editor.
            Set $EDITOR or have micro in your PATH.
            https://github.com/zyedidia/micro
`

func logDebug(format string, args ...any) {
	if debugLog != nil {
		fmt.Fprintf(debugLog, format+"\n", args...)
	}
}

// BlameLine represents a single line of the file with its git blame metadata.
// Blame data is loaded incrementally, so HasBlame indicates whether git blame has provided data yet.
type BlameLine struct {
	LineNumber int           // Line number in original file (1-based)
	CommitHash string        // Full 40-character commit SHA that last modified this line
	Author     string        // Author name from git blame
	AuthorTime time.Time     // Commit timestamp for age calculations and color gradient
	Content    ColorizedText // Syntax-highlighted line content from bat
	HasBlame   bool          // Whether blame data has been loaded for this line (false during incremental load)
}

// FileEntry represents a file in directory view with its last modification metadata.
type FileEntry struct {
	Path       string    // Relative path from repository root
	CommitHash string    // Full commit SHA that last modified this file
	Author     string    // Author name from last commit
	AuthorTime time.Time // Timestamp of last commit affecting this file
	Status     string    // Git status: M (modified), A (added), D (deleted), etc.
}

// FileLoadedMsg signals file has been read and initial BlameLine structs created.
// Sent after file read completes but before blame data is loaded (content only, no git info yet).
type FileLoadedMsg struct {
	BlameLines         []BlameLine     // Lines with content but no blame data (HasBlame=false)
	Ctx                context.Context // Context for subsequent blame operations
	TargetLine         int             // Cursor line to select after loading (from <file>:<line> or refresh)
	ViewportOffsetLine int             // Editor's first visible line (from --viewport-offset flag)
	RepoRoot           string          // Git repository root for running git commands
	ContentHash        [32]byte        // SHA256 hash of file contents for change detection
	LastCommitHash     string          // Commit hash that last modified this file (for detecting git operations)
}

// ColorizeCompleteMsg delivers syntax-highlighted content for large files (>10k lines).
// For small files, colorization is done synchronously; for large files, it's async.
type ColorizeCompleteMsg struct {
	ColorizedLines []ColorizedText // List indexed by line number (line 1 at index 0)
}

// spinnerTickMsg triggers periodic UI updates for spinner animation and commit hash checks.
// Sent every 100ms during loading, every 15s when idle.
type spinnerTickMsg struct{}

// switchToFileViewMsg signals that we should switch from directory view to file blame view.
type switchToFileViewMsg struct {
	filename string // Absolute path to the file to open
}

// lastCommitHashLoadedMsg delivers the commit hash that last modified a file.
// Sent after async git log completes, used to establish baseline for commit change detection.
type lastCommitHashLoadedMsg struct {
	commitHash string // Commit hash that last modified this file (empty string if git log failed)
}

// execFinishedMsg signals that an external process (editor, pager) has exited.
// Bubbletea disables mouse reporting before handing the terminal over and does
// not restore it afterwards, so we have to re-enable it ourselves.
type execFinishedMsg struct {
	err error // Error from running the process, nil on success
}

// ExtendedMsgState tracks whether a commit's message has been checked for extended body text.
// Used to show "+" indicator in UI for commits with descriptive body content.
type ExtendedMsgState int

const (
	ExtMsgChecking ExtendedMsgState = iota // Currently checking for extended message (git log task in flight)
	ExtMsgNoBody                           // Confirmed: commit has no extended message (only subject line)
	ExtMsgHasBody                          // Confirmed: commit has extended message body beyond git attributes
)

// CommitExtendedInfo caches information about commit messages to avoid redundant git log calls.
// Stored in Model.commitExtendedInfo map, keyed by commit hash.
type CommitExtendedInfo struct {
	state   ExtendedMsgState // Current check state (checking/no body/has body)
	subject string           // Commit subject line for bottom border display
}

// LoadingState tracks the current phase of async file and blame data loading.
// Used to show appropriate loading indicators and adjust tick rate.
type LoadingState int

const (
	LoadingFile     LoadingState = iota // Reading file from disk and setting up structures
	LoadingBlame                        // Running git blame --incremental to populate blame data
	LoadingComplete                     // All loading finished, blame data is complete
)

// ViewMode determines whether we're viewing a single file's blame or a directory's file list.
type ViewMode int

const (
	FileView      ViewMode = iota // Viewing git blame for a single file
	DirectoryView                 // Viewing recently modified files in a directory
)

// FileLoadStatus tracks whether the file was successfully loaded or encountered an error.
type FileLoadStatus int

const (
	FileLoadSuccess FileLoadStatus = iota // File loaded successfully (default state)
	FileLoadError                         // File load failed (e.g., file not found)
)

type EditorStatus int

const (
	EditorSet      EditorStatus = iota // EDITOR env var is set
	MicroAvailable                     // micro is in PATH
	NoEditorFound                      // No editor available
)

// mouseScrollLines is how many lines one mouse wheel notch scrolls.
// Matches the number of arrow keys terminals synthesize per notch in
// alternate-scroll mode, so the scroll speed feels unchanged.
const mouseScrollLines = 3

// tableFirstRow is the screen row (0-based) of the first table data row.
// Layout: header (0), table top border (1), column headers (2), data (3...).
// This is the same offset the --viewport-offset flag compensates for.
const tableFirstRow = 3

// BlameRowContext holds the context needed for rendering blame table rows.
// This context is captured by column render functions via closures.
type BlameRowContext struct {
	lineNumWidth       int
	oldestCommit       time.Time
	newestCommit       time.Time
	spinnerFrame       int
	commitExtendedInfo map[string]CommitExtendedInfo
}

// BlameRowData wraps a BlameLine with selection state for rendering.
type BlameRowData struct {
	BlameLine  BlameLine
	IsSelected bool
}

// DirectoryRowData wraps a FileEntry with selection state for rendering.
type DirectoryRowData struct {
	FileEntry  FileEntry
	IsSelected bool
}

type Model struct {
	// View mode: Determines whether we're showing file blame or directory listing
	viewMode ViewMode // FileView (showing git blame) or DirectoryView (showing file list)

	// Core data: File content and blame information (for FileView mode)
	blameLines []BlameLine // All lines of the file with their git blame metadata (commit, author, time)

	// Core data: Directory file listing (for DirectoryView mode)
	fileEntries []FileEntry // All files in directory with their last modification metadata

	filename string // Absolute path to the file or directory being viewed
	repoRoot string // Git repository root path (for running git commands relative to repo)

	// Main view: Cursor position and viewport
	selectedRow   int // Currently selected line index (0-based, highlighted row)
	viewportStart int // First visible line index in the scrollable viewport (0-based)
	pageSize      int // Number of lines visible in viewport (calculated from window height minus header/footer)

	// Terminal dimensions
	windowWidth  int // Terminal width in characters (updated by tea.WindowSizeMsg)
	windowHeight int // Terminal height in lines (updated by tea.WindowSizeMsg)

	// Detail/Help view: Scrollable overlay for commit details or help screen
	detailView DetailViewModel // Generic scrollable overlay component

	// Commit metadata for rendering
	oldestCommit       time.Time                     // Oldest commit timestamp in file (for age color gradient scaling)
	newestCommit       time.Time                     // Newest commit timestamp in file (for age color gradient scaling)
	commitExtendedInfo map[string]CommitExtendedInfo // Cache: commit hash -> (subject line, has extended message body)

	// Loading state: Tracks async file load and blame operations
	loadingState       LoadingState       // Current loading phase (LoadingFile -> LoadingBlame -> LoadingComplete)
	fileLoadStatus     FileLoadStatus     // Whether file load succeeded or failed (FileLoadSuccess/FileLoadError)
	linesWithBlame     int                // Number of lines that have received blame data (for progress percentage)
	blameChan          chan tea.Msg       // Channel receiving incremental blame updates from git blame --incremental
	spinnerFrame       int                // Current animation frame (0-9) for loading spinner display
	ctx                context.Context    // Context for cancelling file load and blame operations
	cancelBlame        context.CancelFunc // Function to cancel blame goroutine (on refresh or quit)
	targetLine         int                // Cursor line number to jump to after file loads (from <file>:<line> or refresh)
	viewportOffsetLine int                // Editor's first visible line (from --viewport-offset flag, +3 applied in handleFileLoaded)
	blameStartTime     time.Time          // Time when blame operation started (for timing measurement)

	// Task queue: Throttles concurrent git commit message queries
	runningTasks atomic.Int32 // Atomic counter of currently running git log tasks (for extended message checks)
	pendingTasks []string     // Queue of commit hashes waiting to be checked for extended messages
	tasksMutex   sync.RWMutex // Protects pendingTasks slice from concurrent modifications

	// File watching: Detects external file modifications
	fileWatcher            FileWatcher // Watches file for content changes using fsnotify and SHA256 hashing
	lastCommitHashOriginal string      // Commit hash that last modified file at load time
	lastCommitHash         string      // Current commit hash that last modified file (detects git operations)

	// Editor integration: Opens file at current line in external editor
	editorStatus  EditorStatus // Editor availability status (EditorSet/MicroAvailable/NoEditorFound)
	editorCommand string       // Command to launch editor (from $EDITOR or "micro" fallback)
	editorMessage string       // User-facing message about editor configuration

	// Modal overlay: Error dialogs shown over main view
	modalText ColorizedText // If non-empty, displays centered modal with red border (e.g., editor not found error)

	// Debug mode: Performance metrics and diagnostic info
	debugUI             bool            // Whether to show debug overlay (Ctrl+U to toggle)
	updateCounter       int             // Total number of Update() calls (for tracking render frequency)
	currentTickInterval time.Duration   // Current tick rate (100ms during load, 15s when idle)
	updateDurations     []time.Duration // Last 10 Update() call durations (for avg performance calculation)
	hadSlowUpdate       bool            // Set to true once Update() exceeds 50ms threshold (persists as warning)
}

// addDuration adds a duration to the list, keeping only the last 10 entries
func addDuration(durations []time.Duration, d time.Duration) []time.Duration {
	durations = append(durations, d)
	if len(durations) > 10 {
		durations = durations[1:]
	}
	return durations
}

// averageDuration calculates the average of a list of durations
func averageDuration(durations []time.Duration) time.Duration {
	if len(durations) == 0 {
		return 0
	}
	var sum time.Duration
	for _, d := range durations {
		sum += d
	}
	return sum / time.Duration(len(durations))
}

// getItemCount returns the number of items to display based on viewMode.
// For FileView, returns number of blame lines; for DirectoryView, returns number of file entries.
func (m Model) getItemCount() int {
	if m.viewMode == DirectoryView {
		return len(m.fileEntries)
	}
	return len(m.blameLines)
}

// maxViewportStart returns the largest valid value for viewportStart, i.e. the
// scroll position where the last item sits on the bottom row of the viewport.
// Returns 0 when everything fits on screen.
func (m Model) maxViewportStart() int {
	return max(m.getItemCount()-m.pageSize, 0)
}

// clampSelectionToViewport constrains the selection to the currently visible
// window (and to the valid item range). Used after the viewport moved
// independently of the selection: when scrolling down the selection is pushed
// to the top visible row, when scrolling up to the bottom visible row.
func (m Model) clampSelectionToViewport() Model {
	itemCount := m.getItemCount()
	if itemCount == 0 {
		m.selectedRow = 0
		return m
	}

	// Constrain to the visible window
	if m.selectedRow < m.viewportStart {
		m.selectedRow = m.viewportStart
	}
	if m.selectedRow > m.viewportStart+m.pageSize-1 {
		m.selectedRow = m.viewportStart + m.pageSize - 1
	}

	// Constrain to valid items (viewport can be taller than the item count)
	m.selectedRow = min(max(m.selectedRow, 0), itemCount-1)
	return m
}

// scrollBy moves the viewport by delta lines, independently of the selection,
// then clamps the selection back into the visible window. Negative delta
// scrolls up, positive scrolls down.
func (m Model) scrollBy(delta int) Model {
	m.viewportStart = min(max(m.viewportStart+delta, 0), m.maxViewportStart())
	return m.clampSelectionToViewport()
}

// shellQuote returns a shell-escaped version of a string for safe use in shell commands.
// Uses single-quote escaping: wraps string in single quotes and escapes embedded single quotes.
func shellQuote(s string) string {
	// Replace ' with '\'' (close quote, escaped quote, open quote)
	return "'" + strings.ReplaceAll(s, "'", "'\\''") + "'"
}

// detectEditor checks for editor availability and returns status, command, and help message
func detectEditor() (EditorStatus, string, string) {
	// Check if EDITOR is set (don't validate PATH yet - will check when actually executing)
	if editor := os.Getenv("EDITOR"); editor != "" {
		return EditorSet, editor, fmt.Sprintf("Using editor: %s", editor)
	}

	// Check if micro is in PATH
	if _, err := exec.LookPath("micro"); err == nil {
		return MicroAvailable, "micro", "Using editor: micro (install: https://github.com/zyedidia/micro)"
	}

	// No editor found
	return NoEditorFound, "", "No editor found - Set EDITOR or install micro: https://github.com/zyedidia/micro"
}

// parseFileArg parses command-line file argument with optional line number.
// Supports formats: "file.go" or "file.go:42". Returns (filename, lineNumber, error).
func parseFileArg(arg string) (string, int, error) {
	parts := strings.Split(arg, ":")
	if len(parts) == 1 {
		return parts[0], 0, nil
	}
	if len(parts) == 2 {
		lineNo, err := strconv.Atoi(parts[1])
		if err != nil {
			return "", 0, fmt.Errorf("invalid line number: %s", parts[1])
		}
		return parts[0], lineNo, nil
	}
	return "", 0, fmt.Errorf("invalid file argument format: %s", arg)
}

// getSpinnerFrame returns a braille spinner character for the given frame number (0-9).
// Used to show loading animation while blame data is being fetched.
func getSpinnerFrame(frame int) string {
	frames := []string{"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"}
	return frames[frame%len(frames)]
}

// getAgeColorLogarithmic returns a color for a commit timestamp based on its age.
// Uses logarithmic scaling to give more color variation to recent commits.
// Green (newest) → yellow → gray (oldest).
func getAgeColorLogarithmic(t time.Time, oldest time.Time, newest time.Time) lipgloss.Color {
	// Color gradient from newest to oldest
	colors := ageGradientColors

	// If same commit time for all lines, use middle color
	if oldest.Equal(newest) {
		return colors[len(colors)/2]
	}

	// Calculate age relative to the range
	totalRange := newest.Sub(oldest).Seconds()
	ageFromOldest := t.Sub(oldest).Seconds()

	if totalRange <= 0 {
		return colors[0]
	}

	// Use logarithmic scale: log(1 + x) to map [0, totalRange] to [0, 1]
	// This gives more color variation for recent commits
	normalizedAge := ageFromOldest / totalRange
	logScale := math.Log1p(normalizedAge*9) / math.Log1p(9) // Scale to [0, 1]

	// Map to color index
	colorIdx := int(logScale * float64(len(colors)-1))
	if colorIdx >= len(colors) {
		colorIdx = len(colors) - 1
	}

	return colors[len(colors)-1-colorIdx] // Reverse: newest = green, oldest = gray
}

// getCommitColor returns a consistent color for a commit hash.
// Hashes the commit SHA to pick a color, so the same commit always gets the same color.
func getCommitColor(commitHash string) lipgloss.Color {
	// Convert first 8 hex chars to int, modulo by number of colors
	if len(commitHash) >= 8 {
		hashVal, err := strconv.ParseInt(commitHash[:8], 16, 64)
		if err == nil {
			colorIdx := hashVal % int64(len(commitHashColors))
			return commitHashColors[colorIdx]
		}
	}
	return commitHashColors[len(commitHashColors)-1] // Default to last color (white)
}

// getAuthorEmoji returns a consistent food emoji for an author name.
// Hashes the author name to pick an emoji, making it easy to visually distinguish authors.
func getAuthorEmoji(author string) string {
	foodEmojis := []string{
		"🍎", "🍊", "🍋", "🍌", "🍉", "🍇", "🍓", "🫐", "🍈", "🍒",
		"🍑", "🥭", "🍍", "🥥", "🥝", "🍅", "🍆", "🥑", "🥦", "🥬",
		"🥒", "🌶️", "🫑", "🌽", "🥕", "🫒", "🧄", "🧅", "🥔", "🍠",
		"🥐", "🥯", "🍞", "🥖", "🥨", "🧀", "🥚", "🍳", "🧈", "🥞",
		"🧇", "🥓", "🥩", "🍗", "🍖", "🦴", "🌭", "🍔", "🍟", "🍕",
		"🫓", "🥙", "🌮", "🌯", "🥗", "🥘", "🫕", "🥫", "🍝", "🍜",
		"🍲", "🍛", "🍣", "🍱", "🥟", "🦪", "🍤", "🍙", "🍚", "🍘",
		"🍥", "🥠", "🥮", "🍢", "🍡", "🍧", "🍨", "🍦", "🥧", "🧁",
		"🍰", "🎂", "🍮", "🍭", "🍬", "🍫", "🍿", "🍩", "🍪",
	}

	// Hash author name by summing character values
	hash := 0
	for i, c := range author {
		hash += int(c) * (i + 1)
	}

	if len(foodEmojis) > 0 {
		return foodEmojis[hash%len(foodEmojis)]
	}
	return "🍽️"
}

// renderCell renders a table cell with exact width, panicking if width doesn't match.
// Used to ensure table alignment stays pixel-perfect across all rows.
func renderCell(text string, width int, style lipgloss.Style) string {
	rendered := style.Width(width).Render(text)
	actualWidth := ansi.StringWidth(rendered)
	// Assert: Rendered cell width must exactly match expected width
	// This ensures table columns stay aligned across all rows
	if actualWidth != width {
		log.Panicf("renderCell width mismatch: expected %d, got %d for text %q (rendered: %q)", width, actualWidth, text, rendered)
	}
	return rendered
}

// formatRelativeTime formats a timestamp as a short relative time string.
// Examples: "″42" (seconds), "'23" (minutes), "5h", "3d", "2w", "6mo", "15y".
func formatRelativeTime(t time.Time) string {
	now := time.Now()
	duration := now.Sub(t)

	// Calculate time units
	years := int(duration.Hours() / 24 / 365)
	months := int(duration.Hours() / 24 / 30)
	days := int(duration.Hours() / 24)
	hours := int(duration.Hours())
	minutes := int(duration.Minutes())
	seconds := int(duration.Seconds())

	// Return the largest unit
	if years > 0 {
		return fmt.Sprintf("%2dy", years)
	} else if months > 0 {
		return fmt.Sprintf("%2dm", months)
	} else if days > 0 {
		return fmt.Sprintf("%2dd", days)
	} else if hours > 0 {
		return fmt.Sprintf("%2dh", hours)
	} else if minutes > 0 {
		return fmt.Sprintf("'%2d", minutes)
	} else {
		return fmt.Sprintf("″%2d", seconds)
	}
}

// renderCommitColumn renders the commit hash column (8 characters, colored).
// Shows spinner while loading, special styling for uncommitted changes.
func (ctx *BlameRowContext) renderCommitColumn(data any, width int) string {
	rowData := data.(BlameRowData)
	bl := rowData.BlameLine

	if !bl.HasBlame {
		// Still loading - show spinner
		return lipgloss.NewStyle().
			Foreground(ColorTextSecondary).
			Render(getSpinnerFrame(ctx.spinnerFrame))
	}

	if bl.CommitHash == "0000000000000000000000000000000000000000" {
		// Uncommitted changes
		return lipgloss.NewStyle().
			Foreground(ColorUncommittedChanges).
			Render("…")
	}

	// Normal commit - show 8-char hash with color
	commit := bl.CommitHash
	if len(commit) >= 8 {
		commit = commit[:8]
	} else if commit == "" {
		commit = "err"
	}

	commitColor := getCommitColor(bl.CommitHash)
	return lipgloss.NewStyle().
		Foreground(commitColor).
		Render(commit)
}

// renderExtendedIndicatorColumn renders the "+" indicator if commit has extended message.
func (ctx *BlameRowContext) renderExtendedIndicatorColumn(data any, width int) string {
	rowData := data.(BlameRowData)
	bl := rowData.BlameLine

	info, exists := ctx.commitExtendedInfo[bl.CommitHash]
	if exists && info.state == ExtMsgHasBody {
		return "+"
	}
	return " "
}

// renderAuthorColumn renders the author column with emoji and name.
func (ctx *BlameRowContext) renderAuthorColumn(data any, width int) string {
	rowData := data.(BlameRowData)
	bl := rowData.BlameLine

	if !bl.HasBlame {
		return lipgloss.NewStyle().
			Foreground(ColorTextSecondary).
			Render("…")
	}

	if bl.CommitHash == "0000000000000000000000000000000000000000" {
		return lipgloss.NewStyle().
			Foreground(ColorUncommittedChanges).
			Render("…")
	}

	authorEmoji := getAuthorEmoji(bl.Author)
	emojiWidth := ansi.StringWidth(authorEmoji)

	// Use provided width instead of hardcoded value
	remainingWidth := width - emojiWidth - 1 // -1 for space between emoji and name

	authorName := bl.Author
	if bl.Author == "" {
		authorName = "err"
	} else if ansi.StringWidth(bl.Author) > remainingWidth {
		authorName = ansi.Truncate(bl.Author, remainingWidth, "…")
	}

	// Build author string (table framework adds trailing space)
	author := authorEmoji + " " + authorName

	// Truncate if too wide
	if ansi.StringWidth(author) > width {
		author = ansi.Truncate(author, width, "…")
	}

	return author
}

// renderAgeColumn renders the relative time column with color gradient.
func (ctx *BlameRowContext) renderAgeColumn(data any, width int) string {
	rowData := data.(BlameRowData)
	bl := rowData.BlameLine

	if !bl.HasBlame {
		return lipgloss.NewStyle().
			Foreground(ColorTextSecondary).
			Render("…")
	}

	if bl.CommitHash == "0000000000000000000000000000000000000000" {
		return lipgloss.NewStyle().
			Foreground(ColorUncommittedChanges).
			Render("…")
	}

	if bl.AuthorTime.IsZero() {
		return lipgloss.NewStyle().
			Foreground(ColorError).
			Render("err")
	}

	dateStr := formatRelativeTime(bl.AuthorTime)
	dateColor := getAgeColorLogarithmic(bl.AuthorTime, ctx.oldestCommit, ctx.newestCommit)

	return lipgloss.NewStyle().
		Foreground(dateColor).
		Render(dateStr)
}

// renderLineNumColumn renders the line number column with dot leaders.
func (ctx *BlameRowContext) renderLineNumColumn(data any, width int) string {
	rowData := data.(BlameRowData)
	bl := rowData.BlameLine

	lineNumDigits := fmt.Sprintf("%d", bl.LineNumber)
	paddingNeeded := width - len(lineNumDigits)
	lineNumStr := strings.Repeat("․", paddingNeeded) + lineNumDigits

	return lipgloss.NewStyle().
		Foreground(ColorTextDim).
		Render(lineNumStr)
}

// createContentColumnRenderer creates a content column render function.
// The render function receives the width dynamically from the table.
func (ctx *BlameRowContext) createContentColumnRenderer() func(any, int) string {
	return func(data any, width int) string {
		rowData := data.(BlameRowData)
		bl := rowData.BlameLine

		var content string
		if rowData.IsSelected {
			// Strip background colors so selection highlight shows properly
			content = bl.Content.GetLineWithoutBackgrounds(0)
			// Truncate to full width (table framework adds trailing space)
			content = ansi.Truncate(content, width, "…")
		} else {
			// Truncate to full width (table framework adds trailing space)
			content = bl.Content.GetLineTruncated(0, width)
		}
		return content
	}
}

// renderStatusColumn renders the git status column (M/A/D for Modified/Added/Deleted).
func (ctx *BlameRowContext) renderStatusColumn(data any, width int) string {
	rowData := data.(DirectoryRowData)
	entry := rowData.FileEntry

	// Color the status based on type
	statusColor := ColorTextSecondary
	switch entry.Status {
	case "A":
		statusColor = lipgloss.Color("34") // Blue for added files
	case "M":
		statusColor = lipgloss.Color("178") // Yellow for modified files
	case "D":
		statusColor = lipgloss.Color("160") // Red for deleted files
	}

	return lipgloss.NewStyle().
		Foreground(statusColor).
		Render(entry.Status)
}

// createFilepathColumnRenderer creates a filepath column render function for directory view.
func (ctx *BlameRowContext) createFilepathColumnRenderer() func(any, int) string {
	return func(data any, width int) string {
		rowData := data.(DirectoryRowData)
		entry := rowData.FileEntry

		// Truncate path if too long
		path := entry.Path
		if ansi.StringWidth(path) > width {
			path = ansi.Truncate(path, width, "…")
		}

		return path
	}
}

// renderDirectoryCommitColumn renders commit hash for directory view (reuses same logic as file view).
func (ctx *BlameRowContext) renderDirectoryCommitColumn(data any, width int) string {
	rowData := data.(DirectoryRowData)
	entry := rowData.FileEntry

	if entry.CommitHash == "" {
		return lipgloss.NewStyle().
			Foreground(ColorTextSecondary).
			Render("err")
	}

	// Show 8-char hash with color
	commit := entry.CommitHash
	if len(commit) >= 8 {
		commit = commit[:8]
	}

	commitColor := getCommitColor(entry.CommitHash)
	return lipgloss.NewStyle().
		Foreground(commitColor).
		Render(commit)
}

// renderDirectoryAuthorColumn renders author for directory view.
func (ctx *BlameRowContext) renderDirectoryAuthorColumn(data any, width int) string {
	rowData := data.(DirectoryRowData)
	entry := rowData.FileEntry

	if entry.Author == "" {
		return lipgloss.NewStyle().
			Foreground(ColorTextSecondary).
			Render("err")
	}

	authorEmoji := getAuthorEmoji(entry.Author)
	emojiWidth := ansi.StringWidth(authorEmoji)
	remainingWidth := width - emojiWidth - 1

	authorName := entry.Author
	if ansi.StringWidth(entry.Author) > remainingWidth {
		authorName = ansi.Truncate(entry.Author, remainingWidth, "…")
	}

	author := authorEmoji + " " + authorName
	if ansi.StringWidth(author) > width {
		author = ansi.Truncate(author, width, "…")
	}

	return author
}

// renderDirectoryAgeColumn renders age for directory view.
func (ctx *BlameRowContext) renderDirectoryAgeColumn(data any, width int) string {
	rowData := data.(DirectoryRowData)
	entry := rowData.FileEntry

	if entry.AuthorTime.IsZero() {
		return lipgloss.NewStyle().
			Foreground(ColorError).
			Render("err")
	}

	dateStr := formatRelativeTime(entry.AuthorTime)
	dateColor := getAgeColorLogarithmic(entry.AuthorTime, ctx.oldestCommit, ctx.newestCommit)

	return lipgloss.NewStyle().
		Foreground(dateColor).
		Render(dateStr)
}

// renderDirectoryExtendedIndicatorColumn renders the "+" indicator for directory view.
func (ctx *BlameRowContext) renderDirectoryExtendedIndicatorColumn(data any, width int) string {
	rowData := data.(DirectoryRowData)
	entry := rowData.FileEntry

	info, exists := ctx.commitExtendedInfo[entry.CommitHash]
	if exists && info.state == ExtMsgHasBody {
		return "+"
	}
	return " "
}

// readFileLines reads a file and returns its lines as a string slice.
// Removes trailing empty line if present. Used during initial file loading.
func readFileLines(filename string) ([]string, error) {
	// Check if file exists
	if _, err := os.Stat(filename); os.IsNotExist(err) {
		return nil, fmt.Errorf("file does not exist: %s", filename)
	} else if err != nil {
		return nil, fmt.Errorf("failed to stat file: %w", err)
	}

	content, err := os.ReadFile(filename)
	if err != nil {
		return nil, fmt.Errorf("failed to read file: %w", err)
	}

	lines := strings.Split(string(content), "\n")

	// Drop the last line if it's only a linebreak (empty string)
	if len(lines) > 0 && lines[len(lines)-1] == "" {
		lines = lines[:len(lines)-1]
	}

	return lines, nil
}

// NewModel creates a new Bubble Tea Model for the git blame TUI.
// Initializes contexts for file loading, blame operations, and file watching.
// Detects editor availability and starts the file watcher goroutine.
func NewModel(filename string, cursorLine int, viewportOffsetLine int, debugUI bool) Model {
	// Create cancellable context for both file load and blame
	ctx, cancel := context.WithCancel(context.Background())

	// Create separate context for file watching (independent lifecycle)
	watchCtx, _ := context.WithCancel(context.Background())

	// Detect editor availability
	editorStatus, editorCommand, editorMessage := detectEditor()

	// Create file watcher
	fileWatcher := NewFileWatcher(watchCtx, filename)

	// Initialize model with empty state
	model := Model{
		blameLines:          []BlameLine{}, // Will be populated by FileLoadedMsg
		selectedRow:         0,
		viewportStart:       0,
		pageSize:            20, // Will be updated when we get window size
		filename:            filename,
		loadingState:        LoadingFile,     // Start by loading file
		fileLoadStatus:      FileLoadSuccess, // Default to success, set to error if load fails
		cancelBlame:         cancel,
		ctx:                 ctx,
		targetLine:          cursorLine,
		viewportOffsetLine:  viewportOffsetLine,
		commitExtendedInfo:  make(map[string]CommitExtendedInfo),
		debugUI:             debugUI,
		currentTickInterval: time.Millisecond * 100, // Start with fast ticks
		fileWatcher:         fileWatcher,
		editorStatus:        editorStatus,
		editorCommand:       editorCommand,
		editorMessage:       editorMessage,
		detailView:          NewDetailViewModel(),
	}

	// Log editor status
	log.Printf("%s", editorMessage)

	return model
}

// NewDirectoryModel creates a new Bubble Tea Model for directory view.
// Lists recently modified files in the directory using git log.
func NewDirectoryModel(dirpath string, debugUI bool) Model {
	// Create cancellable context for directory loading
	ctx, cancel := context.WithCancel(context.Background())

	// Create separate context for file watching (independent lifecycle)
	watchCtx, _ := context.WithCancel(context.Background())

	// Detect editor availability
	editorStatus, editorCommand, editorMessage := detectEditor()

	// Create file watcher
	fileWatcher := NewFileWatcher(watchCtx, dirpath)

	// Initialize model with empty state
	model := Model{
		viewMode:            DirectoryView,
		fileEntries:         []FileEntry{}, // Will be populated by DirectoryLoadedMsg
		selectedRow:         0,
		viewportStart:       0,
		pageSize:            20, // Will be updated when we get window size
		filename:            dirpath,
		loadingState:        LoadingFile,     // Start by loading directory
		fileLoadStatus:      FileLoadSuccess, // Default to success, set to error if load fails
		cancelBlame:         cancel,
		ctx:                 ctx,
		commitExtendedInfo:  make(map[string]CommitExtendedInfo),
		debugUI:             debugUI,
		currentTickInterval: time.Millisecond * 100, // Start with fast ticks
		fileWatcher:         fileWatcher,
		editorStatus:        editorStatus,
		editorCommand:       editorCommand,
		editorMessage:       editorMessage,
		detailView:          NewDetailViewModel(),
	}

	// Log editor status
	log.Printf("%s", editorMessage)

	return model
}

// Init implements tea.Model interface. Called once when the program starts.
// Starts async file/directory loading, spinner ticker for UI updates, and file watcher listener.
func (m Model) Init() tea.Cmd {
	var loadCmd tea.Cmd
	if m.viewMode == DirectoryView {
		// Load directory files (max 1000 files to keep it snappy)
		loadCmd = startDirectoryLoad(m.ctx, m.filename, 1000)
	} else {
		// Load single file for blame view
		loadCmd = startFileLoad(m.ctx, m.filename, m.targetLine, m.viewportOffsetLine)
	}

	// Start async load, spinner ticker, and file watcher
	return tea.Batch(
		loadCmd,
		tea.Tick(time.Millisecond*100, func(t time.Time) tea.Msg {
			return spinnerTickMsg{}
		}),
		m.fileWatcher.waitForMessage(),
	)
}

// startFileLoad loads file asynchronously and returns a command.
// Reads file content, calculates hash, gets git repo info, and optionally colorizes with bat.
// Returns FileLoadedMsg on success or FileLoadErrorMsg on failure.
func startFileLoad(ctx context.Context, filename string, targetLine int, viewportOffsetLine int) tea.Cmd {
	return func() tea.Msg {
		startTime := time.Now()

		// Check if context is already cancelled
		select {
		case <-ctx.Done():
			return nil
		default:
		}

		// Get git repository root
		repoRoot, err := getGitRepoRoot(filename)
		if err != nil {
			return FileLoadErrorMsg{Err: fmt.Errorf("failed to find git repository: %w", err)}
		}

		// Read file content first (fast operation)
		fileLines, err := readFileLines(filename)
		if err != nil {
			return FileLoadErrorMsg{Err: err}
		}

		// Calculate hash of file contents
		fileContent, err := os.ReadFile(filename)
		if err != nil {
			return FileLoadErrorMsg{Err: fmt.Errorf("failed to read file for hashing: %w", err)}
		}
		contentHash := sha256.Sum256(fileContent)

		// Log file read completion with timing
		elapsed := time.Since(startTime)
		log.Printf("File read: %s (%d lines, %d bytes) in %d ms", filename, len(fileLines), len(fileContent), elapsed.Milliseconds())

		// Check cancellation after file read
		select {
		case <-ctx.Done():
			return nil
		default:
		}

		// Decide on colorization strategy based on file size
		const largeFileThreshold = 10000
		var colorizedLines map[int]ColorizedText

		if len(fileLines) <= largeFileThreshold {
			// Small file: colorize synchronously (fast enough)
			batStartTime := time.Now()
			var err error
			colorizedLines, err = ColorizeFileWithBat(filename)
			if err != nil {
				// Use plain content if bat fails
				colorizedLines = make(map[int]ColorizedText)
				for i, line := range fileLines {
					colorizedLines[i+1] = NewColorizedText(line)
				}
			}
			// Log bat colorization completion with timing
			batElapsed := time.Since(batStartTime)
			log.Printf("Bat highlighting complete in %d ms", batElapsed.Milliseconds())

			// Check cancellation after bat colorization
			select {
			case <-ctx.Done():
				return nil
			default:
			}
		} else {
			// Large file: skip colorization for now (will be done async)
			log.Printf("Large file (%d lines), skipping sync colorization", len(fileLines))
			colorizedLines = nil
		}

		// Create placeholder blame lines with file content
		blameLineStartTime := time.Now()
		blameLines := make([]BlameLine, len(fileLines))
		for i := range fileLines {
			content := NewColorizedText(fileLines[i])
			if colorizedLines != nil {
				if colorized, ok := colorizedLines[i+1]; ok {
					content = colorized
				}
			}
			blameLines[i] = BlameLine{
				LineNumber: i + 1,
				Content:    content,
				HasBlame:   false, // No blame data yet
			}
		}
		blameLineElapsed := time.Since(blameLineStartTime)
		if debugLog != nil {
			log.Printf("BlameLine creation complete in %d ms", blameLineElapsed.Milliseconds())
		}

		// Log total elapsed time for entire file load
		totalElapsed := time.Since(startTime)
		if debugLog != nil {
			log.Printf("startFileLoad total time: %d ms", totalElapsed.Milliseconds())
		}

		return FileLoadedMsg{
			BlameLines:         blameLines,
			Ctx:                ctx,
			TargetLine:         targetLine,
			ViewportOffsetLine: viewportOffsetLine,
			RepoRoot:           repoRoot,
			ContentHash:        contentHash,
			LastCommitHash:     "", // Will be populated async by startGetLastCommitHash()
		}
	}
}

// startAsyncColorize colorizes a file asynchronously using bat.
// Used for large files (>10k lines) to avoid blocking initial file load.
// Returns ColorizeCompleteMsg on success, nil on failure or cancellation.
func startAsyncColorize(ctx context.Context, filename string) tea.Cmd {
	return func() tea.Msg {
		// Check if context is already cancelled
		select {
		case <-ctx.Done():
			return nil
		default:
		}

		// Call bat to colorize the file
		batStartTime := time.Now()
		colorizedMap, err := ColorizeFileWithBat(filename)
		if err != nil {
			return nil // Fail silently, keep plain text
		}
		// Log async bat colorization completion with timing
		batElapsed := time.Since(batStartTime)
		log.Printf("Bat highlighting (async) complete in %d ms", batElapsed.Milliseconds())

		// Check cancellation after colorization
		select {
		case <-ctx.Done():
			return nil
		default:
		}

		// Convert map to list for simpler indexing
		// Find max line number to determine list size
		maxLine := 0
		for lineNum := range colorizedMap {
			if lineNum > maxLine {
				maxLine = lineNum
			}
		}

		// Create list indexed by line number (line 1 at index 0)
		colorizedList := make([]ColorizedText, maxLine)
		for lineNum, colorized := range colorizedMap {
			colorizedList[lineNum-1] = colorized
		}

		return ColorizeCompleteMsg{
			ColorizedLines: colorizedList,
		}
	}
}

// startGetLastCommitHash loads the last commit hash for a file asynchronously.
// Used to avoid blocking initial file display with 400ms+ git log operation.
// Returns lastCommitHashLoadedMsg with commit hash on success, empty string on failure.
func startGetLastCommitHash(ctx context.Context, repoRoot, filename string) tea.Cmd {
	return func() tea.Msg {
		// Check if context is already cancelled
		select {
		case <-ctx.Done():
			return lastCommitHashLoadedMsg{commitHash: ""}
		default:
		}

		// Get last commit hash for this file
		commitStartTime := time.Now()
		commitHash, err := getLatestCommitForFile(repoRoot, filename)
		if err != nil {
			// Return empty string on error (same as initial state)
			log.Printf("Failed to get last commit hash: %v", err)
			return lastCommitHashLoadedMsg{commitHash: ""}
		}

		// Log completion with timing (only if debugLog is set)
		commitElapsed := time.Since(commitStartTime)
		if debugLog != nil {
			log.Printf("getLatestCommitForFile (async) complete in %d ms", commitElapsed.Milliseconds())
		}

		// Check cancellation after git log
		select {
		case <-ctx.Done():
			return lastCommitHashLoadedMsg{commitHash: ""}
		default:
		}

		return lastCommitHashLoadedMsg{commitHash: commitHash}
	}
}

// getCommitHashesInRange returns unique commit hashes in the given line/item range.
// Filters out empty hashes, uncommitted lines (all zeros), and duplicates.
// Works for both FileView (blame lines) and DirectoryView (file entries).
func (m Model) getCommitHashesInRange(startIdx, endIdx int) []string {
	itemCount := m.getItemCount()

	// Clamp to valid range
	if startIdx < 0 {
		startIdx = 0
	}
	if endIdx > itemCount {
		endIdx = itemCount
	}
	if startIdx >= endIdx {
		return nil
	}

	// Collect unique commit hashes
	seen := make(map[string]bool)
	var hashes []string

	for i := startIdx; i < endIdx; i++ {
		var hash string
		if m.viewMode == DirectoryView {
			hash = m.fileEntries[i].CommitHash
		} else {
			hash = m.blameLines[i].CommitHash
		}

		// Skip empty hashes, uncommitted lines, and already seen hashes
		if hash == "" || hash == "0000000000000000000000000000000000000000" || seen[hash] {
			continue
		}
		seen[hash] = true
		hashes = append(hashes, hash)
	}

	return hashes
}

// getVisibleCommitHashes returns unique commit hashes that are currently visible in the viewport.
// Used to prioritize extended message checks for visible commits.
func (m Model) getVisibleCommitHashes() []string {
	endIdx := m.viewportStart + m.pageSize
	return m.getCommitHashesInRange(m.viewportStart, endIdx)
}

// checkVisibleExtendedMessages queues extended message checks for visible commits.
// Prefetches current page plus one page above and below. Returns nil (tasks are queued
// in pendingTasks for later execution by Update's task manager).
func (m *Model) checkVisibleExtendedMessages() (tea.Cmd, []string) {
	// Don't check if repoRoot is not set yet (file not loaded)
	if m.repoRoot == "" {
		return nil, nil
	}

	// Get visible commit hashes (current page)
	visibleHashes := m.getVisibleCommitHashes()

	// Get hashes for page below (prefetch)
	pageBelow := m.getCommitHashesInRange(m.viewportStart+m.pageSize, m.viewportStart+2*m.pageSize)

	// Get hashes for page above (prefetch)
	pageAbove := m.getCommitHashesInRange(m.viewportStart-m.pageSize, m.viewportStart)

	// Filter out hashes already in cache (regardless of state - Checking, NoBody, or HasBody)
	// Only check hashes that aren't in the map at all
	var uncachedVisible []string
	for _, hash := range visibleHashes {
		if _, exists := m.commitExtendedInfo[hash]; !exists {
			uncachedVisible = append(uncachedVisible, hash)
		}
	}

	var uncachedBelow []string
	for _, hash := range pageBelow {
		if _, exists := m.commitExtendedInfo[hash]; !exists {
			uncachedBelow = append(uncachedBelow, hash)
		}
	}

	var uncachedAbove []string
	for _, hash := range pageAbove {
		if _, exists := m.commitExtendedInfo[hash]; !exists {
			uncachedAbove = append(uncachedAbove, hash)
		}
	}

	// If no uncached hashes at all, return nil
	if len(uncachedVisible) == 0 && len(uncachedBelow) == 0 && len(uncachedAbove) == 0 {
		return nil, nil
	}

	// Add uncached hashes to pending queue in priority order:
	// 1. Current visible page (highest priority)
	// 2. Page below (scroll down is more common)
	// 3. Page above
	m.tasksMutex.Lock()
	m.pendingTasks = append(m.pendingTasks, uncachedVisible...)
	m.pendingTasks = append(m.pendingTasks, uncachedBelow...)
	m.pendingTasks = append(m.pendingTasks, uncachedAbove...)
	m.tasksMutex.Unlock()

	// Return nil - tasks will be started by queue manager in Update()
	return nil, nil
}

func logReturn(m Model, cmd tea.Cmd, msg tea.Msg, context string) (tea.Model, tea.Cmd) {
	// Skip logging for spinner ticks
	if _, isSpinner := msg.(spinnerTickMsg); isSpinner {
		return m, cmd
	}

	cmdDesc := "nil"
	if cmd != nil {
		cmdDesc = "cmd"
	}
	logDebug("UPDATE OUT [%s]: state=%v lines=%d selected=%d cmd=%s",
		context, m.loadingState, len(m.blameLines), m.selectedRow, cmdDesc)
	return m, cmd
}

// ============================================================================
// Update() Helper Functions
// ============================================================================

// handleWindowSizeMsg handles terminal resize events
func (m Model) handleWindowSizeMsg(msg tea.WindowSizeMsg) (Model, tea.Cmd) {
	m.windowWidth = msg.Width
	m.windowHeight = msg.Height
	// Reserve space for: header (1) + table header (1) + top border (1) + bottom border (1) = 4 lines
	pageSize := max(m.windowHeight-4, 1)
	m.pageSize = pageSize

	// The viewport scrolls independently of the selection, so a resize can
	// leave it past the end of the file or the selection off-screen.
	m.viewportStart = min(max(m.viewportStart, 0), m.maxViewportStart())
	m = m.clampSelectionToViewport()
	return m, nil
}

// handleMouseMsg handles mouse input: wheel scrolls the viewport independently
// of the selection, left click selects the row under the cursor.
func (m Model) handleMouseMsg(msg tea.MouseMsg) (Model, tea.Cmd) {
	// Modal swallows all mouse input (it is dismissed with 'q')
	if m.modalText.LineCount() > 0 {
		return m, nil
	}

	// Detail/help view scrolls its own content
	if m.detailView.UpdateMouse(msg, m.windowWidth, m.windowHeight) {
		return m, nil
	}

	// Only react to presses; ignore motion and release events
	if msg.Action != tea.MouseActionPress {
		return m, nil
	}

	switch msg.Button {
	case tea.MouseButtonWheelUp:
		m = m.scrollBy(-mouseScrollLines)

	case tea.MouseButtonWheelDown:
		m = m.scrollBy(mouseScrollLines)

	case tea.MouseButtonLeft:
		// Map screen row to item index; clicks on chrome are ignored
		if msg.Y >= tableFirstRow {
			idx := m.viewportStart + (msg.Y - tableFirstRow)
			if idx < m.getItemCount() && idx < m.viewportStart+m.pageSize {
				m.selectedRow = idx
			}
		}
	}

	return m, nil
}

// handleModalKeys handles keyboard input when modal is showing
func (m Model) handleModalKeys(msg tea.KeyMsg) (Model, tea.Cmd) {
	switch msg.String() {
	case "q":
		m.modalText = ColorizedText{} // Clear modal
		return m, nil
	}
	return m, nil // Ignore other keys when modal is showing
}

// handleEditorKey handles the 'e' key - opens file in external editor
func (m Model) handleEditorKey() (Model, tea.Cmd) {
	itemCount := m.getItemCount()
	if m.selectedRow >= itemCount {
		return m, nil
	}

	// Check if editor is available
	if m.editorStatus == NoEditorFound {
		// Show modal with error message
		modalMarkdown := `# No Editor Found

git-blimey could not find a text editor to open the file.

Please either:
- Set the **EDITOR** environment variable to your preferred editor
- Install **micro**: https://github.com/zyedidia/micro`
		colorized, err := ColorizeTextWithBat(modalMarkdown, "markdown")
		if err != nil {
			// Fallback to plain text if bat fails
			m.modalText = NewColorizedText(modalMarkdown)
		} else {
			// Store just the colorized markdown (keybindings will be added in View)
			m.modalText = colorized
		}
		return m, nil
	}

	// Validate that editor command is in PATH
	if _, err := exec.LookPath(m.editorCommand); err != nil {
		// Editor command not found in PATH
		modalMarkdown := fmt.Sprintf(`# Editor Not Found

git-blimey could not find the editor `+"`%s`"+` in your PATH.

Please either:
- Set the `+"`EDITOR`"+` environment variable to a valid editor
- Install `+"`micro`"+`: https://github.com/zyedidia/micro`, m.editorCommand)
		colorized, err := ColorizeTextWithBat(modalMarkdown, "markdown")
		if err != nil {
			m.modalText = NewColorizedText(modalMarkdown)
		} else {
			// Store just the colorized markdown (keybindings will be added in View)
			m.modalText = colorized
		}
		return m, nil
	}

	var cmd *exec.Cmd
	if m.viewMode == DirectoryView {
		// Directory view: open the selected file
		filePath := filepath.Join(m.repoRoot, m.fileEntries[m.selectedRow].Path)
		cmd = exec.Command(m.editorCommand, filePath)
	} else {
		// File view: open file at specific line
		lineNumber := m.blameLines[m.selectedRow].LineNumber
		cmd = exec.Command(m.editorCommand, fmt.Sprintf("+%d", lineNumber), m.filename)
	}
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return m, tea.ExecProcess(cmd, func(err error) tea.Msg {
		return execFinishedMsg{err: err}
	})
}

// handleEnterKey handles the Enter key - shows commit details
func (m Model) handleEnterKey() (Model, tea.Cmd) {
	itemCount := m.getItemCount()
	if m.selectedRow >= itemCount {
		return m, nil
	}

	var commitHash string
	if m.viewMode == DirectoryView {
		commitHash = m.fileEntries[m.selectedRow].CommitHash
	} else {
		commitHash = m.blameLines[m.selectedRow].CommitHash
	}

	if commitHash != "" {
		details, err := getCommitDetails(m.repoRoot, commitHash)
		if err != nil {
			m.detailView.Show("Commit Details", NewColorizedText(fmt.Sprintf("Error: %v", err)))
		} else {
			m.detailView.Show("Commit Details", details)
		}
	}
	return m, nil
}

// handleAuthorLogKey handles the 'a' key - shows git log for author
func (m Model) handleAuthorLogKey() (Model, tea.Cmd) {
	itemCount := m.getItemCount()
	if m.selectedRow >= itemCount {
		return m, nil
	}

	var author string
	if m.viewMode == DirectoryView {
		author = m.fileEntries[m.selectedRow].Author
	} else {
		author = m.blameLines[m.selectedRow].Author
	}

	if author != "" {
		// Run git log piped to pager (uses $PAGER or falls back to less -R)
		// Using shell to handle pipe and environment variable expansion
		shellCmd := fmt.Sprintf(
			"git -C %s log --author=%s --color=always | ${PAGER:-less -R}",
			shellQuote(m.repoRoot),
			shellQuote(author),
		)
		cmd := exec.Command("/bin/sh", "-c", shellCmd)
		cmd.Stdin = os.Stdin
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		return m, tea.ExecProcess(cmd, func(err error) tea.Msg {
			return execFinishedMsg{err: err}
		})
	}
	return m, nil
}

// handleBlameFileKey handles the 'b' key - switches to file blame view
func (m Model) handleBlameFileKey() (Model, tea.Cmd) {
	// Only works in directory mode
	if m.viewMode != DirectoryView {
		return m, nil
	}

	itemCount := m.getItemCount()
	if m.selectedRow >= itemCount {
		return m, nil
	}

	// Get the selected file path and construct absolute path
	relPath := m.fileEntries[m.selectedRow].Path
	absPath := filepath.Join(m.repoRoot, relPath)
	return m, func() tea.Msg {
		return switchToFileViewMsg{filename: absPath}
	}
}

// handleHelpKey handles the 'h' and 'f1' keys - shows help screen
func (m Model) handleHelpKey() (Model, tea.Cmd) {
	helpText, err := ColorizeTextWithBat(helpMarkdown, "markdown")
	if err != nil {
		// If bat fails, show plain help
		m.detailView.Show("Help", NewColorizedText(helpMarkdown))
	} else {
		m.detailView.Show("Help", helpText)
	}
	return m, nil
}

// handleReloadKey handles the 'r' key - reloads current file
func (m Model) handleReloadKey() (Model, tea.Cmd) {
	// Ignore refresh if already loading file
	if m.loadingState == LoadingFile {
		return m, nil
	}

	// Cancel old blame operations
	if m.cancelBlame != nil {
		m.cancelBlame()
	}

	log.Printf("User requested reload")

	// Create new context for reload
	ctx, cancel := context.WithCancel(context.Background())
	m.ctx = ctx
	m.cancelBlame = cancel

	// Preserve current cursor and viewport positions for after reload completes
	m.targetLine = m.selectedRow + 1
	m.viewportOffsetLine = m.viewportStart - 3 // Subtract 3 to convert back to 0-indexed editor offset

	// Set loading state (old data stays visible, viewport stays wherever user scrolled)
	m.loadingState = LoadingFile

	// Start file load in background
	return m, startFileLoad(m.ctx, m.filename, m.targetLine, m.viewportOffsetLine)
}

// handleBlameUpdate processes BlameUpdateMsg - updates blame data for lines
func (m Model) handleBlameUpdate(msg BlameUpdateMsg) (Model, tea.Cmd) {
	// Update blame data for lines in the batch
	for _, update := range msg.Updates {
		lineIdx := update.LineNumber - 1
		if lineIdx >= 0 && lineIdx < len(m.blameLines) {
			m.blameLines[lineIdx].CommitHash = update.CommitHash
			m.blameLines[lineIdx].Author = update.Author
			m.blameLines[lineIdx].AuthorTime = update.AuthorTime
			m.blameLines[lineIdx].HasBlame = true
			m.linesWithBlame++ // Increment counter for progress tracking

			// Update oldest/newest commit times
			if !update.AuthorTime.IsZero() {
				if m.oldestCommit.IsZero() || update.AuthorTime.Before(m.oldestCommit) {
					m.oldestCommit = update.AuthorTime
				}
				if m.newestCommit.IsZero() || update.AuthorTime.After(m.newestCommit) {
					m.newestCommit = update.AuthorTime
				}
			}
		}
	}
	// Wait for next update
	return m, func() tea.Msg { return <-m.blameChan }
}

// handleBlameUntracked processes BlameUntrackedMsg - marks all lines as untracked
func (m Model) handleBlameUntracked() (Model, tea.Cmd) {
	// File is untracked - mark all lines with uncommitted marker (all-zeros hash)
	log.Printf("Marking all lines as untracked")
	untrackedHash := "0000000000000000000000000000000000000000"
	for i := range m.blameLines {
		m.blameLines[i].CommitHash = untrackedHash
		m.blameLines[i].Author = ""
		m.blameLines[i].AuthorTime = time.Time{} // Zero time
		m.blameLines[i].HasBlame = true
	}
	m.linesWithBlame = len(m.blameLines)
	m.loadingState = LoadingComplete
	return m, nil
}

// handleFileLoaded processes FileLoadedMsg - file loaded, start blame
func (m Model) handleFileLoaded(msg FileLoadedMsg) (Model, tea.Cmd) {
	// File loaded successfully - populate blameLines and start blame
	m.blameLines = msg.BlameLines
	m.repoRoot = msg.RepoRoot
	m.fileWatcher.ResetBaseline(msg.ContentHash)
	m.lastCommitHashOriginal = msg.LastCommitHash
	m.lastCommitHash = msg.LastCommitHash

	// Set cursor position based on target line (from <file>:<line> or refresh)
	selectedRow := 0
	if msg.TargetLine > 0 && msg.TargetLine <= len(msg.BlameLines) {
		selectedRow = msg.TargetLine - 1
	}
	m.selectedRow = selectedRow

	// Set viewport position (independent of cursor position)
	if msg.ViewportOffsetLine != -1 {
		// --viewport-offset flag was used: add 3 to account for UI headers
		// (top border, table border, column headers = 3 lines)
		// This preserves the cursor's absolute screen position from the editor
		// ViewportOffsetLine can be negative (for heavy wrapping near file start)
		m.viewportStart = max(
			// Clamp to valid range
			msg.ViewportOffsetLine+3, 0)
		maxViewportStart := max(len(m.blameLines)-m.pageSize, 0)
		if m.viewportStart > maxViewportStart {
			m.viewportStart = maxViewportStart
		}
	} else if msg.TargetLine > 0 {
		// No --viewport-offset flag: center viewport on cursor (legacy behavior)
		m.viewportStart = max(selectedRow-m.pageSize/2, 0)
		maxViewportStart := max(len(m.blameLines)-m.pageSize, 0)
		if m.viewportStart > maxViewportStart {
			m.viewportStart = maxViewportStart
		}
	}

	// Start blame with the same context used for file loading
	log.Printf("File loaded - starting blame")
	m.linesWithBlame = 0          // Reset blame progress counter
	m.blameStartTime = time.Now() // Track when blame starts
	m.blameChan = startIncrementalBlame(msg.Ctx, m.filename)
	m.loadingState = LoadingBlame // Now loading blame data

	var cmds []tea.Cmd
	// Wait for blame updates
	cmds = append(cmds, func() tea.Msg { return <-m.blameChan })

	// If this is a large file (>10k lines), start async colorization
	const largeFileThreshold = 10000
	if len(msg.BlameLines) > largeFileThreshold {
		cmds = append(cmds, startAsyncColorize(msg.Ctx, m.filename))
	}

	// Start async commit hash loading (non-blocking)
	cmds = append(cmds, startGetLastCommitHash(msg.Ctx, msg.RepoRoot, m.filename))

	return m, tea.Batch(cmds...)
}

// handleDirectoryLoaded processes DirectoryLoadedMsg - directory loaded successfully
func (m Model) handleDirectoryLoaded(msg DirectoryLoadedMsg) (Model, tea.Cmd) {
	// Directory loaded successfully - populate fileEntries
	m.fileEntries = msg.FileEntries
	m.repoRoot = msg.RepoRoot
	m.loadingState = LoadingComplete
	log.Printf("Directory loaded - %d files found", len(m.fileEntries))

	// Calculate oldest/newest commit times for color gradient
	for _, entry := range m.fileEntries {
		if !entry.AuthorTime.IsZero() {
			if m.oldestCommit.IsZero() || entry.AuthorTime.Before(m.oldestCommit) {
				m.oldestCommit = entry.AuthorTime
			}
			if m.newestCommit.IsZero() || entry.AuthorTime.After(m.newestCommit) {
				m.newestCommit = entry.AuthorTime
			}
		}
	}
	return m, nil
}

// handleColorizeComplete processes ColorizeCompleteMsg - replaces content with colorized version
func (m Model) handleColorizeComplete(msg ColorizeCompleteMsg) (Model, tea.Cmd) {
	// Replace plain text content with colorized version
	for i := range m.blameLines {
		if i < len(msg.ColorizedLines) {
			m.blameLines[i].Content = msg.ColorizedLines[i]
		}
	}
	return m, nil
}

// handleSpinnerTick processes spinnerTickMsg - adaptive tick rate for spinner and file watching
func (m Model) handleSpinnerTick() (Model, tea.Cmd) {
	// Adaptive tick rate: fast (100ms) while loading, slow (15s) when complete
	var tickInterval time.Duration
	if m.loadingState != LoadingComplete {
		// Fast ticks for spinner animation while loading
		tickInterval = time.Millisecond * 100
		m.spinnerFrame = (m.spinnerFrame + 1) % 10
	} else {
		// Slow ticks - check for commit changes
		tickInterval = time.Second * 15

		// Check if commit has changed (git operations like commit --amend, rebase, etc.)
		if m.lastCommitHashOriginal != "" && m.repoRoot != "" {
			currentCommit, err := getLatestCommitForFile(m.repoRoot, m.filename)
			if err == nil && currentCommit != m.lastCommitHash {
				m.lastCommitHash = currentCommit
			}
		}
	}
	m.currentTickInterval = tickInterval
	return m, tea.Tick(tickInterval, func(t time.Time) tea.Msg {
		return spinnerTickMsg{}
	})
}

// handleExtendedMsgResult processes extendedMsgResult - caches commit extended message info
func (m Model) handleExtendedMsgResult(msg extendedMsgResult) (Model, tea.Cmd) {
	// Store result in cache (update from ExtMsgChecking to final state)
	state := ExtMsgNoBody
	if msg.hasExtended {
		state = ExtMsgHasBody
	}
	m.commitExtendedInfo[msg.commitHash] = CommitExtendedInfo{
		state:   state,
		subject: msg.subject,
	}
	return m, nil
}

// handleSwitchToFileView processes switchToFileViewMsg - switches from directory to file view
func (m Model) handleSwitchToFileView(msg switchToFileViewMsg) (Model, tea.Cmd) {
	// Switch from directory view to file blame view
	log.Printf("Switching to file view: %s", msg.filename)

	// Cancel old context
	if m.cancelBlame != nil {
		m.cancelBlame()
	}

	// Create new context for file loading
	ctx, cancel := context.WithCancel(context.Background())
	m.ctx = ctx
	m.cancelBlame = cancel

	// Reset state
	m.viewMode = FileView
	m.filename = msg.filename
	m.fileEntries = nil
	m.blameLines = nil
	m.selectedRow = 0
	m.viewportStart = 0
	m.targetLine = 0
	m.viewportOffsetLine = -1 // -1 = not provided, use default centering
	m.loadingState = LoadingFile
	m.fileLoadStatus = FileLoadSuccess
	m.commitExtendedInfo = make(map[string]CommitExtendedInfo)

	// Start file load
	return m, startFileLoad(ctx, msg.filename, 0, -1)
}

// ============================================================================
// Update() - Main Message Handler
// ============================================================================

// Update implements tea.Model interface. Handles all messages and updates model state.
// Manages loading states, keyboard input, blame updates, file watching, and async task queue.
func (m Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
	start := time.Now()

	// Log all incoming messages except spinner ticks
	if _, isSpinner := msg.(spinnerTickMsg); !isSpinner {
		elapsed := time.Since(programStart).Seconds()
		msgDesc := fmt.Sprintf("%T", msg)
		if blameUpdate, ok := msg.(BlameUpdateMsg); ok {
			msgDesc = fmt.Sprintf("%T[%d updates]", msg, len(blameUpdate.Updates))
		}
		logDebug("UPDATE IN [%.3fs]: %s | state=%v lines=%d", elapsed, msgDesc, m.loadingState, len(m.blameLines))
	}

	// Handle Ctrl+C and Ctrl+Q first - always allow immediate exit
	if keyMsg, ok := msg.(tea.KeyMsg); ok {
		if keyMsg.String() == "ctrl+c" || keyMsg.String() == "ctrl+q" {
			if m.cancelBlame != nil {
				m.cancelBlame()
			}
			m.fileWatcher.Stop()
			return m, tea.Quit
		}
	}

	// Accumulate commands to batch at the end
	var cmds []tea.Cmd

	switch msg := msg.(type) {
	case tea.WindowSizeMsg:
		return m.handleWindowSizeMsg(msg)

	case tea.MouseMsg:
		return m.handleMouseMsg(msg)

	case tea.KeyMsg:
		// Check if modal is showing
		if m.modalText.LineCount() > 0 {
			return m.handleModalKeys(msg)
		}

		// Check if detail/help view is showing
		if m.detailView.Update(msg, m.pageSize, m.windowWidth, m.windowHeight) {
			return m, nil
		}

		switch msg.String() {
		case "q":
			if m.cancelBlame != nil {
				m.cancelBlame()
			}
			m.fileWatcher.Stop()
			return m, tea.Quit

		case "up", "k":
			if m.selectedRow > 0 {
				m.selectedRow--
				// Scroll viewport if selection goes above visible area
				if m.selectedRow < m.viewportStart {
					m.viewportStart = m.selectedRow
				}
			}

		case "down", "j":
			itemCount := m.getItemCount()
			if m.selectedRow < itemCount-1 {
				m.selectedRow++
				// Scroll viewport if selection goes below visible area
				if m.selectedRow >= m.viewportStart+m.pageSize {
					m.viewportStart = m.selectedRow - m.pageSize + 1
				}
			}

		case "pgup":
			// Scroll the viewport, selection only follows to the bottom edge
			m = m.scrollBy(-m.pageSize)

		case "pgdown":
			// Scroll the viewport, selection only follows to the top edge
			m = m.scrollBy(m.pageSize)

		case "home", "g":
			m.selectedRow = 0
			m.viewportStart = 0

		case "end", "G":
			itemCount := m.getItemCount()
			m.selectedRow = max(itemCount-1, 0)
			// Show last page
			m.viewportStart = m.maxViewportStart()

		case "e":
			return m.handleEditorKey()

		case "enter":
			return m.handleEnterKey()

		case "a":
			return m.handleAuthorLogKey()

		case "b":
			return m.handleBlameFileKey()

		case "h", "f1":
			return m.handleHelpKey()

		case "ctrl+u":
			// Toggle debug UI mode
			m.debugUI = !m.debugUI

		case "r":
			return m.handleReloadKey()
		}

	case BlameUpdateMsg:
		var cmd tea.Cmd
		m, cmd = m.handleBlameUpdate(msg)
		cmds = append(cmds, cmd)

	case BlameCompleteMsg:
		// Log blame completion with timing
		elapsed := time.Since(m.blameStartTime)
		log.Printf("Blame complete (%d lines) in %d ms", len(m.blameLines), elapsed.Milliseconds())
		m.loadingState = LoadingComplete

	case BlameUntrackedMsg:
		m, _ = m.handleBlameUntracked()

	case BlameErrorMsg:
		log.Printf("Blame error: %v", msg.Err)
		m.loadingState = LoadingComplete

	case FileLoadedMsg:
		var cmd tea.Cmd
		m, cmd = m.handleFileLoaded(msg)
		cmds = append(cmds, cmd)

	case DirectoryLoadedMsg:
		m, _ = m.handleDirectoryLoaded(msg)

	case FileLoadErrorMsg:
		m.loadingState = LoadingComplete
		m.fileLoadStatus = FileLoadError
		log.Printf("File load error: %v", msg.Err)

	case ColorizeCompleteMsg:
		m, _ = m.handleColorizeComplete(msg)

	case lastCommitHashLoadedMsg:
		// Async commit hash loaded - update baseline for change detection
		if msg.commitHash != "" {
			m.lastCommitHashOriginal = msg.commitHash
			m.lastCommitHash = msg.commitHash
		}

	case spinnerTickMsg:
		var cmd tea.Cmd
		m, cmd = m.handleSpinnerTick()
		cmds = append(cmds, cmd)

	case fileChangedMsg:
		// Delegate to file watcher to update hash and get next command
		handled, cmd := m.fileWatcher.Update(msg)
		if handled {
			cmds = append(cmds, cmd)
		}

	case extendedMsgResult:
		m, _ = m.handleExtendedMsgResult(msg)

	case switchToFileViewMsg:
		return m.handleSwitchToFileView(msg)

	case execFinishedMsg:
		if msg.err != nil {
			log.Printf("External process failed: %v", msg.err)
		}
		// Bubbletea disables mouse reporting when handing over the terminal and
		// does not restore it, so re-enable it to keep wheel/click working.
		cmds = append(cmds, tea.EnableMouseCellMotion)
	}

	// Add extended message checks for visible commits (queues them for later)
	(&m).checkVisibleExtendedMessages()

	// Start tasks from pending queue to reach concurrency limit
	const maxConcurrentTasks = 10
	running := m.runningTasks.Load()
	available := maxConcurrentTasks - int(running)

	if available > 0 && len(m.pendingTasks) > 0 {
		m.tasksMutex.Lock()
		tasksToStart := min(available, len(m.pendingTasks))
		hashesToStart := m.pendingTasks[:tasksToStart]
		m.pendingTasks = m.pendingTasks[tasksToStart:]
		m.tasksMutex.Unlock()

		// Mark as checking and create commands
		for _, hash := range hashesToStart {
			m.commitExtendedInfo[hash] = CommitExtendedInfo{
				state:   ExtMsgChecking,
				subject: "",
			}
			cmds = append(cmds, checkExtendedMsgCmd(m.repoRoot, hash, &m.runningTasks))
		}
	}

	// Increment update counter to track View() calls
	m.updateCounter++

	// Record Update() duration for debug metrics and warn if slow
	elapsed := time.Since(start)
	if elapsed > 50*time.Millisecond {
		log.Printf("WARNING: Update() took %d ms (threshold: 50ms)", elapsed.Milliseconds())
		m.hadSlowUpdate = true // Persist slow update flag for debug UI
	}
	if m.debugUI {
		m.updateDurations = addDuration(m.updateDurations, elapsed)
	}

	// Return with all accumulated commands
	if len(cmds) > 0 {
		return m, tea.Batch(cmds...)
	}
	return m, nil
}

// ============================================================================
// View() Helper Functions
// ============================================================================

// renderCommitSubject gets the commit subject for the currently selected row
func (m Model) renderCommitSubject() string {
	itemCount := m.getItemCount()
	if m.selectedRow < 0 || m.selectedRow >= itemCount {
		return ""
	}

	var commitHash string
	if m.viewMode == DirectoryView {
		commitHash = m.fileEntries[m.selectedRow].CommitHash
	} else {
		commitHash = m.blameLines[m.selectedRow].CommitHash
	}

	if info, exists := m.commitExtendedInfo[commitHash]; exists && info.subject != "" {
		return info.subject
	}
	return ""
}

// renderLoadingIndicator returns loading state text for the header
func (m Model) renderLoadingIndicator() string {
	switch m.loadingState {
	case LoadingFile:
		return " | Loading..."
	case LoadingBlame:
		// Calculate blame progress percentage
		totalLines := len(m.blameLines)
		if totalLines > 0 {
			percentage := (m.linesWithBlame * 100) / totalLines
			return fmt.Sprintf(" | Blaming... (%d%%)", percentage)
		}
		return " | Blaming..."
	case LoadingComplete:
		return ""
	}
	return ""
}

// renderDebugInfo returns debug metrics display for the header
func (m Model) renderDebugInfo() string {
	if !m.debugUI {
		return ""
	}

	tickStr := fmt.Sprintf("%v", m.currentTickInterval)
	runningTasks := m.runningTasks.Load()
	avgUpdate := averageDuration(m.updateDurations)
	avgView := averageDuration(viewDurations)

	// Color-code performance metrics
	updateMs := float64(avgUpdate.Microseconds()) / 1000.0
	viewMs := float64(avgView.Microseconds()) / 1000.0

	updateColor := ColorPerfGood
	if updateMs >= 10 {
		updateColor = ColorPerfBad
	} else if updateMs >= 5 {
		updateColor = ColorPerfWarning
	}

	viewColor := ColorPerfGood
	if viewMs >= 10 {
		viewColor = ColorPerfBad
	} else if viewMs >= 5 {
		viewColor = ColorPerfWarning
	}

	coloredVU := lipgloss.NewStyle().Foreground(viewColor).Render(fmt.Sprintf("V%.1f", viewMs)) +
		" " + lipgloss.NewStyle().Foreground(updateColor).Render(fmt.Sprintf("U%.1f", updateMs))

	// Add SLOW indicator if we've had a slow update
	slowIndicator := ""
	if m.hadSlowUpdate {
		slowIndicator = lipgloss.NewStyle().Foreground(ColorWarningText).Bold(true).Render("SLOW") + " | "
	}

	return fmt.Sprintf(" | Updates: %d | Tick: %s | Tasks: %d | %s%s",
		m.updateCounter, tickStr, runningTasks, slowIndicator, coloredVU)
}

// renderFileChangeWarning returns file change indicator with modified filename
func (m Model) renderFileChangeWarning() string {
	// Check if file has changed (by content hash or commit hash)
	fileContentChanged := m.fileWatcher.HasChanged()
	commitChanged := m.lastCommitHashOriginal != "" && m.lastCommitHash != m.lastCommitHashOriginal
	fileChanged := fileContentChanged || commitChanged

	// Build filename display
	filenameDisplay := m.filename

	// For directory view, ensure trailing slash
	if m.viewMode == DirectoryView && !strings.HasSuffix(filenameDisplay, "/") {
		filenameDisplay = filenameDisplay + "/"
	}

	if fileChanged {
		// Determine message based on type of change
		changeMessage := "Changed"
		if commitChanged && !fileContentChanged {
			changeMessage = "New Commit"
		}

		coloredFilename := lipgloss.NewStyle().
			Foreground(ColorWarningText).
			Render(filenameDisplay)
		changeText := lipgloss.NewStyle().
			Foreground(ColorWarningText).
			Bold(true).
			Render(changeMessage)
		refreshText := lipgloss.NewStyle().
			Foreground(ColorTextDim).
			Render(", r: refresh")
		return coloredFilename + " (" + changeText + refreshText + ")"
	}

	return filenameDisplay
}

// renderEditorWarning returns editor status warning for the header
func (m Model) renderEditorWarning() string {
	if m.editorStatus == NoEditorFound {
		return " | " + lipgloss.NewStyle().
			Foreground(ColorWarningText).
			Bold(true).
			Render("⚠ ") +
			lipgloss.NewStyle().
				Foreground(ColorTextDim).
				Render(m.editorMessage)
	}
	return ""
}

// renderHeader builds the complete header text with all components
func (m Model) renderHeader(filenameDisplay, loadingIndicator, debugInfo, editorWarning string) string {
	var headerText string
	if m.viewMode == DirectoryView {
		headerText = fmt.Sprintf("Git Blame Dir: %s%s%s%s | h/F1: help | q: quit | ↑↓/jk: navigate | b: blame file | Enter: details", filenameDisplay, loadingIndicator, debugInfo, editorWarning)
	} else {
		headerText = fmt.Sprintf("Git Blame: %s%s%s%s | h/F1: help | q: quit | ↑↓/jk: navigate | e: editor | Enter: details", filenameDisplay, loadingIndicator, debugInfo, editorWarning)
	}

	// Truncate to window width: a wrapping header would push every table row
	// down by a line, breaking click-to-row mapping and the height assertion.
	if m.windowWidth > 0 {
		headerText = ansi.Truncate(headerText, m.windowWidth, "…")
	}

	return lipgloss.NewStyle().
		Foreground(ColorTextDim).
		Render(headerText)
}

// renderFileLoadError renders the file load error view
func (m Model) renderFileLoadError() string {
	// Display error message in table border
	errorText := lipgloss.NewStyle().
		Foreground(ColorTextSecondary).
		Render("<file does not exist>")

	// Create bordered box with error message
	borderedError := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		BorderForeground(ColorTableBorder).
		Padding(1, 2).
		Render(errorText)

	// Header with instructions
	header := lipgloss.NewStyle().
		Foreground(ColorTextDim).
		Render(fmt.Sprintf("Git Blame: %s | h/F1: help | q: quit", m.filename))

	return header + "\n" + borderedError
}

// renderDirectoryTable renders the directory view table and returns header + rows
func (m Model) renderDirectoryTable(ctx *BlameRowContext, commitWidth, extIndicatorWidth, authorWidth, dateWidth int, tableBorderStyle lipgloss.Style) (string, []string) {
	statusWidth := 1 // 1 char for M/A/D status

	columns := []TableColumn{
		{
			Name:       "Commit",
			Width:      commitWidth,
			Align:      lipgloss.Left,
			RenderCell: ctx.renderDirectoryCommitColumn,
		},
		{
			Name:       " ",
			Width:      extIndicatorWidth,
			Align:      lipgloss.Left,
			RenderCell: ctx.renderDirectoryExtendedIndicatorColumn,
		},
		{
			Name:       "Author",
			Width:      authorWidth,
			Align:      lipgloss.Left,
			RenderCell: ctx.renderDirectoryAuthorColumn,
		},
		{
			Name:       "Age",
			Width:      dateWidth,
			Align:      lipgloss.Right,
			RenderCell: ctx.renderDirectoryAgeColumn,
		},
		{
			Name:       "S",
			Width:      statusWidth,
			Align:      lipgloss.Center,
			RenderCell: ctx.renderStatusColumn,
		},
		{
			Name:       "File",
			Width:      0, // Last column width is calculated dynamically by Table
			Align:      lipgloss.Left,
			RenderCell: ctx.createFilepathColumnRenderer(),
		},
	}

	table := NewTable(columns, m.windowWidth, tableBorderStyle)
	tableHeader := table.RenderHeader()

	// Render visible rows from fileEntries
	endIdx := min(m.viewportStart+m.pageSize, len(m.fileEntries))

	var rows []string
	for i := m.viewportStart; i < endIdx; i++ {
		isSelected := i == m.selectedRow
		rowData := DirectoryRowData{
			FileEntry:  m.fileEntries[i],
			IsSelected: isSelected,
		}

		var row string
		if isSelected {
			row = table.RenderRowWithBackground(rowData, ColorSelectionBackground)
		} else {
			row = table.RenderRow(rowData)
		}
		rows = append(rows, row)
	}

	return tableHeader, rows
}

// renderFileTable renders the file blame view table and returns header + rows
func (m Model) renderFileTable(ctx *BlameRowContext, commitWidth, extIndicatorWidth, authorWidth, dateWidth int, tableBorderStyle lipgloss.Style) (string, []string) {
	lineNumWidth := len(strconv.Itoa(len(m.blameLines)))
	lineNumCellWidth := lineNumWidth
	ctx.lineNumWidth = lineNumWidth

	columns := []TableColumn{
		{
			Name:       "Commit",
			Width:      commitWidth,
			Align:      lipgloss.Left,
			RenderCell: ctx.renderCommitColumn,
		},
		{
			Name:       " ",
			Width:      extIndicatorWidth,
			Align:      lipgloss.Left,
			RenderCell: ctx.renderExtendedIndicatorColumn,
		},
		{
			Name:       "Author",
			Width:      authorWidth,
			Align:      lipgloss.Left,
			RenderCell: ctx.renderAuthorColumn,
		},
		{
			Name:       "Age",
			Width:      dateWidth,
			Align:      lipgloss.Right,
			RenderCell: ctx.renderAgeColumn,
		},
		{
			Name:       "#",
			Width:      lineNumCellWidth,
			Align:      lipgloss.Right,
			RenderCell: ctx.renderLineNumColumn,
		},
		{
			Name:       "Content",
			Width:      0, // Last column width is calculated dynamically by Table
			Align:      lipgloss.Left,
			RenderCell: ctx.createContentColumnRenderer(),
		},
	}

	table := NewTable(columns, m.windowWidth, tableBorderStyle)
	tableHeader := table.RenderHeader()

	// Render visible rows from blameLines
	endIdx := min(m.viewportStart+m.pageSize, len(m.blameLines))

	var rows []string
	for i := m.viewportStart; i < endIdx; i++ {
		isSelected := i == m.selectedRow
		rowData := BlameRowData{
			BlameLine:  m.blameLines[i],
			IsSelected: isSelected,
		}

		var row string
		if isSelected {
			row = table.RenderRowWithBackground(rowData, ColorSelectionBackground)
		} else {
			row = table.RenderRow(rowData)
		}
		rows = append(rows, row)
	}

	return tableHeader, rows
}

// renderModalOverlay overlays a modal on top of the output
func (m Model) renderModalOverlay(output string) string {
	// Create modal style to measure frame size
	modalStyle := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		Padding(1, 2)
	modalHorizontalFrameSize := modalStyle.GetHorizontalFrameSize()

	// Calculate max box width (leave some margin for window edges)
	maxBoxWidth := max(m.windowWidth-4, 40)

	// Calculate content width by subtracting frame size
	contentWidth := max(maxBoxWidth-modalHorizontalFrameSize+2, 30)
	wrappedText := wrapTextWithLineNumbers(m.modalText, contentWidth)
	totalLines := wrappedText.LineCount()

	// Find longest line for width calculation
	maxLineWidth := 0
	for i := range totalLines {
		lineWidth := wrappedText.LineWidth(i)
		if lineWidth > maxLineWidth {
			maxLineWidth = lineWidth
		}
	}

	// Calculate box width (add back frame size)
	neededBoxWidth := maxLineWidth + modalHorizontalFrameSize
	boxWidth := min(neededBoxWidth, maxBoxWidth)
	if boxWidth < 40 {
		boxWidth = 40
	}

	// Get all modal text (no scrolling in modal) and append keybindings
	numberedText := wrappedText.GetLineRange(0, totalLines)
	keybindings := lipgloss.NewStyle().Foreground(ColorTextDim).Render("q: close")
	visibleText := lipgloss.JoinVertical(lipgloss.Left, numberedText, "", keybindings)

	// Create modal with RED border
	style := lipgloss.NewStyle().
		Border(lipgloss.RoundedBorder()).
		BorderForeground(ColorErrorModalBorder).
		Padding(1, 2).
		Width(boxWidth)

	modal := style.Render(visibleText)

	// Manually overlay modal on top of existing output
	outputLines := strings.Split(output, "\n")
	modalLines := strings.Split(modal, "\n")

	// Calculate position to center modal
	modalHeight := len(modalLines)
	modalWidth := lipgloss.Width(modalLines[0]) // First line width (all should be same with border)

	startRow := max((m.windowHeight-modalHeight)/2, 0)

	// Overlay each modal line
	for i, modalLine := range modalLines {
		row := startRow + i
		if row >= 0 && row < len(outputLines) {
			outputLine := outputLines[row]
			outputLineWidth := lipgloss.Width(outputLine)

			// Calculate column to center modal
			startCol := max((m.windowWidth-modalWidth)/2, 0)
			endCol := startCol + modalWidth

			// Extract parts before and after modal, preserving ANSI codes
			before := ""
			after := ""

			if startCol > 0 {
				// Get first startCol characters (preserves ANSI codes)
				before = ansi.Truncate(outputLine, startCol, "")
			}

			if endCol < outputLineWidth {
				// Skip first endCol characters to get the after part (preserves ANSI codes)
				after = ansi.TruncateLeft(outputLine, endCol, "")
			}

			outputLines[row] = before + modalLine + after
		}
	}

	return strings.Join(outputLines, "\n")
}

// ============================================================================
// View() - Main Rendering Function
// ============================================================================

// View implements tea.Model interface. Renders the entire TUI.
// Handles three view modes: detail view, help view, and main blame table view.
// Also renders modal overlay for errors when needed.
func (m Model) View() string {
	start := time.Now()

	// Early returns for special views
	if m.detailView.IsShowing() {
		return m.detailView.View(m.windowWidth, m.windowHeight)
	}

	if m.windowWidth == 0 {
		return "Loading..."
	}

	if m.loadingState == LoadingComplete && m.fileLoadStatus == FileLoadError {
		return m.renderFileLoadError()
	}

	// Define fixed column widths (content only, table framework adds spacing)
	commitWidth := 8       // 8 chars
	extIndicatorWidth := 1 // 1 char
	authorWidth := 9       // 9 chars
	dateWidth := 3         // 3 chars

	// Create table border style to measure frame size
	tableBorderStyle := lipgloss.NewStyle().Border(lipgloss.RoundedBorder())

	// Create rendering context (used by both file and directory views)
	ctx := &BlameRowContext{
		oldestCommit:       m.oldestCommit,
		newestCommit:       m.newestCommit,
		spinnerFrame:       m.spinnerFrame,
		commitExtendedInfo: m.commitExtendedInfo,
	}

	// Render appropriate table based on view mode
	var tableHeader string
	var rows []string
	if m.viewMode == DirectoryView {
		tableHeader, rows = m.renderDirectoryTable(ctx, commitWidth, extIndicatorWidth, authorWidth, dateWidth, tableBorderStyle)
	} else {
		tableHeader, rows = m.renderFileTable(ctx, commitWidth, extIndicatorWidth, authorWidth, dateWidth, tableBorderStyle)
	}

	// Join all rows
	tableBody := lipgloss.JoinVertical(lipgloss.Left, rows...)

	// Get commit subject for selected line/file
	commitSubject := m.renderCommitSubject()

	// Create custom border with commit subject in bottom
	customBorder := lipgloss.RoundedBorder()
	customBorder.BottomLeft = "╰"
	customBorder.BottomRight = "╯"
	if commitSubject == "" {
		customBorder.Bottom = "─"
	} else {
		customBorder.Bottom = "─────" + commitSubject + "─────"
	}

	// Add border around entire table
	tableContent := lipgloss.JoinVertical(lipgloss.Left, tableHeader, tableBody)
	borderedTable := lipgloss.NewStyle().
		Border(customBorder).
		BorderForeground(ColorTableBorder).
		Render(tableContent)

	// Build header components
	loadingIndicator := m.renderLoadingIndicator()
	debugInfo := m.renderDebugInfo()
	filenameDisplay := m.renderFileChangeWarning()
	editorWarning := m.renderEditorWarning()
	header := m.renderHeader(filenameDisplay, loadingIndicator, debugInfo, editorWarning)

	// Render header and table
	output := header + "\n" + borderedTable
	viewEnd := min(m.viewportStart+m.pageSize, len(m.blameLines))

	// Assert: View output height must not exceed terminal window height
	// This validates that pageSize calculation is correct and prevents rendering issues
	// If this fails, it means we're trying to render more lines than the terminal can display
	outputLines := strings.Count(output, "\n") + 1
	if m.windowHeight > 0 && outputLines > m.windowHeight {
		logDebug("ERROR: View output has %d lines but window height is only %d", outputLines, m.windowHeight)
		panic(fmt.Sprintf("View output (%d lines) exceeds window height (%d)", outputLines, m.windowHeight))
	}

	logDebug("VIEW: state=%v lines=%d selected=%d viewport=%d-%d output_len=%d output_lines=%d",
		m.loadingState, len(m.blameLines), m.selectedRow, m.viewportStart, viewEnd, len(output), outputLines)

	// Only log full output if it changed
	if output != lastViewOutput {
		logDebug("VIEW OUTPUT:\n%s", output)
		logDebug("--- END VIEW OUTPUT ---")
		lastViewOutput = output
	} else {
		logDebug("VIEW OUTPUT: (unchanged)")
	}

	// Record View() duration for debug metrics
	if m.debugUI {
		viewDurations = addDuration(viewDurations, time.Since(start))
	}

	// Render modal overlay if active
	if m.modalText.LineCount() > 0 {
		output = m.renderModalOverlay(output)
	}

	return output
}

// main is the entry point for git-blimey.
// Parses command-line flags and starts the TUI.
// Flags: --debug-ui (enable debug logging), file[:line] argument.
func main() {
	programStart = time.Now()

	// Set up standard logger to buffer output and dump to stderr on exit
	log.SetOutput(&logBuffer)
	defer func() {
		if logBuffer.Len() > 0 {
			fmt.Fprintf(os.Stderr, "%s", logBuffer.String())
		}
	}()

	// Unset CI environment variable to enable interactive mode in Bubble Tea
	// (muesli/termenv checks CI and disables TTY detection if set)
	os.Unsetenv("CI")

	// Parse command line flags first (needed before flag.Args())
	debugUIFlag := flag.Bool("debug-ui", false, "Enable debug logging to debug.log for UI events")
	viewportOffsetFlag := flag.Int("viewport-offset", -1, "Editor viewport offset (accounts for soft wrapping; negative values allowed)")
	flag.Parse()

	// Set up debug logging to debug.log if --debug-ui is enabled
	if *debugUIFlag {
		var err error
		debugLog, err = os.OpenFile("debug.log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to open debug.log: %v\n", err)
			os.Exit(1)
		}
		defer debugLog.Close()
	}

	args := flag.Args()
	if len(args) < 1 {
		fmt.Fprintf(os.Stderr, "Usage: %s [--debug-ui] [--viewport-offset=LINE] <file>[:<line>] | <directory>\n", os.Args[0])
		os.Exit(1)
	}

	filename, cursorLine, err := parseFileArg(args[0])
	if err != nil {
		log.Fatal(err)
	}

	// --viewport-offset sets viewport position (git-blimey adds +3 for UI headers)
	viewportOffsetLine := *viewportOffsetFlag

	// Check if path is a directory
	fileInfo, err := os.Stat(filename)
	if err != nil {
		log.Fatal(fmt.Errorf("failed to access path: %w", err))
	}

	var model Model
	if fileInfo.IsDir() {
		// Directory view mode
		if cursorLine != 0 || viewportOffsetLine != -1 {
			log.Fatal(fmt.Errorf("cannot specify line number for directory view"))
		}
		model = NewDirectoryModel(filename, *debugUIFlag)
	} else {
		// File view mode (existing behavior)
		model = NewModel(filename, cursorLine, viewportOffsetLine, *debugUIFlag)
	}

	// WithMouseCellMotion enables wheel and click events. This takes over the
	// terminal's own scroll/selection handling; hold Shift to select text.
	p := tea.NewProgram(model, tea.WithAltScreen(), tea.WithMouseCellMotion())
	if _, err := p.Run(); err != nil {
		log.Fatal(err)
	}
}