1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
// asciinema-server: a minimal asciinema-compatible server in Go.
// All code lives in this single file for now.
package main

import (
	"bytes"
	"context"
	"crypto/md5"
	"crypto/rand"
	"database/sql"
	"embed"
	"encoding/base64"
	"encoding/json"
	"errors"
	"flag"
	"fmt"
	"html/template"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"
	"strconv"
	"strings"
	"sync"
	"time"

	"image"
	"image/color"
	"image/draw"
	"image/png"

	avt "avt-go"
	"avt-go/types"
	zstd "github.com/klauspost/stdgozstd"
	"golang.org/x/crypto/bcrypt"
	"golang.org/x/image/font"
	"golang.org/x/image/font/gofont/gomonobold"
	"golang.org/x/image/font/opentype"
	"golang.org/x/image/math/fixed"
	"golang.org/x/net/websocket"
	_ "modernc.org/sqlite"
	sqlite "zombiezen.com/go/sqlite"
	"zombiezen.com/go/sqlite/sqlitex"
)

// ---------------------------------------------------------------------------
// Embedded static assets
// ---------------------------------------------------------------------------

//go:embed static
var staticFiles embed.FS

// gomonoBoldFont is the Go Mono Bold font, used for PNG preview rendering.
var gomonoBoldFont = func() *opentype.Font {
	f, err := opentype.Parse(gomonobold.TTF)
	if err != nil {
		panic(err)
	}
	return f
}()

var (
	staticPlayerCSS    = mustReadStatic("static/asciinema-player.css")
	staticPlayerJS     = mustReadStatic("static/asciinema-player.min.js")
	staticLivePlayerJS = mustReadStatic("static/live-player.js")
	staticVtJS         = mustReadStatic("static/vt_js.js")
	staticVtWasm       = mustReadStatic("static/vt_js_bg.wasm")
)

func mustReadStatic(path string) []byte {
	data, err := staticFiles.ReadFile(path)
	if err != nil {
		panic(err)
	}
	return data
}

// ---------------------------------------------------------------------------
// Config
// ---------------------------------------------------------------------------

type Config struct {
	DatabasePath        string
	BaseURL             string // full URL e.g. "http://localhost:4000" or "https://example.com"
	AppTitle            string // displayed in page titles and login page
	UploadSizeLimit     int64
	StreamRetentionDays int // days to keep ended streams (default 7)
}

func loadConfig() Config {
	port := getenv("PORT", "4000")
	c := Config{
		DatabasePath:        getenv("DATABASE_PATH", "asciinema.db"),
		BaseURL:             getenv("BASE_URL", "http://localhost:"+port),
		AppTitle:            getenv("APP_TITLE", "asciinema"),
		UploadSizeLimit:     10 * 1024 * 1024, // 10 MB default
		StreamRetentionDays: 7,
	}
	if lim := os.Getenv("UPLOAD_SIZE_LIMIT"); lim != "" {
		if n, err := strconv.ParseInt(lim, 10, 64); err == nil {
			c.UploadSizeLimit = n
		}
	}
	if days := os.Getenv("STREAM_RETENTION_DAYS"); days != "" {
		if n, err := strconv.Atoi(days); err == nil && n > 0 {
			c.StreamRetentionDays = n
		}
	}
	// Strip trailing slash for consistent URL building
	c.BaseURL = strings.TrimRight(c.BaseURL, "/")
	return c
}

func getenv(key, def string) string {
	if v := os.Getenv(key); v != "" {
		return v
	}
	return def
}

// ---------------------------------------------------------------------------
// Database schema & migrations
// ---------------------------------------------------------------------------

const schema = `
CREATE TABLE IF NOT EXISTS users (
	id INTEGER PRIMARY KEY AUTOINCREMENT,
	email TEXT UNIQUE,
	username TEXT UNIQUE,
	auth_token TEXT UNIQUE,

	inserted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	password_hash TEXT
);

CREATE TABLE IF NOT EXISTS invites (
	token TEXT PRIMARY KEY,
	username TEXT NOT NULL UNIQUE,
	used_at DATETIME,
	inserted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS clis (
	id INTEGER PRIMARY KEY AUTOINCREMENT,
	user_id INTEGER REFERENCES users(id),
	token TEXT NOT NULL UNIQUE,
	revoked_at DATETIME,
	inserted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS asciicasts (
	id INTEGER PRIMARY KEY AUTOINCREMENT,
	user_id INTEGER REFERENCES users(id),
	cli_id INTEGER REFERENCES clis(id),
	version INTEGER NOT NULL DEFAULT 2,
	duration REAL NOT NULL DEFAULT 0,
	term_cols INTEGER NOT NULL DEFAULT 80,
	term_rows INTEGER NOT NULL DEFAULT 24,
	term_type TEXT,
	term_theme_fg TEXT,
	term_theme_bg TEXT,
	term_theme_palette TEXT,
	command TEXT,
	shell TEXT,
	user_agent TEXT,
	title TEXT,
	description TEXT,
	secret_token TEXT NOT NULL UNIQUE,
	idle_time_limit REAL,
	snapshot_at REAL,
	archivable INTEGER NOT NULL DEFAULT 1,
	archived_at DATETIME,
	inserted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
	cast_data BLOB
);

CREATE TABLE IF NOT EXISTS sessions (
	token TEXT PRIMARY KEY,
	user_id INTEGER NOT NULL REFERENCES users(id),
	expires_at DATETIME NOT NULL,
	inserted_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
);


`

// Server holds all shared server state.
type Server struct {
	cfg      Config
	db       *sql.DB      // normal queries
	blobConn *sqlite.Conn // zombiezen conn for blob I/O only
	blobMu   sync.Mutex
	hub      *StreamHub
}

// sqliteDSN builds the connection string, carrying the pragmas we want applied
// to every connection: WAL, foreign-key enforcement, and a busy_timeout so a
// writer waits for the lock rather than failing outright with SQLITE_BUSY.
//
// These must be _pragma DSN parameters. The modernc driver applies those on
// each connection it opens; the plausible-looking _journal_mode=/_foreign_keys=
// /_busy_timeout= spelling used previously did nothing at all, because the
// driver silently ignores DSN parameters it does not recognise. (This went
// unnoticed because the pool is capped at a single connection below, and the
// foreign_keys pragma was also being set via db.Exec.)
func sqliteDSN(path string) string {
	return "file:" + path +
		"?_pragma=busy_timeout(5000)&_pragma=journal_mode(WAL)&_pragma=foreign_keys(on)"
}

func openServer(cfg Config) (*Server, error) {
	db, err := sql.Open("sqlite", sqliteDSN(cfg.DatabasePath))
	if err != nil {
		return nil, err
	}
	db.SetMaxOpenConns(1)
	db.Exec(`PRAGMA foreign_keys = ON`)
	db.Exec(`PRAGMA secure_delete = ON`)
	if _, err := db.Exec(schema); err != nil {
		db.Close()
		return nil, fmt.Errorf("schema: %w", err)
	}
	if _, err := db.Exec(streamSchema); err != nil {
		db.Close()
		return nil, fmt.Errorf("stream schema: %w", err)
	}
	// Additive migrations — ALTER TABLE errors are ignored if column already exists.
	for _, migration := range []string{
		`ALTER TABLE users ADD COLUMN theme_dark  TEXT NOT NULL DEFAULT 'asciinema'`,
		`ALTER TABLE users ADD COLUMN theme_light TEXT NOT NULL DEFAULT 'default-light'`,
	} {
		db.Exec(migration) // intentionally ignore error (column may already exist)
	}
	for _, migration := range streamMigrations {
		db.Exec(migration) // intentionally ignore error (column may already exist)
	}

	blobConn, err := sqlite.OpenConn(cfg.DatabasePath, sqlite.OpenReadWrite|sqlite.OpenWAL)
	if err != nil {
		db.Close()
		return nil, fmt.Errorf("blob conn: %w", err)
	}
	blobConn.SetBusyTimeout(5 * time.Second)

	return &Server{cfg: cfg, db: db, blobConn: blobConn, hub: newStreamHub()}, nil
}

func (s *Server) close() {
	s.blobConn.Close()
	s.db.Close()
}

// ---------------------------------------------------------------------------
// Theme definitions
// ---------------------------------------------------------------------------

type themeInfo struct {
	ID         string
	Label      string
	Dark       bool
	Background string // matches --term-color-background in the CSS
	Foreground string // matches --term-color-foreground in the CSS
	Red        string // matches --term-color-1 in the CSS
	Green      string // matches --term-color-2 in the CSS
	Yellow     string // matches --term-color-3 in the CSS
	Blue       string // matches --term-color-4 in the CSS
	// Full 16-color ANSI palette: Color[0]=black … Color[15]=bright-white.
	// Used when rendering terminal content as a PNG.
	Color [16]string
}

var themes = []themeInfo{
	{
		ID: "asciinema", Label: "asciinema", Dark: true,
		Background: "#121314", Foreground: "#cccccc",
		Red: "#dd3c69", Green: "#4ebf22", Yellow: "#ddaf3c", Blue: "#26b0d7",
		Color: [16]string{
			"#121314", "#dd3c69", "#4ebf22", "#ddaf3c", "#26b0d7", "#a347ba", "#26b0d7", "#cccccc",
			"#686868", "#ff4f7a", "#70ef42", "#ffd04e", "#56d6ff", "#c76fe0", "#56d6ff", "#ffffff",
		},
	},
	{
		ID: "dracula", Label: "Dracula", Dark: true,
		Background: "#282a36", Foreground: "#f8f8f2",
		Red: "#ff5555", Green: "#50fa7b", Yellow: "#f1fa8c", Blue: "#bd93f9",
		Color: [16]string{
			"#21222c", "#ff5555", "#50fa7b", "#f1fa8c", "#bd93f9", "#ff79c6", "#8be9fd", "#f8f8f2",
			"#6272a4", "#ff6e6e", "#69ff94", "#ffffa5", "#d6acff", "#ff92df", "#a4ffff", "#ffffff",
		},
	},
	{
		ID: "monokai", Label: "Monokai", Dark: true,
		Background: "#272822", Foreground: "#f8f8f2",
		Red: "#f92672", Green: "#a6e22e", Yellow: "#f4bf75", Blue: "#66d9ef",
		Color: [16]string{
			"#272822", "#f92672", "#a6e22e", "#f4bf75", "#66d9ef", "#ae81ff", "#a1efe4", "#f8f8f2",
			"#75715e", "#f92672", "#a6e22e", "#f4bf75", "#66d9ef", "#ae81ff", "#a1efe4", "#f9f8f5",
		},
	},
	{
		ID: "gruvbox-dark", Label: "Gruvbox Dark", Dark: true,
		Background: "#282828", Foreground: "#fbf1c7",
		Red: "#cc241d", Green: "#98971a", Yellow: "#d79921", Blue: "#458588",
		Color: [16]string{
			"#282828", "#cc241d", "#98971a", "#d79921", "#458588", "#b16286", "#689d6a", "#a89984",
			"#928374", "#fb4934", "#b8bb26", "#fabd2f", "#83a598", "#d3869b", "#8ec07c", "#ebdbb2",
		},
	},
	{
		ID: "papercolor-light", Label: "PaperColor", Dark: false,
		Background: "#eeeeee", Foreground: "#444444",
		Red: "#af0000", Green: "#008700", Yellow: "#5f8700", Blue: "#0087af",
		Color: [16]string{
			"#eeeeee", "#af0000", "#008700", "#5f8700", "#0087af", "#878787", "#005f87", "#444444",
			"#bcbcbc", "#d70000", "#d70087", "#8700af", "#d75f00", "#d75f00", "#005faf", "#005f87",
		},
	},
	{
		ID: "github-light", Label: "GitHub", Dark: false,
		Background: "#f4f4f4", Foreground: "#3e3e3e",
		Red: "#970b16", Green: "#07962a", Yellow: "#c18401", Blue: "#003e8a",
		Color: [16]string{
			"#f4f4f4", "#970b16", "#07962a", "#c18401", "#003e8a", "#8f0075", "#007377", "#3e3e3e",
			"#888888", "#de3d35", "#3e9d4f", "#d2b700", "#0451a5", "#bc05bc", "#0598bc", "#ffffff",
		},
	},
	{
		ID: "default-light", Label: "Default Light", Dark: false,
		Background: "#f8f8f8", Foreground: "#383838",
		Red: "#ab4642", Green: "#a1b56c", Yellow: "#f7ca88", Blue: "#7cafc2",
		Color: [16]string{
			"#181818", "#ab4642", "#a1b56c", "#f7ca88", "#7cafc2", "#ba8baf", "#86c1b9", "#d8d8d8",
			"#585858", "#ab4642", "#a1b56c", "#f7ca88", "#7cafc2", "#ba8baf", "#86c1b9", "#f8f8f8",
		},
	},
	{
		ID: "gruvbox-light", Label: "Gruvbox Light", Dark: false,
		Background: "#fbf1c7", Foreground: "#282828",
		Red: "#9d0006", Green: "#79740e", Yellow: "#b57614", Blue: "#076678",
		Color: [16]string{
			"#fbf1c7", "#9d0006", "#79740e", "#b57614", "#076678", "#8f3f71", "#427b58", "#3c3836",
			"#928374", "#cc241d", "#98971a", "#d79921", "#458588", "#b16286", "#689d6a", "#282828",
		},
	},
}

var darkThemes, lightThemes []themeInfo

var themesByID = func() map[string]themeInfo {
	m := make(map[string]themeInfo, len(themes))
	for _, t := range themes {
		m[t.ID] = t
		if t.Dark {
			darkThemes = append(darkThemes, t)
		} else {
			lightThemes = append(lightThemes, t)
		}
	}
	return m
}()

// ---------------------------------------------------------------------------
// Models
// ---------------------------------------------------------------------------

type User struct {
	ID           int64
	Email        sql.NullString
	Username     sql.NullString
	AuthToken    sql.NullString
	PasswordHash sql.NullString
}

type CLI struct {
	ID        int64
	UserID    int64
	Token     string
	RevokedAt sql.NullTime
	User      *User
}

type Asciicast struct {
	ID            int64
	UserID        sql.NullInt64
	CliID         sql.NullInt64
	Version       int
	Duration      float64
	TermCols      int
	TermRows      int
	SecretToken   string
	Title         sql.NullString
	Description   sql.NullString
	Command       sql.NullString
	Shell         sql.NullString
	UserAgent     sql.NullString
	IdleTimeLimit sql.NullFloat64
	ArchivedAt    sql.NullTime
	InsertedAt    time.Time
	User          *User
}

// ---------------------------------------------------------------------------
// DB helpers
// ---------------------------------------------------------------------------

func findCLIByToken(db *sql.DB, token string) (*CLI, error) {
	cli := &CLI{}
	var userID sql.NullInt64
	var userDBID sql.NullInt64
	var userEmail, userUsername sql.NullString
	err := db.QueryRow(`
		SELECT c.id, c.user_id, c.token, c.revoked_at,
		       u.id, u.email, u.username
		FROM clis c
		LEFT JOIN users u ON u.id = c.user_id
		WHERE c.token = ?
	`, token).Scan(
		&cli.ID, &userID, &cli.Token, &cli.RevokedAt,
		&userDBID, &userEmail, &userUsername,
	)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	if userDBID.Valid {
		cli.User = &User{
			ID:       userDBID.Int64,
			Email:    userEmail,
			Username: userUsername,
		}
	}
	cli.UserID = userID.Int64
	return cli, nil
}

func insertAsciicast(db *sql.DB, a *Asciicast, castDataSize int) (int64, error) {
	res, err := db.Exec(`
		INSERT INTO asciicasts
			(user_id, cli_id, version, duration, term_cols, term_rows,
			 secret_token, title, command, shell, user_agent, idle_time_limit,
			 cast_data)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, zeroblob(?))
	`,
		nullInt64(a.UserID), nullInt64(a.CliID),
		a.Version, a.Duration, a.TermCols, a.TermRows,
		a.SecretToken,
		nullString(a.Title), nullString(a.Command), nullString(a.Shell),
		nullString(a.UserAgent), nullFloat64(a.IdleTimeLimit),
		castDataSize,
	)
	if err != nil {
		return 0, err
	}
	return res.LastInsertId()
}

const asciicastSelect = `
	SELECT a.id, a.user_id, a.cli_id, a.version, a.duration,
	       a.term_cols, a.term_rows, a.secret_token,
	       a.title, a.description, a.command, a.shell, a.user_agent,
	       a.idle_time_limit, a.archived_at, a.inserted_at,
	       u.id, u.email, u.username
	FROM asciicasts a
	LEFT JOIN users u ON u.id = a.user_id`

func scanAsciicast(row *sql.Row) (*Asciicast, error) {
	a := &Asciicast{}
	var userID, userDBID sql.NullInt64
	var userEmail, userUsername sql.NullString
	err := row.Scan(
		&a.ID, &userID, &a.CliID, &a.Version, &a.Duration,
		&a.TermCols, &a.TermRows, &a.SecretToken,
		&a.Title, &a.Description, &a.Command, &a.Shell, &a.UserAgent,
		&a.IdleTimeLimit, &a.ArchivedAt, &a.InsertedAt,
		&userDBID, &userEmail, &userUsername,
	)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	a.UserID = userID
	if userDBID.Valid {
		a.User = &User{ID: userDBID.Int64, Email: userEmail, Username: userUsername}
	}
	return a, nil
}

func getAsciicast(db *sql.DB, id int64) (*Asciicast, error) {
	return scanAsciicast(db.QueryRow(asciicastSelect+` WHERE a.id = ?`, id))
}

func getAsciicastBySecretToken(db *sql.DB, token string) (*Asciicast, error) {
	return scanAsciicast(db.QueryRow(asciicastSelect+` WHERE a.secret_token = ?`, token))
}

// lookupAsciicast resolves a URL id param by secret token.
func lookupAsciicast(db *sql.DB, idParam string) (*Asciicast, error) {
	return getAsciicastBySecretToken(db, strings.TrimSpace(idParam))
}

func deleteAsciicast(db *sql.DB, id int64) error {
	_, err := db.Exec(`DELETE FROM asciicasts WHERE id = ?`, id)
	return err
}

func updateAsciicast(db *sql.DB, id int64, title, description *string) error {
	_, err := db.Exec(`
		UPDATE asciicasts
		SET title = COALESCE(?, title),
		    description = COALESCE(?, description),
		    updated_at = CURRENT_TIMESTAMP
		WHERE id = ?
	`, title, description, id)
	return err
}

// RecordingRow is used for listing a user's recordings.
type RecordingRow struct {
	SecretToken string
	Title       sql.NullString
	Duration    float64
	InsertedAt  time.Time
}

func listUserRecordings(db *sql.DB, userID int64) ([]RecordingRow, error) {
	rows, err := db.Query(`
		SELECT secret_token, title, duration, inserted_at
		FROM asciicasts
		WHERE user_id = ?
		ORDER BY inserted_at DESC
	`, userID)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var recs []RecordingRow
	for rows.Next() {
		var r RecordingRow
		if err := rows.Scan(&r.SecretToken, &r.Title, &r.Duration, &r.InsertedAt); err != nil {
			return nil, err
		}
		recs = append(recs, r)
	}
	return recs, rows.Err()
}

// deleteUserAndEverything deletes a user and all associated data in a
// single transaction. Returns the number of recordings deleted.
func deleteUserAndEverything(db *sql.DB, userID int64) (int64, error) {
	tx, err := db.Begin()
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()

	// Count recordings first
	var count int64
	tx.QueryRow(`SELECT COUNT(*) FROM asciicasts WHERE user_id = ?`, userID).Scan(&count)

	steps := []struct {
		q    string
		args []any
	}{
		{`DELETE FROM asciicasts WHERE user_id = ?`, []any{userID}},
		{`DELETE FROM sessions WHERE user_id = ?`, []any{userID}},
		{`DELETE FROM clis WHERE user_id = ?`, []any{userID}},
		{`DELETE FROM invites WHERE username = (SELECT username FROM users WHERE id = ?)`, []any{userID}},
		{`DELETE FROM users WHERE id = ?`, []any{userID}},
	}
	for _, s := range steps {
		if _, err := tx.Exec(s.q, s.args...); err != nil {
			return 0, err
		}
	}

	return count, tx.Commit()
}

// ---------------------------------------------------------------------------
// Invite + user DB helpers
// ---------------------------------------------------------------------------

type Invite struct {
	Token    string
	Username string
	UsedAt   sql.NullTime
}

func createInvite(db *sql.DB, username, token string) error {
	_, err := db.Exec(
		`INSERT INTO invites (token, username) VALUES (?, ?)`,
		token, username,
	)
	return err
}

func hasPendingInvite(db *sql.DB, username string) (bool, error) {
	var count int
	err := db.QueryRow(
		`SELECT COUNT(*) FROM invites WHERE username = ? AND used_at IS NULL`, username,
	).Scan(&count)
	return count > 0, err
}

func getInvite(db *sql.DB, token string) (*Invite, error) {
	inv := &Invite{}
	err := db.QueryRow(
		`SELECT token, username, used_at FROM invites WHERE token = ?`, token,
	).Scan(&inv.Token, &inv.Username, &inv.UsedAt)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	return inv, err
}

func useInvite(db *sql.DB, token string) error {
	_, err := db.Exec(
		`UPDATE invites SET used_at = CURRENT_TIMESTAMP WHERE token = ? AND used_at IS NULL`,
		token,
	)
	return err
}

func createUser(db *sql.DB, username, passwordHash string) (int64, error) {
	res, err := db.Exec(
		`INSERT INTO users (username, password_hash) VALUES (?, ?)`,
		username, passwordHash,
	)
	if err != nil {
		return 0, err
	}
	return res.LastInsertId()
}

func getUserByUsername(db *sql.DB, username string) (*User, error) {
	u := &User{}
	err := db.QueryRow(
		`SELECT id, username, password_hash FROM users WHERE username = ?`,
		username,
	).Scan(&u.ID, &u.Username, &u.PasswordHash)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	return u, err
}

func getUserByID(db *sql.DB, id int64) (*User, error) {
	u := &User{}
	err := db.QueryRow(
		`SELECT id, username, password_hash FROM users WHERE id = ?`,
		id,
	).Scan(&u.ID, &u.Username, &u.PasswordHash)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	return u, err
}

// syncUserTheme saves the authenticated user's current dark/light theme preferences
// to the DB so they can be used to generate embed URLs for Mastodon crawlers,
// which visit the page without cookies.
func syncUserTheme(db *sql.DB, userID int64, darkID, lightID string) {
	db.Exec(
		`UPDATE users SET theme_dark = ?, theme_light = ? WHERE id = ?`,
		darkID, lightID, userID,
	)
}

// getOwnerTheme returns the owner's stored dark/light theme IDs for a recording.
// Falls back to server defaults if the user has no stored preferences.
func getOwnerTheme(db *sql.DB, userID sql.NullInt64) (darkID, lightID string) {
	darkID, lightID = defaultDarkThemeID, defaultLightThemeID
	if !userID.Valid {
		return
	}
	db.QueryRow(
		`SELECT theme_dark, theme_light FROM users WHERE id = ?`, userID.Int64,
	).Scan(&darkID, &lightID)
	// Validate — fall back to defaults if stored values are no longer valid themes.
	if themesByID[darkID].ID == "" {
		darkID = defaultDarkThemeID
	}
	if themesByID[lightID].ID == "" {
		lightID = defaultLightThemeID
	}
	return
}

// linkCLIToUser sets user_id on the clis row identified by token, creating it if needed.
func linkCLIToUser(db *sql.DB, installID string, userID int64) error {
	_, err := db.Exec(`
		INSERT INTO clis (token, user_id)
		VALUES (?, ?)
		ON CONFLICT(token) DO UPDATE SET user_id = excluded.user_id, updated_at = CURRENT_TIMESTAMP
	`, installID, userID)
	return err
}

// ---------------------------------------------------------------------------
// Session cookie helpers (DB-backed)
// ---------------------------------------------------------------------------

const sessionCookieName = "asciinema_session"
const sessionTTL = 7 * 24 * time.Hour

func (s *Server) setSessionCookie(w http.ResponseWriter, userID int64) error {
	token := randomToken(32)
	expires := time.Now().Add(sessionTTL)
	_, err := s.db.Exec(
		`INSERT INTO sessions (token, user_id, expires_at) VALUES (?, ?, ?)`,
		token, userID, expires.UTC().Format("2006-01-02 15:04:05"),
	)
	if err != nil {
		return err
	}
	http.SetCookie(w, &http.Cookie{
		Name:     sessionCookieName,
		Value:    token,
		Path:     "/",
		MaxAge:   int(sessionTTL.Seconds()),
		HttpOnly: true,
		SameSite: http.SameSiteLaxMode,
	})
	return nil
}

func (s *Server) clearSessionCookie(w http.ResponseWriter, r *http.Request) {
	if cookie, err := r.Cookie(sessionCookieName); err == nil {
		s.db.Exec(`DELETE FROM sessions WHERE token = ?`, cookie.Value)
	}
	http.SetCookie(w, &http.Cookie{
		Name:     sessionCookieName,
		Value:    "",
		Path:     "/",
		MaxAge:   -1,
		HttpOnly: true,
	})
}

// sessionUser returns the logged-in user from the request cookie, or nil.
func (s *Server) sessionUser(r *http.Request) (*User, error) {
	cookie, err := r.Cookie(sessionCookieName)
	if err != nil {
		return nil, nil
	}
	var userID int64
	err = s.db.QueryRow(
		`SELECT user_id FROM sessions WHERE token = ? AND expires_at > CURRENT_TIMESTAMP`,
		cookie.Value,
	).Scan(&userID)
	if errors.Is(err, sql.ErrNoRows) {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return getUserByID(s.db, userID)
}

// ---------------------------------------------------------------------------
// .cast file parsing (v2 / v3)
// ---------------------------------------------------------------------------

type CastMetadata struct {
	Version       int
	Width         int
	Height        int
	Title         string
	Command       string
	Env           map[string]string
	IdleTimeLimit float64
	Duration      float64 // computed from events
}

func parseCastMetadata(r io.Reader) (*CastMetadata, error) {
	dec := json.NewDecoder(r)

	// First line is the header object
	var header map[string]any
	if err := dec.Decode(&header); err != nil {
		return nil, fmt.Errorf("invalid cast header: %w", err)
	}

	ver, _ := header["version"].(float64)
	if ver != 2 && ver != 3 {
		return nil, fmt.Errorf("unsupported cast version: %v", ver)
	}

	meta := &CastMetadata{
		Version: int(ver),
		Width:   int(jsonFloat(header, "width")),
		Height:  int(jsonFloat(header, "height")),
		Title:   jsonString(header, "title"),
		Command: jsonString(header, "command"),
	}
	meta.IdleTimeLimit = jsonFloat(header, "idle_time_limit")
	// v3: terminal size may be nested under "term": {"cols": N, "rows": N}
	if meta.Width <= 0 || meta.Height <= 0 {
		if term, ok := header["term"].(map[string]any); ok {
			if meta.Width <= 0 {
				meta.Width = int(jsonFloat(term, "cols"))
			}
			if meta.Height <= 0 {
				meta.Height = int(jsonFloat(term, "rows"))
			}
		}
	}
	if env, ok := header["env"].(map[string]any); ok {
		meta.Env = make(map[string]string, len(env))
		for k, v := range env {
			if s, ok := v.(string); ok {
				meta.Env[k] = s
			}
		}
	}

	if meta.Width <= 0 || meta.Height <= 0 {
		return nil, fmt.Errorf("invalid terminal size: %dx%d", meta.Width, meta.Height)
	}

	// Scan remaining lines to find the last timestamp (= duration)
	var lastTime float64
	for {
		var event []any
		if err := dec.Decode(&event); err != nil {
			if errors.Is(err, io.EOF) {
				break
			}
			// Non-JSON lines (comments in v3) — skip
			continue
		}
		if len(event) >= 1 {
			if t, ok := event[0].(float64); ok && t > lastTime {
				lastTime = t
			}
		}
	}
	meta.Duration = lastTime

	return meta, nil
}

func jsonFloat(m map[string]any, key string) float64 {
	v, _ := m[key].(float64)
	return v
}

func jsonString(m map[string]any, key string) string {
	v, _ := m[key].(string)
	return v
}

// ---------------------------------------------------------------------------
// zstd helpers (same pattern as hosty)
// ---------------------------------------------------------------------------

var (
	zstdDecoder, _ = zstd.NewReader(nil)
	zstdEncoder    = zstd.NewWriter(nil)
)

// ---------------------------------------------------------------------------
// Auth middleware
// ---------------------------------------------------------------------------

type contextKey int

const ctxCLI contextKey = 1

// basicAuthToken extracts the password from HTTP Basic auth.
// asciinema CLI uses the install-id as the password.
func basicAuthToken(r *http.Request) string {
	auth := r.Header.Get("Authorization")
	if !strings.HasPrefix(auth, "Basic ") {
		return ""
	}
	decoded, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(auth, "Basic "))
	if err != nil {
		return ""
	}
	parts := strings.SplitN(string(decoded), ":", 2)
	if len(parts) != 2 {
		return ""
	}
	// The CLI sends the system $USER as the username, but we ignore it —
	// the install-id (password) is the actual credential.
	return parts[1] // password = install-id / CLI token
}

func (s *Server) requireCLI(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := basicAuthToken(r)
		if token == "" {
			jsonError(w, "Missing credentials", http.StatusUnauthorized)
			return
		}
		cli, err := findCLIByToken(s.db, token)
		if err != nil {
			jsonError(w, "Internal error", http.StatusInternalServerError)
			return
		}
		if cli == nil {
			jsonError(w, "Unregistered CLI", http.StatusUnauthorized)
			return
		}
		if cli.RevokedAt.Valid {
			jsonError(w, "Revoked CLI", http.StatusUnauthorized)
			return
		}
		r = r.WithContext(context.WithValue(r.Context(), ctxCLI, cli))
		next.ServeHTTP(w, r)
	})
}

// ---------------------------------------------------------------------------
// Handlers
// ---------------------------------------------------------------------------

// POST /api/v1/recordings  (CLI 3.x)
// POST /api/asciicasts      (CLI 2.x legacy)
func (s *Server) handleRecordingCreate() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Get install-id from Basic auth; auto-create anonymous CLI if unknown.
		token := basicAuthToken(r)
		if token == "" {
			jsonError(w, "Missing credentials", http.StatusUnauthorized)
			return
		}
		cli, err := findCLIByToken(s.db, token)
		if err != nil {
			jsonError(w, "Internal error", http.StatusInternalServerError)
			return
		}
		if cli != nil && cli.RevokedAt.Valid {
			jsonError(w, "Revoked CLI", http.StatusUnauthorized)
			return
		}

		// If CLI is not linked to an account, drain the upload and return a
		// 201 with a message pointing to the connect URL — the CLI prints it.
		if cli == nil || cli.User == nil {
			connectURL := s.cfg.BaseURL + "/connect/" + url.PathEscape(token)
			r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadSizeLimit)
			io.Copy(io.Discard, r.Body)
			w.Header().Set("Content-Type", "application/json")
			w.WriteHeader(http.StatusCreated)
			json.NewEncoder(w).Encode(map[string]string{
				"url": connectURL,
				"message": "This CLI is not linked to any account.\n\n" +
					"Register or log in at:\n\n    " + connectURL + "\n\n" +
					"Then upload your recording again.",
			})
			return
		}

		r.Body = http.MaxBytesReader(w, r.Body, s.cfg.UploadSizeLimit)
		if err := r.ParseMultipartForm(32 << 20); err != nil {
			jsonError(w, "Invalid multipart form", http.StatusBadRequest)
			return
		}

		// Accept field name "asciicast" (CLI 3.x) or "file" (CLI 2.x)
		var uploadFile io.ReadCloser
		for _, field := range []string{"asciicast", "file"} {
			f, _, err := r.FormFile(field)
			if err == nil {
				uploadFile = f
				break
			}
		}
		if uploadFile == nil {
			jsonError(w, "Missing file field", http.StatusBadRequest)
			return
		}
		defer uploadFile.Close()

		// Read entire upload into RAM — cast files are typically small
		raw, err := io.ReadAll(uploadFile)
		if err != nil {
			jsonError(w, "Upload failed", http.StatusInternalServerError)
			return
		}

		// Parse metadata from the raw bytes
		meta, err := parseCastMetadata(bytes.NewReader(raw))
		if err != nil {
			jsonError(w, "Invalid cast file: "+err.Error(), http.StatusUnprocessableEntity)
			return
		}

		// Compress with zstd
		compressed := zstdEncoder.AppendCompress(nil, raw)

		secretToken := randomToken(16)

		a := &Asciicast{
			UserID:      sql.NullInt64{Int64: cli.User.ID, Valid: true},
			CliID:       sql.NullInt64{Int64: cli.ID, Valid: true},
			Version:     meta.Version,
			Duration:    meta.Duration,
			TermCols:    meta.Width,
			TermRows:    meta.Height,
			SecretToken: secretToken,
			UserAgent:   sql.NullString{String: r.UserAgent(), Valid: true},
		}
		if meta.Title != "" {
			a.Title = sql.NullString{String: meta.Title, Valid: true}
		}
		if meta.Command != "" {
			a.Command = sql.NullString{String: meta.Command, Valid: true}
		}
		if meta.Env["SHELL"] != "" {
			a.Shell = sql.NullString{String: meta.Env["SHELL"], Valid: true}
		}
		if meta.IdleTimeLimit > 0 {
			a.IdleTimeLimit = sql.NullFloat64{Float64: meta.IdleTimeLimit, Valid: true}
		}

		// Insert row with zeroblob placeholder, then write blob
		id, err := insertAsciicast(s.db, a, len(compressed))
		if err != nil {
			jsonError(w, "DB error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		// Write compressed bytes into the blob via zombiezen conn
		if err := s.writeCastBlob(id, compressed); err != nil {
			_ = deleteAsciicast(s.db, id)
			jsonError(w, "Blob write error: "+err.Error(), http.StatusInternalServerError)
			return
		}

		castURL := s.cfg.BaseURL + "/a/" + secretToken

		w.Header().Set("Location", castURL)
		w.Header().Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		json.NewEncoder(w).Encode(map[string]string{"url": castURL})
	})
}

// writeCastBlob writes compressed cast data into the cast_data blob for the given asciicast id.
func (s *Server) writeCastBlob(id int64, compressed []byte) error {
	s.blobMu.Lock()
	defer s.blobMu.Unlock()

	blob, err := s.blobConn.OpenBlob("main", "asciicasts", "cast_data", id, true)
	if err != nil {
		return fmt.Errorf("open blob: %w", err)
	}
	defer blob.Close()

	_, err = blob.Write(compressed)
	return err
}

// readCastBlob reads and decompresses the cast_data blob for the given asciicast id.
func (s *Server) readCastBlob(id int64) ([]byte, error) {
	s.blobMu.Lock()
	defer s.blobMu.Unlock()

	var compressed []byte
	err := sqlitex.Execute(s.blobConn,
		`SELECT cast_data FROM asciicasts WHERE id = ?`,
		&sqlitex.ExecOptions{
			Args: []any{id},
			ResultFunc: func(stmt *sqlite.Stmt) error {
				n := stmt.ColumnLen(0)
				compressed = make([]byte, n)
				stmt.ColumnBytes(0, compressed)
				return nil
			},
		})
	if err != nil {
		return nil, fmt.Errorf("read blob: %w", err)
	}
	if compressed == nil {
		return nil, fmt.Errorf("cast_data is null for id %d", id)
	}

	return zstdDecoder.AppendDecompress(nil, compressed)
}

// PATCH /api/v1/recordings/:id
func (s *Server) handleRecordingUpdate() http.Handler {
	return s.requireCLI(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cli := cliFromRequest(r)
		id, err := pathID(r)
		if err != nil {
			jsonError(w, "Invalid id", http.StatusBadRequest)
			return
		}
		a, err := getAsciicast(s.db, id)
		if err != nil || a == nil {
			jsonError(w, "Not found", http.StatusNotFound)
			return
		}
		if a.UserID.Int64 != cli.User.ID {
			jsonError(w, "Forbidden", http.StatusForbidden)
			return
		}

		var params struct {
			Title       *string `json:"title"`
			Description *string `json:"description"`
		}
		if err := json.NewDecoder(r.Body).Decode(&params); err != nil {
			_ = r.ParseForm()
			if v := r.FormValue("title"); v != "" {
				params.Title = &v
			}
			if v := r.FormValue("description"); v != "" {
				params.Description = &v
			}
		}

		if err := updateAsciicast(s.db, id, params.Title, params.Description); err != nil {
			jsonError(w, "DB error", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusOK)
		json.NewEncoder(w).Encode(map[string]any{"id": id})
	}))
}

// DELETE /api/v1/recordings/:id
func (s *Server) handleRecordingDelete() http.Handler {
	return s.requireCLI(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		cli := cliFromRequest(r)
		id, err := pathID(r)
		if err != nil {
			jsonError(w, "Invalid id", http.StatusBadRequest)
			return
		}
		a, err := getAsciicast(s.db, id)
		if err != nil || a == nil {
			jsonError(w, "Not found", http.StatusNotFound)
			return
		}
		if a.UserID.Int64 != cli.User.ID {
			jsonError(w, "Forbidden", http.StatusForbidden)
			return
		}
		if err := deleteAsciicast(s.db, id); err != nil {
			jsonError(w, "DB error", http.StatusInternalServerError)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	}))
}

// GET /a/:id  or  GET /a/:id.cast  or  GET /a/:id.json
func (s *Server) handleRecordingShow() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Extract id from path: strip leading /a/ and any extension
		raw := strings.TrimPrefix(r.URL.Path, "/a/")
		var ext string
		if dot := strings.LastIndexByte(raw, '.'); dot >= 0 {
			ext = strings.ToLower(raw[dot:])
			raw = raw[:dot]
		}

		a, err := lookupAsciicast(s.db, raw)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		if a == nil {
			http.NotFound(w, r)
			return
		}
		if a.ArchivedAt.Valid {
			http.Error(w, "Gone", http.StatusGone)
			return
		}

		wantCast := ext == ".cast" || ext == ".json" ||
			strings.Contains(r.Header.Get("Accept"), "application/x-asciicast")

		if wantCast {
			s.serveCastFile(w, r, a)
		} else {
			user, _ := s.sessionUser(r)
			servePlayerPage(w, r, a, user, s.cfg.AppTitle, s.db, s.cfg.BaseURL)
		}
	})
}

func (s *Server) serveCastFile(w http.ResponseWriter, r *http.Request, a *Asciicast) {
	data, err := s.readCastBlob(a.ID)
	if err != nil {
		http.Error(w, "Server error", http.StatusInternalServerError)
		return
	}

	etag := fmt.Sprintf(`"%x"`, md5.Sum(data))
	w.Header().Set("ETag", etag)
	w.Header().Set("Cache-Control", "no-cache")

	if r.Header.Get("If-None-Match") == etag {
		w.WriteHeader(http.StatusNotModified)
		return
	}

	w.Header().Set("Content-Type", "application/x-asciicast")
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Write(data)
}

// sharedCSS is included verbatim in every page's <style> block.
// themeCSS sets the CSS custom properties; commonCSS has rules that every page uses.
const themeCSS = `{{if eq .Mode "auto"}}
    :root { --bg: {{.AutoDarkBg}}; --fg: {{.AutoDarkFg}}; --red: {{.AutoDarkRed}}; }
    @media (prefers-color-scheme: light) {
      :root { --bg: {{.AutoLightBg}}; --fg: {{.AutoLightFg}}; --red: {{.AutoLightRed}}; }
    }{{else}}
    :root { --bg: {{.ThemeBg}}; --fg: {{.ThemeFg}}; --red: {{.ThemeRed}}; }{{end}}
    body { background: var(--bg); color: var(--fg); }
`

const commonCSS = `
    body { font-family: sans-serif; }
    a { color: inherit; }
    label { display: block; margin: .6rem 0 .2rem; }
    input { width: 100%; padding: .4rem; box-sizing: border-box; background: var(--bg); color: inherit; border: 1px solid currentColor; border-radius: 3px; }
    button { background: var(--bg); border: 1px solid currentColor; color: inherit; padding: .2rem .6rem; cursor: pointer; border-radius: 3px; }
    button:hover { background: var(--fg); color: var(--bg); }
    .danger { border-color: var(--red); color: var(--red); }
    .danger:hover { background: var(--red); color: var(--bg); }
    .theme-sel { background: var(--bg); color: var(--fg); border: 1px solid color-mix(in oklab, var(--fg) 40%, var(--bg)); border-radius: 3px; padding: .2rem .4rem; cursor: pointer; font-size: .85rem; }
    #top-bar { position: fixed; top: .5rem; right: 1rem; }
    #theme-bar { display: flex; align-items: center; gap: .5rem; font-size: .85rem; }
    #theme-bar label { display: inline; margin: 0; }
    #mode-toggle { display: flex; border: 1px solid color-mix(in oklab, var(--fg) 40%, var(--bg)); border-radius: 3px; overflow: hidden; }
    #mode-toggle button { border: none; border-radius: 0; padding: .25rem .4rem; opacity: .45; display: flex; align-items: center; }
    #mode-toggle button:hover { opacity: .75; background: color-mix(in oklab, var(--fg) 15%, var(--bg)); color: inherit; }
    #mode-toggle button.active { opacity: 1; background: color-mix(in oklab, var(--fg) 20%, var(--bg)); }
    #mode-toggle button + button { border-left: 1px solid color-mix(in oklab, var(--fg) 40%, var(--bg)); }
`

// themeBar is the HTML+JS for the theme controls, inlined into every template.
// The mode selector is rendered as a three-button icon toggle.
// Pages that recreate on theme change must define onThemeChange(id) globally
// before this snippet runs (see playerTmpl).
const themeBar = `
<div id="theme-bar">
  <select id="sel-theme" class="theme-sel"></select>
  <div id="mode-toggle" role="group" aria-label="Color mode">
    <button type="button" id="mode-light" data-mode="light" title="Light mode">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="5"/><line x1="12" y1="1" x2="12" y2="3"/><line x1="12" y1="21" x2="12" y2="23"/>
        <line x1="4.22" y1="4.22" x2="5.64" y2="5.64"/><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"/>
        <line x1="1" y1="12" x2="3" y2="12"/><line x1="21" y1="12" x2="23" y2="12"/>
        <line x1="4.22" y1="19.78" x2="5.64" y2="18.36"/><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"/>
      </svg>
    </button>
    <button type="button" id="mode-auto" data-mode="auto" title="Auto (follow system)">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <circle cx="12" cy="12" r="10"/>
        <path d="M12 2 A10 10 0 0 0 12 22 Z" fill="currentColor" stroke="none"/>
      </svg>
    </button>
    <button type="button" id="mode-dark" data-mode="dark" title="Dark mode">
      <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"/>
      </svg>
    </button>
  </div>
</div>
<script>
(function() {
  var themeBg = {
    {{range .DarkThemes}}'{{.ID}}':'{{.Background}}',{{end}}
    {{range .LightThemes}}'{{.ID}}':'{{.Background}}',{{end}}
  };
  var themeFg = {
    {{range .DarkThemes}}'{{.ID}}':'{{.Foreground}}',{{end}}
    {{range .LightThemes}}'{{.ID}}':'{{.Foreground}}',{{end}}
  };
  var themeRed = {
    {{range .DarkThemes}}'{{.ID}}':'{{.Red}}',{{end}}
    {{range .LightThemes}}'{{.ID}}':'{{.Red}}',{{end}}
  };
  // Full 16-color palette per theme — used by the live canvas player.
  var themeColors = {
    {{range .DarkThemes}}'{{.ID}}':['{{index .Color 0}}','{{index .Color 1}}','{{index .Color 2}}','{{index .Color 3}}','{{index .Color 4}}','{{index .Color 5}}','{{index .Color 6}}','{{index .Color 7}}','{{index .Color 8}}','{{index .Color 9}}','{{index .Color 10}}','{{index .Color 11}}','{{index .Color 12}}','{{index .Color 13}}','{{index .Color 14}}','{{index .Color 15}}'],{{end}}
    {{range .LightThemes}}'{{.ID}}':['{{index .Color 0}}','{{index .Color 1}}','{{index .Color 2}}','{{index .Color 3}}','{{index .Color 4}}','{{index .Color 5}}','{{index .Color 6}}','{{index .Color 7}}','{{index .Color 8}}','{{index .Color 9}}','{{index .Color 10}}','{{index .Color 11}}','{{index .Color 12}}','{{index .Color 13}}','{{index .Color 14}}','{{index .Color 15}}'],{{end}}
  };

  // Options arrays built from server-rendered data, keyed by polarity.
  // We build them as Option objects so they can be freely moved in/out of the DOM.
  var optsByPolarity = {
    dark: [{{range .DarkThemes}}{id:'{{.ID}}',label:'{{.Label}}',bg:'{{.Background}}',fg:'{{.Foreground}}'},{{end}}],
    light: [{{range .LightThemes}}{id:'{{.ID}}',label:'{{.Label}}',bg:'{{.Background}}',fg:'{{.Foreground}}'},{{end}}],
  };

  var selTheme  = document.getElementById('sel-theme');
  var modeLight = document.getElementById('mode-light');
  var modeAuto  = document.getElementById('mode-auto');
  var modeDark  = document.getElementById('mode-dark');
  var root      = document.documentElement;
  var curMode   = '{{.Mode}}';
  var darkID    = '{{.DarkID}}';
  var lightID   = '{{.LightID}}';

  var CKMAX   = '; path=/; max-age=31536000; SameSite=Lax';
  var CKDARK  = '{{.CookieDark}}';
  var CKLIGHT = '{{.CookieLight}}';
  var CKMODE  = '{{.CookieMode}}';

  function osIsDark() {
    return window.matchMedia('(prefers-color-scheme: dark)').matches;
  }

  function setCookie(name, val) {
    document.cookie = name + '=' + val + CKMAX;
  }

  function activePolarityIsDark() {
    if (curMode === 'dark')  return true;
    if (curMode === 'light') return false;
    return osIsDark();
  }

  function activeThemeID() {
    return activePolarityIsDark() ? darkID : lightID;
  }

  // Rebuild the select with only the options matching the active polarity.
  function updateOptgroups() {
    var polarity = activePolarityIsDark() ? 'dark' : 'light';
    var activeID = activeThemeID();
    selTheme.innerHTML = '';
    optsByPolarity[polarity].forEach(function(t) {
      var o = document.createElement('option');
      o.value = t.id;
      o.textContent = t.label;
      o.style.background = t.bg;
      o.style.color = t.fg;
      if (t.id === activeID) o.selected = true;
      selTheme.appendChild(o);
    });
  }

  function updateModeButtons() {
    [modeLight, modeAuto, modeDark].forEach(function(btn) {
      btn.classList.toggle('active', btn.dataset.mode === curMode);
    });
  }

  function applyTheme(id) {
    root.style.setProperty('--bg',  themeBg[id]);
    root.style.setProperty('--fg',  themeFg[id]);
    root.style.setProperty('--red', themeRed[id]);
    if (typeof onThemeChange === 'function') {
      var colors = themeColors[id];
      var themeObj = colors ? { fg: themeFg[id], bg: themeBg[id], palette: colors } : null;
      onThemeChange(id, themeObj);
    }
  }

  // On select change: always stay in current mode, just update the stored ID.
  selTheme.addEventListener('change', function() {
    var id = selTheme.value;
    if (activePolarityIsDark()) { darkID = id;  setCookie(CKDARK,  id); }
    else                        { lightID = id; setCookie(CKLIGHT, id); }
    applyTheme(id);
  });

  // Mode button clicks: switch mode, rebuild options, apply.
  [modeLight, modeAuto, modeDark].forEach(function(btn) {
    btn.addEventListener('click', function() {
      curMode = btn.dataset.mode;
      setCookie(CKMODE, curMode);
      updateOptgroups();
      applyTheme(activeThemeID());
      updateModeButtons();
    });
  });

  // Initial setup — runs synchronously before first paint.
  updateOptgroups();
  updateModeButtons();
  applyTheme(activeThemeID());

  // React to OS preference changes while page is open (auto mode only).
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function() {
    if (curMode === 'auto') {
      updateOptgroups();
      applyTheme(activeThemeID());
    }
  });
})();
</script>
`

var playerTmpl = template.Must(template.New("player").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>{{.Title}}{{.AppTitle}}</title>
  <link rel="alternate" type="application/x-asciicast" href="{{.CastURL}}">
  <meta property="og:title" content="{{.Title}}{{.AppTitle}}">
  <meta property="og:url" content="{{.RecordingURL}}">
  <meta property="og:site_name" content="{{.AppTitle}}">
  <meta property="twitter:card" content="player">
  <meta property="twitter:player" content="{{.EmbedURL}}">
  <meta property="twitter:player:width" content="{{.EmbedWidth}}">
  <meta property="twitter:player:height" content="{{.EmbedHeight}}">
  <meta property="og:video" content="{{.EmbedURL}}">
  <meta property="og:video:secure_url" content="{{.EmbedURL}}">
  <meta property="og:video:type" content="text/html">
  <meta property="og:video:width" content="{{.EmbedWidth}}">
  <meta property="og:video:height" content="{{.EmbedHeight}}">
  <meta property="og:image" content="{{.PreviewURL}}">
  <meta property="og:image:width" content="1200">
  <meta property="og:image:height" content="675">
  <meta property="twitter:image" content="{{.PreviewURL}}">
  <link rel="stylesheet" href="/static/asciinema-player.css">
  <style>` + themeCSS + commonCSS + `
    html, body { height: 100%; margin: 0; }
    body { display: flex; flex-direction: column; }
    #player { flex: 1 1 0; min-height: 0; background: var(--bg); }
    #player-bar { flex: 0 0 auto; box-sizing: border-box; padding: .5rem 1rem; display: flex; flex-wrap: wrap; gap: .4rem; justify-content: space-between; align-items: center; }
    #player-bar-left  { display: flex; gap: 1rem; align-items: center; font-family: sans-serif; font-size: .85rem; }
    #player-bar-right { display: flex; align-items: center; }
  </style>
</head>
<body>
  <div id="player"></div>
  <div id="player-bar">
    <div id="player-bar-left">
{{if .IsOwner}}
      <a href="/user/my-recordings" style="color:inherit">← My recordings</a>
      <form method="POST" action="/recordings/{{.SecretToken}}/delete" style="margin:0">
        <button onclick="return confirm('Delete this recording?')">Delete this recording</button>
      </form>
{{end}}
    </div>
    <div id="player-bar-right">
{{if .LiveStream}}
  {{if .UpstreamPlayer}}
  <script src="/static/asciinema-player.min.js"></script>
  <script>
    var isLive = true;
    var upstreamEl = document.getElementById('player');
    function createUpstreamPlayer(themeID) {
      upstreamEl.innerHTML = '';
      AsciinemaPlayer.create({{.CastSrc}}, upstreamEl, {
        fit: 'both', theme: themeID, cols: {{.TermCols}}, rows: {{.TermRows}}, autoPlay: true, bufferTime: 20,
      });
    }
    function createPlayer() {}
    function onThemeChange(id, themeObj) { createUpstreamPlayer(id); }
  </script>
  {{else}}
  <script>
    window.liveplayer = { containerId: 'player', wsUrl: {{.CastSrc}} };
    window.liveplayer.setTheme = function(themeObj) {
      window.liveplayer.theme = themeObj;
    };
  </script>
  <script type="module" src="/static/live-player.js"></script>
  <script>
    var isLive = true;
    function createPlayer() {}
    function onThemeChange(id, themeObj) {
      if (!themeObj) return;
      window.liveplayer.setTheme(themeObj);
    }
  </script>
  {{end}}
{{else}}
  <script src="/static/asciinema-player.min.js"></script>
  <script>
    // Defined as a global so themeBar's applyTheme() can call it.
    var src = {{.CastSrc}};
    var el  = document.getElementById('player');
    var STORAGE_KEY = 'asciinema-pos-' + src;
    var player = null;

    var isPlaying = false;

    function wirePlayState(p) {
      p.addEventListener('play',  function() { isPlaying = true; });
      p.addEventListener('pause', function() { isPlaying = false; });
      p.addEventListener('ended', function() {
        isPlaying = false;
        localStorage.removeItem(STORAGE_KEY);
      });

      // The terminal text surface is focusable by default (for copy/paste)
      // but it's not a control — remove it from the tab order so keyboard
      // navigation goes straight to the actual controls.
      var termText = el.querySelector('.ap-term-text');
      if (termText) termText.removeAttribute('tabindex');

      // Show the control bar when any child element receives focus so that
      // keyboard users can see and interact with the controls. The player
      // toggles .ap-hud on .ap-wrapper to show/hide the control bar.
      var wrapper = el.querySelector('.ap-wrapper');
      if (wrapper) {
        el.addEventListener('focusin', function() {
          wrapper.classList.add('ap-hud');
        });
        el.addEventListener('focusout', function(e) {
          if (!el.contains(e.relatedTarget)) {
            wrapper.classList.remove('ap-hud');
          }
        });
      }
    }

    var isLive = false;

    function createPlayer(themeID, seekTo, autoPlay) {
      el.innerHTML = '';
      var opts = {fit: 'both', theme: themeID, cols: {{.TermCols}}, rows: {{.TermRows}}, autoPlay: autoPlay, bufferTime: 20};
      opts.preload = true;
      var p = AsciinemaPlayer.create(src, el, opts);
      wirePlayState(p);
      if (seekTo > 0) p.seek(seekTo);
      return p;
    }

    function onThemeChange(themeID) {
      if (player) {
        // Recreate with new theme, restoring position and play state.
        // getCurrentTime() wraps a synchronous driver call — resolves in
        // the same microtask tick, so seek/play happen before first paint.
        var playing = isPlaying;
        if (isLive) {
          player = createPlayer(themeID, 0, true);
        } else {
          player.getCurrentTime().then(function(t) {
            player = createPlayer(themeID, t, playing);
          });
        }
      } else {
        // Player not yet mounted — for live streams autoPlay immediately,
        // for recordings restore saved position.
        if (isLive) {
          player = createPlayer(themeID, 0, true);
        } else {
          var saved = parseFloat(localStorage.getItem(STORAGE_KEY));
          player = createPlayer(themeID, saved, false);
        }
      }
    }

    // Click on .ap-wrapper (the letterbox area around the terminal) but not
    // inside .ap-player (the terminal surface + controls) to toggle play/pause
    // and briefly show the control bar so the user sees the new state.
    var hudTimer = null;
    el.addEventListener('click', function(e) {
      if (!player) return;
      var wrapper = e.target.closest('.ap-wrapper');
      if (!wrapper) return;
      if (e.target.closest('.ap-player')) return;
      if (isPlaying) { player.pause(); } else { player.play(); }
      wrapper.classList.add('ap-hud');
      if (hudTimer) clearTimeout(hudTimer);
      hudTimer = setTimeout(function() { wrapper.classList.remove('ap-hud'); hudTimer = null; }, 1000);
    });

    // Save playback position on page unload.
    // getCurrentTime() wraps a synchronous driver call in a Promise, so it
    // resolves within the same microtask tick. Browsers drain the microtask
    // queue before tearing down the page, so localStorage.setItem fires in
    // time. Not guaranteed by spec but works reliably in practice.
    window.addEventListener('beforeunload', function() {
      if (!player) return;
      player.getCurrentTime().then(function(t) {
        if (t > 0) localStorage.setItem(STORAGE_KEY, t);
      });
    });
  </script>
{{end}}
` + themeBar + `
    </div>
  </div>
</body>
</html>
`))

type playerData struct {
	pageTheme
	Title          string
	AppTitle       string
	CastURL        string      // raw URL for the <link> tag
	CastSrc        template.JS // JSON-encoded URL for AsciinemaPlayer.create()
	IsOwner        bool
	SecretToken    string
	TermCols       int
	TermRows       int
	RecordingURL   string // full public URL for og:url
	EmbedURL       string // full embed URL with dark/light params
	EmbedWidth     int
	EmbedHeight    int
	PreviewURL     string // full URL to the SVG preview image
	LiveStream     bool   // if true: autoPlay, no preload, no seek restoration
	UpstreamPlayer bool   // if true: use asciinema-player.min.js instead of live-player.js
}

const (
	cookieDarkTheme  = "asciinema-theme-dark"
	cookieLightTheme = "asciinema-theme-light"
	cookieMode       = "asciinema-theme-mode"

	defaultDarkThemeID  = "asciinema"
	defaultLightThemeID = "solarized-light"
	defaultMode         = "auto"
)

// pageTheme holds the resolved colours and selections for server-side rendering.
// Embed this in every template data struct.
type pageTheme struct {
	ThemeBg     string // resolved background for this request (used for mode=dark/light)
	ThemeFg     string // resolved foreground for this request (used for mode=dark/light)
	ThemeRed    string // resolved red (color-1) for this request
	DarkID      string // selected dark theme id
	LightID     string // selected light theme id
	Mode        string // "dark" | "light" | "auto"
	DarkThemes  []themeInfo
	LightThemes []themeInfo
	// For mode=auto: both polarities so the server can emit a @media rule
	// and the browser resolves the correct theme with no JS required.
	AutoDarkBg   string
	AutoDarkFg   string
	AutoDarkRed  string
	AutoLightBg  string
	AutoLightFg  string
	AutoLightRed string
	// Cookie names exposed to templates so themeBar can write them.
	CookieDark  string
	CookieLight string
	CookieMode  string
}

func cookieVal(r *http.Request, name string) string {
	if c, err := r.Cookie(name); err == nil {
		return c.Value
	}
	return ""
}

// resolveEmbedThemes resolves the dark/light theme IDs for embed and preview
// pages from query params, falling back to the owner's DB preferences, then
// server defaults.
func resolveEmbedThemes(r *http.Request, db *sql.DB, userID sql.NullInt64) (darkID, lightID string) {
	darkID = r.URL.Query().Get("dark")
	lightID = r.URL.Query().Get("light")
	if themesByID[darkID].ID == "" || themesByID[lightID].ID == "" {
		ownerDark, ownerLight := getOwnerTheme(db, userID)
		if themesByID[darkID].ID == "" {
			darkID = ownerDark
		}
		if themesByID[lightID].ID == "" {
			lightID = ownerLight
		}
	}
	return
}

// resolveTheme reads the three theme cookies and returns the active colours.
// For mode=auto the server falls back to the dark theme; JS corrects on load.
func resolveTheme(r *http.Request) pageTheme {
	darkID := defaultDarkThemeID
	if v := cookieVal(r, cookieDarkTheme); themesByID[v].ID != "" {
		darkID = v
	}
	lightID := defaultLightThemeID
	if v := cookieVal(r, cookieLightTheme); themesByID[v].ID != "" {
		lightID = v
	}
	mode := defaultMode
	if v := cookieVal(r, cookieMode); v == "dark" || v == "light" || v == "auto" {
		mode = v
	}

	// Resolve which theme is active server-side.
	activeID := darkID
	if mode == "light" {
		activeID = lightID
	}
	// mode=auto: can't know OS preference server-side; use dark as safe default.
	t := themesByID[activeID]
	dark := themesByID[darkID]
	light := themesByID[lightID]
	return pageTheme{
		ThemeBg:      t.Background,
		ThemeFg:      t.Foreground,
		ThemeRed:     t.Red,
		DarkID:       darkID,
		LightID:      lightID,
		Mode:         mode,
		DarkThemes:   darkThemes,
		LightThemes:  lightThemes,
		AutoDarkBg:   dark.Background,
		AutoDarkFg:   dark.Foreground,
		AutoDarkRed:  dark.Red,
		AutoLightBg:  light.Background,
		AutoLightFg:  light.Foreground,
		AutoLightRed: light.Red,
		CookieDark:   cookieDarkTheme,
		CookieLight:  cookieLightTheme,
		CookieMode:   cookieMode,
	}
}

func servePlayerPage(w http.ResponseWriter, r *http.Request, a *Asciicast, sessionUser *User, appTitle string, db *sql.DB, baseURL string) {
	title := "recording"
	if a.Title.Valid && a.Title.String != "" {
		title = a.Title.String
	}

	isOwner := sessionUser != nil && a.UserID.Valid && sessionUser.ID == a.UserID.Int64

	pt := resolveTheme(r)

	// Persist the authenticated owner's theme preferences so that Mastodon
	// crawlers (which have no cookies) still get the owner's chosen themes
	// baked into the embed URL.
	if isOwner {
		syncUserTheme(db, sessionUser.ID, pt.DarkID, pt.LightID)
	}

	// For the embed URL, use the owner's DB-stored preferences rather than
	// the current request's cookies (which may belong to a crawler).
	ownerDark, ownerLight := getOwnerTheme(db, a.UserID)
	embedW, embedH := embedDimensions(a.TermCols, a.TermRows)
	recordingURL := baseURL + "/a/" + a.SecretToken
	embedURL := fmt.Sprintf("%s/a/%s/embed?dark=%s&light=%s",
		baseURL, a.SecretToken, ownerDark, ownerLight)
	previewURL := fmt.Sprintf("%s/a/%s/preview.png?dark=%s&light=%s",
		baseURL, a.SecretToken, ownerDark, ownerLight)

	castURL := "/a/" + a.SecretToken + ".cast"
	src, _ := json.Marshal(castURL)

	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	playerTmpl.Execute(w, playerData{
		pageTheme:    pt,
		Title:        title,
		AppTitle:     appTitle,
		CastURL:      castURL,
		CastSrc:      template.JS(src),
		IsOwner:      isOwner,
		SecretToken:  a.SecretToken,
		TermCols:     a.TermCols,
		TermRows:     a.TermRows,
		RecordingURL: recordingURL,
		EmbedURL:     embedURL,
		EmbedWidth:   embedW,
		EmbedHeight:  embedH,
		PreviewURL:   previewURL,
	})
}

// ---------------------------------------------------------------------------
// Recordings management page
// ---------------------------------------------------------------------------

var recordingsTmpl = template.Must(template.New("recordings").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>My recordings — {{.AppTitle}}</title>
  <style>` + themeCSS + commonCSS + `
     body { max-width: 800px; margin: 2rem auto; padding: 0 1rem; }
    h1 { margin-bottom: 1.5rem; }
    h2 { margin: 2rem 0 1rem; }
    table { width: 100%; border-collapse: collapse; }
    th { text-align: left; border-bottom: 2px solid currentColor; padding: .4rem .6rem; }
    td { padding: .4rem .6rem; border-bottom: 1px solid color-mix(in oklab, var(--fg) 30%, var(--bg)); vertical-align: middle; }
    .empty { opacity: .5; font-style: italic; }
    .stream-ended { opacity: .5; }
    .stream-offline { opacity: .7; border-bottom: 1px dotted currentColor; cursor: help; }
    .stream-actions { display: flex; gap: .5rem; align-items: center; }
    .account-delete { margin-top: 3rem; padding-top: 1rem; border-top: 1px solid color-mix(in oklab, var(--fg) 30%, var(--bg)); }
    .title-view { display: flex; align-items: center; gap: .4rem; }
    .title-edit { display: none; align-items: center; gap: .4rem; }
    .title-edit input { width: 18rem; }
    #page-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 1.5rem; }
    #bottom-bar { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid color-mix(in oklab, var(--fg) 20%, var(--bg)); display: flex; justify-content: flex-end; }
    @media (max-width: 600px) {
      table, thead, tbody, tr, th, td { display: block; }
      thead { display: none; }
      tr { border: 1px solid color-mix(in oklab, var(--fg) 25%, var(--bg)); border-radius: 4px; margin-bottom: .75rem; }
      td { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid color-mix(in oklab, var(--fg) 10%, var(--bg)); }
      td:last-child { border-bottom: none; }
      td::before { content: attr(data-label); opacity: .6; flex-shrink: 0; margin-right: 1rem; }
      td[data-label=""] { justify-content: flex-end; }
      td[data-label=""]::before { display: none; }
      .title-edit input { width: 100%; }
    }
  </style>
</head>
<body>
  <div id="page-header">
    <h1 style="margin:0">My recordings</h1>
    <div style="display:flex;gap:1rem;align-items:center">
      <span style="opacity:.6">{{.Username}}</span>
      <form method="POST" action="/logout" style="margin:0">
        <button>Log out</button>
      </form>
    </div>
  </div>

  {{if .Streams}}
  <h2>My streams</h2>
  <table>
    <thead><tr><th>Title</th><th>Status</th><th>Last active</th><th></th></tr></thead>
    <tbody>
    {{range .Streams}}
    <tr>
      <td data-label="Title">
        <span class="title-view">
          <a href="/s/{{.PublicToken}}">{{if .Title}}{{.Title}}{{else}}<span class="empty">(untitled)</span>{{end}}</a>
          <button type="button" class="rename-btn" aria-label="Rename this stream">Rename</button>
        </span>
        <span class="title-edit" role="group" aria-label="Rename stream">
          <form method="POST" action="/streams/{{.PublicToken}}/rename" style="margin:0;display:flex;align-items:center;gap:.4rem">
            <input type="text" name="title" value="{{.Title}}" aria-label="Stream title" autocomplete="off">
            <button type="submit">Save</button>
            <button type="button" class="cancel-btn">Cancel</button>
          </form>
        </span>
      </td>
      <td data-label="Status">
        {{if .Live}}<span class="live-badge">LIVE</span>
        {{else if .Ended}}<span class="stream-ended">ended</span>
        {{else}}<span class="stream-offline" title="Resume with: {{.ResumeCmd}}">offline</span>
        {{end}}
      </td>
      <td data-label="Last active">{{.UpdatedAt}}</td>
      <td data-label="">
        <div class="stream-actions">
          <form method="POST" action="/streams/{{.PublicToken}}/delete" style="margin:0">
            <button class="danger" onclick="return confirm('Delete this stream?')">Delete</button>
          </form>
        </div>
      </td>
    </tr>
    {{end}}
    </tbody>
  </table>
  {{end}}

  {{if .Recordings}}
  <h2>My recordings</h2>
  <table>
    <thead><tr><th>Title</th><th>Duration</th><th>Date</th><th></th></tr></thead>
    <tbody>
    {{range .Recordings}}
    <tr>
      <td data-label="Title">
        <span class="title-view">
          <a href="/a/{{.SecretToken}}">{{if .Title}}{{.Title}}{{else}}<span class="empty">(untitled)</span>{{end}}</a>
          <button type="button" class="rename-btn" aria-label="Rename this recording">Rename</button>
        </span>
        <span class="title-edit" role="group" aria-label="Rename recording">
          <form method="POST" action="/recordings/{{.SecretToken}}/rename" style="margin:0;display:flex;align-items:center;gap:.4rem">
            <input type="text" name="title" value="{{.Title}}" aria-label="Recording title" autocomplete="off">
            <button type="submit">Save</button>
            <button type="button" class="cancel-btn">Cancel</button>
          </form>
        </span>
      </td>
      <td data-label="Duration">{{.Duration}}</td>
      <td data-label="Date">{{.Date}}</td>
      <td data-label="">
        <form method="POST" action="/recordings/{{.SecretToken}}/delete" style="margin:0">
          <button class="danger" onclick="return confirm('Delete this recording?')">Delete</button>
        </form>
      </td>
    </tr>
    {{end}}
    </tbody>
  </table>
  {{else}}
  <p class="empty">No recordings yet.</p>
  {{end}}
  <div class="account-delete">
    <form method="POST" action="/user/delete-account"
          onsubmit="return confirm('Delete your account and ALL recordings? This cannot be undone.')">
      <button class="danger">Delete account and all recordings</button>
    </form>
  </div>
  <script>
    document.querySelectorAll('tr').forEach(function(row) {
      var view = row.querySelector('.title-view');
      var edit = row.querySelector('.title-edit');
      if (!view || !edit) return;
      var renameBtn = view.querySelector('.rename-btn');
      var cancelBtn = edit.querySelector('.cancel-btn');
      var input = edit.querySelector('input');

      function showEdit() {
        view.style.display = 'none';
        edit.style.display = 'flex';
        input.focus();
        input.select();
      }
      function showView() {
        edit.style.display = 'none';
        view.style.display = 'flex';
        renameBtn.focus();
      }

      renameBtn.addEventListener('click', showEdit);
      cancelBtn.addEventListener('click', showView);
      input.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') { e.preventDefault(); showView(); }
        // Enter submits the form natively — no handling needed.
      });
    });
  </script>
  <div id="bottom-bar">
` + themeBar + `
  </div>
</body>
</html>
`))

type recordingEntry struct {
	SecretToken string
	Title       string
	Duration    string
	Date        string
}

type streamEntry struct {
	PublicToken string
	Title       string
	Live        bool
	Ended       bool
	UpdatedAt   string // human-readable relative time
	ResumeCmd   string // "asciinema stream --remote <public_token>"
}

type recordingsData struct {
	pageTheme
	AppTitle   string
	Username   string
	Recordings []recordingEntry
	Streams    []streamEntry
}

// GET /user/my-recordings
func (s *Server) handleUserRecordingsList() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := s.sessionUser(r)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		if user == nil {
			http.Redirect(w, r, "/connect/no-install-id", http.StatusSeeOther)
			return
		}

		recs, err := listUserRecordings(s.db, user.ID)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		entries := make([]recordingEntry, len(recs))
		for i, r := range recs {
			title := ""
			if r.Title.Valid {
				title = r.Title.String
			}
			entries[i] = recordingEntry{
				SecretToken: r.SecretToken,
				Title:       title,
				Duration:    formatDuration(r.Duration),
				Date:        r.InsertedAt.Format("2006-01-02"),
			}
		}

		streams, err := listUserStreams(s.db, user.ID)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		streamEntries := make([]streamEntry, len(streams))
		for i, st := range streams {
			title := ""
			if st.Title.Valid {
				title = st.Title.String
			}
			streamEntries[i] = streamEntry{
				PublicToken: st.PublicToken,
				Title:       title,
				Live:        st.Live,
				Ended:       st.Ended,
				UpdatedAt:   timeAgo(st.UpdatedAt),
				ResumeCmd:   "asciinema stream --remote " + st.PublicToken,
			}
		}

		pt := resolveTheme(r)
		syncUserTheme(s.db, user.ID, pt.DarkID, pt.LightID)
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		recordingsTmpl.Execute(w, recordingsData{
			pageTheme:  pt,
			AppTitle:   s.cfg.AppTitle,
			Username:   user.Username.String,
			Recordings: entries,
			Streams:    streamEntries,
		})
	})
}

// POST /recordings/{token}/rename
func (s *Server) handleRecordingBrowserRename() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := s.sessionUser(r)
		if err != nil || user == nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		token := r.PathValue("token")
		a, err := getAsciicastBySecretToken(s.db, token)
		if err != nil || a == nil {
			http.NotFound(w, r)
			return
		}
		if !a.UserID.Valid || a.UserID.Int64 != user.ID {
			http.Error(w, "Forbidden", http.StatusForbidden)
			return
		}
		r.ParseForm()
		title := strings.TrimSpace(r.FormValue("title"))
		if err := updateAsciicast(s.db, a.ID, &title, nil); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
	})
}

// POST /recordings/{token}/delete
func (s *Server) handleRecordingBrowserDelete() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := s.sessionUser(r)
		if err != nil || user == nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		token := r.PathValue("token")
		a, err := getAsciicastBySecretToken(s.db, token)
		if err != nil || a == nil {
			http.NotFound(w, r)
			return
		}
		if !a.UserID.Valid || a.UserID.Int64 != user.ID {
			http.Error(w, "Forbidden", http.StatusForbidden)
			return
		}
		if err := deleteAsciicast(s.db, a.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
	})
}

// POST /user/delete-account
func (s *Server) handleUserDeleteAccount() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, err := s.sessionUser(r)
		if err != nil || user == nil {
			http.Error(w, "Unauthorized", http.StatusUnauthorized)
			return
		}
		if _, err := deleteUserAndEverything(s.db, user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		s.clearSessionCookie(w, r)
		http.Redirect(w, r, "/", http.StatusSeeOther)
	})
}

// ---------------------------------------------------------------------------
// Root + standalone login page
// ---------------------------------------------------------------------------

var loginTmpl = template.Must(template.New("login").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Log in — {{.AppTitle}}</title>
  <style>` + themeCSS + commonCSS + `
    body { max-width: 380px; margin: 4rem auto; padding: 0 1rem; }
    form button { margin-top: 1rem; padding: .5rem 1.2rem; }
    .error { color: #c00; margin: .5rem 0; }
    .muted { opacity: .6; }
  </style>
</head>
<body>
  <h1>Log in</h1>
  <p class="muted" style="margin-top:-.5rem">Welcome to {{.AppTitle}}.</p>
  {{if .Error}}<p class="error">{{.Error}}</p>{{end}}
  {{if .ShowRegister}}
  <h2>Set new password</h2>
  <form method="POST" action="/reset-password">
    <label>Invite token<input type="text" name="invite_token" required autocomplete="off"></label>
    <label>New password<input type="password" name="password" required></label>
    <label>Confirm password<input type="password" name="confirm" required></label>
    <button type="submit">Set password &amp; log in</button>
  </form>
  {{else}}
  <form method="POST" action="/login">
    <label>Username<input type="text" name="username" required autocomplete="username"></label>
    <label>Password<input type="password" name="password" required autocomplete="current-password"></label>
    <button type="submit">Log in</button>
  </form>
  {{end}}
  <div id="top-bar">
` + themeBar + `
  </div>
</body>
</html>
`))

type loginData struct {
	pageTheme
	AppTitle     string
	Error        string
	ShowRegister bool // shown when admin has reset the user's password
}

// GET / — redirect to my-recordings if logged in, else to /login
func (s *Server) handleRoot() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path != "/" {
			http.NotFound(w, r)
			return
		}
		user, err := s.sessionUser(r)
		if err != nil || user == nil {
			http.Redirect(w, r, "/login", http.StatusSeeOther)
			return
		}
		http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
	})
}

// GET /login
func (s *Server) handleLoginShow() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// Already logged in? Go to recordings.
		user, _ := s.sessionUser(r)
		if user != nil {
			http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
			return
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		loginTmpl.Execute(w, loginData{pageTheme: resolveTheme(r), AppTitle: s.cfg.AppTitle, Error: r.URL.Query().Get("error")})
	})
}

// POST /login
func (s *Server) handleLoginSubmit() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		pt := resolveTheme(r)

		username := strings.TrimSpace(r.FormValue("username"))
		user, err := s.authenticateUser(username, r.FormValue("password"))
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		if user == nil {
			msg := s.loginErrorMessage(username)
			pending, _ := hasPendingInvite(s.db, username)
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.WriteHeader(http.StatusUnprocessableEntity)
			loginTmpl.Execute(w, loginData{pageTheme: pt, AppTitle: s.cfg.AppTitle, Error: msg, ShowRegister: pending})
			return
		}

		if err := s.setSessionCookie(w, user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
	})
}

// ---------------------------------------------------------------------------
// Connect page (register / login / link CLI)
// ---------------------------------------------------------------------------

var connectTmpl = template.Must(template.New("connect").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Link CLI — {{.AppTitle}}</title>
  <style>` + themeCSS + commonCSS + `
    body { max-width: 480px; margin: 3rem auto; padding: 0 1rem; }
    h2 { margin-top: 2rem; }
    form button { margin-top: 1rem; padding: .5rem 1.2rem; }
    .error { color: #c00; margin: .5rem 0; }
    .sep { text-align: center; margin: 1.5rem 0; opacity: .5; }
    .info { background: color-mix(in oklab, var(--bg) 80%, var(--fg)); padding: .8rem; border-radius: 4px; font-family: monospace; word-break: break-all; border: 1px solid currentColor; }
  </style>
</head>
<body>
  <h1>Link CLI to your account</h1>
  <p>CLI install ID:</p>
  <div class="info">{{.InstallID}}</div>

{{if .Linked}}
  <p>✓ CLI successfully linked to account <strong>{{.Username}}</strong>. You can close this page and upload again.</p>
  <form method="POST" action="/logout" style="margin-top:.5rem">
    <button type="submit">Log out</button>
  </form>
{{else if .LoggedIn}}
  <h2>You are logged in as <strong>{{.Username}}</strong></h2>
  <form method="POST" action="/connect/{{.InstallID}}/link">
    <button type="submit">Link this CLI to your account</button>
  </form>
  <form method="POST" action="/logout" style="margin-top:.5rem">
    <button type="submit">Log out</button>
  </form>
{{else}}
  {{if .Error}}<p class="error">{{.Error}}</p>{{end}}

  <h2>Register</h2>
  <form method="POST" action="/connect/{{.InstallID}}/register">
    <label>Invite token<input type="text" name="invite_token" required autocomplete="off"></label>
    <label>Password<input type="password" name="password" required></label>
    <label>Confirm password<input type="password" name="confirm" required></label>
    <button type="submit">Register &amp; link CLI</button>
  </form>

  <div class="sep">— or —</div>

  <h2>Log in</h2>
  <form method="POST" action="/connect/{{.InstallID}}/login">
    <label>Username<input type="text" name="username" required autocomplete="username"></label>
    <label>Password<input type="password" name="password" required autocomplete="current-password"></label>
    <button type="submit">Log in &amp; link CLI</button>
  </form>
{{end}}
  <div id="top-bar">
` + themeBar + `
  </div>
</body>
</html>
`))

type connectData struct {
	pageTheme
	AppTitle  string
	InstallID string
	LoggedIn  bool
	Linked    bool
	Username  string
	Error     string
}

// GET /connect/:install_id
func (s *Server) handleConnectShow() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		installID := r.PathValue("install_id")
		user, err := s.sessionUser(r)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		data := connectData{pageTheme: resolveTheme(r), AppTitle: s.cfg.AppTitle, InstallID: installID}
		if user != nil {
			data.LoggedIn = true
			data.Username = user.Username.String
		}
		if r.URL.Query().Get("linked") == "1" {
			data.Linked = true
		}
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		connectTmpl.Execute(w, data)
	})
}

// POST /connect/:install_id/register
func (s *Server) handleConnectRegister() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		installID := r.PathValue("install_id")
		r.ParseForm()
		inviteToken := strings.TrimSpace(r.FormValue("invite_token"))
		password := r.FormValue("password")
		confirm := r.FormValue("confirm")

		pt := resolveTheme(r)
		renderErr := func(msg string) {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.WriteHeader(http.StatusUnprocessableEntity)
			connectTmpl.Execute(w, connectData{pageTheme: pt, AppTitle: s.cfg.AppTitle, InstallID: installID, Error: msg})
		}

		if inviteToken == "" || password == "" {
			renderErr("All fields are required.")
			return
		}
		if password != confirm {
			renderErr("Passwords do not match.")
			return
		}
		if len(password) < 8 {
			renderErr("Password must be at least 8 characters.")
			return
		}

		inv, err := getInvite(s.db, inviteToken)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		if inv == nil || inv.UsedAt.Valid {
			renderErr("Invalid or already-used invite token.")
			return
		}

		hash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		userID, err := createUser(s.db, inv.Username, string(hash))
		if err != nil {
			renderErr("Username already taken.")
			return
		}

		if err := useInvite(s.db, inviteToken); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		if err := linkCLIToUser(s.db, installID, userID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		if err := s.setSessionCookie(w, userID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/connect/"+url.PathEscape(installID)+"?linked=1", http.StatusSeeOther)
	})
}

// POST /reset-password — set a new password using an invite token.
// No CLI linking; used when the admin runs reset-password for an existing user.
func (s *Server) handlePasswordReset() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		r.ParseForm()

		pt := resolveTheme(r)
		renderErr := func(msg string) {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.WriteHeader(http.StatusUnprocessableEntity)
			loginTmpl.Execute(w, loginData{pageTheme: pt, AppTitle: s.cfg.AppTitle, Error: msg, ShowRegister: true})
		}

		inviteToken := strings.TrimSpace(r.FormValue("invite_token"))
		password := r.FormValue("password")
		confirm := r.FormValue("confirm")

		if inviteToken == "" || password == "" {
			renderErr("All fields are required.")
			return
		}
		if password != confirm {
			renderErr("Passwords do not match.")
			return
		}
		if len(password) < 8 {
			renderErr("Password must be at least 8 characters.")
			return
		}

		inv, err := getInvite(s.db, inviteToken)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		if inv == nil || inv.UsedAt.Valid {
			renderErr("Invalid or already-used invite token.")
			return
		}

		hash, err := bcrypt.GenerateFromPassword([]byte(password), 12)
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		user, err := getUserByUsername(s.db, inv.Username)
		if err != nil || user == nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		if _, err := s.db.Exec(`UPDATE users SET password_hash = ? WHERE id = ?`, string(hash), user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		if err := useInvite(s.db, inviteToken); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		if err := s.setSessionCookie(w, user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/user/my-recordings", http.StatusSeeOther)
	})
}

// POST /connect/:install_id/login
// authenticateUser looks up a user by username and verifies their password.
// Returns nil, nil if the credentials are wrong (not an error).
func (s *Server) authenticateUser(username, password string) (*User, error) {
	user, err := getUserByUsername(s.db, username)
	if err != nil {
		return nil, err
	}
	if user == nil || !user.PasswordHash.Valid {
		return nil, nil
	}
	if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash.String), []byte(password)); err != nil {
		return nil, nil
	}
	return user, nil
}

// loginErrorMessage returns a user-facing error for a failed login.
// If the username has a pending invite (password was reset), it returns a
// more specific message instead of the generic "invalid credentials".
func (s *Server) loginErrorMessage(username string) string {
	pending, err := hasPendingInvite(s.db, username)
	if err == nil && pending {
		return "Your password has been reset. Ask your admin for a new invite token."
	}
	return "Invalid username or password."
}

func (s *Server) handleConnectLogin() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		installID := r.PathValue("install_id")
		r.ParseForm()

		pt := resolveTheme(r)
		renderErr := func(msg string) {
			w.Header().Set("Content-Type", "text/html; charset=utf-8")
			w.WriteHeader(http.StatusUnprocessableEntity)
			connectTmpl.Execute(w, connectData{pageTheme: pt, AppTitle: s.cfg.AppTitle, InstallID: installID, Error: msg})
		}

		username := strings.TrimSpace(r.FormValue("username"))
		user, err := s.authenticateUser(username, r.FormValue("password"))
		if err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		if user == nil {
			renderErr(s.loginErrorMessage(username))
			return
		}

		if err := linkCLIToUser(s.db, installID, user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}

		if err := s.setSessionCookie(w, user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/connect/"+url.PathEscape(installID)+"?linked=1", http.StatusSeeOther)
	})
}

// POST /connect/:install_id/link  (already logged in)
func (s *Server) handleConnectLink() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		installID := r.PathValue("install_id")
		user, err := s.sessionUser(r)
		if err != nil || user == nil {
			http.Redirect(w, r, "/connect/"+url.PathEscape(installID), http.StatusSeeOther)
			return
		}
		if err := linkCLIToUser(s.db, installID, user.ID); err != nil {
			http.Error(w, "Server error", http.StatusInternalServerError)
			return
		}
		http.Redirect(w, r, "/connect/"+url.PathEscape(installID)+"?linked=1", http.StatusSeeOther)
	})
}

// POST /logout
func (s *Server) handleLogout() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		s.clearSessionCookie(w, r)
		http.Redirect(w, r, "/", http.StatusSeeOther)
	})
}

// ---------------------------------------------------------------------------
// Utilities
// ---------------------------------------------------------------------------

func formatDuration(secs float64) string {
	total := int(secs)
	m := total / 60
	s := total % 60
	return fmt.Sprintf("%dm %02ds", m, s)
}

func randomToken(n int) string {
	b := make([]byte, n)
	rand.Read(b)
	return fmt.Sprintf("%x", b)[:n]
}

func jsonError(w http.ResponseWriter, msg string, code int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(code)
	json.NewEncoder(w).Encode(map[string]string{"error": msg})
}

func pathID(r *http.Request) (int64, error) {
	return strconv.ParseInt(r.PathValue("id"), 10, 64)
}

func nullString(s sql.NullString) any {
	if s.Valid {
		return s.String
	}
	return nil
}

func nullInt64(n sql.NullInt64) any {
	if n.Valid {
		return n.Int64
	}
	return nil
}

func nullFloat64(f sql.NullFloat64) any {
	if f.Valid {
		return f.Float64
	}
	return nil
}

// cliFromRequest retrieves the authenticated CLI from the request context.
func cliFromRequest(r *http.Request) *CLI {
	v := r.Context().Value(ctxCLI)
	if v == nil {
		return nil
	}
	return v.(*CLI)
}

// embedDimensions computes pixel width/height for the embed iframe based on
// the recorded terminal size using asciinema's default font metrics.
func embedDimensions(cols, rows int) (width, height int) {
	const charW, charH, barH, pad = 7, 14, 32, 20
	width = cols*charW + pad
	height = rows*charH + barH + pad
	if width > 1200 {
		width = 1200
	}
	if height > 800 {
		height = 800
	}
	return
}

// ---------------------------------------------------------------------------
// Themes overview page
// ---------------------------------------------------------------------------

var themesTmpl = template.Must(template.New("themes").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Themes — {{.AppTitle}}</title>
  <link rel="stylesheet" href="/static/asciinema-player.css">
  <style>` + themeCSS + commonCSS + `
    body { max-width: 900px; margin: 2rem auto; padding: 0 1rem; }
    h1 { margin-bottom: 2rem; }
    .themes { display: grid; grid-template-columns: repeat(auto-fill, minmax(380px, 1fr)); gap: 1.5rem; }
    .theme-card { border-radius: 6px; overflow: hidden; border: 1px solid color-mix(in oklab, var(--fg) 20%, var(--bg)); }
    .theme-header { padding: .5rem .8rem; display: flex; justify-content: space-between; align-items: baseline; font-size: .9rem; }
    .theme-name { font-weight: bold; }
    .theme-mode { font-size: .75rem; opacity: .6; }
    .palette { display: flex; height: 28px; }
    .palette-swatch { flex: 1; }
    .term-preview { padding: .75rem 1rem; font-family: "Cascadia Code", "Source Code Pro", Menlo, Consolas, monospace; font-size: .8rem; line-height: 1.5; }
    .term-preview span { display: inline-block; padding: 0 .15em; }
  </style>
</head>
<body>
  <div id="top-bar">
` + themeBar + `
  </div>
  <h1>Themes</h1>
  <div class="themes">
  {{range .AllThemes}}
  <div class="theme-card asciinema-player-theme-{{.ID}}">
    <div class="theme-header" style="background:var(--term-color-background);color:var(--term-color-foreground)">
      <span class="theme-name">{{.Label}}</span>
      <span class="theme-mode">{{if .Dark}}dark{{else}}light{{end}}</span>
    </div>
    <div class="palette" style="background:var(--term-color-background)">
      <div class="palette-swatch" style="background:var(--term-color-0)"></div>
      <div class="palette-swatch" style="background:var(--term-color-1)"></div>
      <div class="palette-swatch" style="background:var(--term-color-2)"></div>
      <div class="palette-swatch" style="background:var(--term-color-3)"></div>
      <div class="palette-swatch" style="background:var(--term-color-4)"></div>
      <div class="palette-swatch" style="background:var(--term-color-5)"></div>
      <div class="palette-swatch" style="background:var(--term-color-6)"></div>
      <div class="palette-swatch" style="background:var(--term-color-7)"></div>
      <div class="palette-swatch" style="background:var(--term-color-8)"></div>
      <div class="palette-swatch" style="background:var(--term-color-9)"></div>
      <div class="palette-swatch" style="background:var(--term-color-10)"></div>
      <div class="palette-swatch" style="background:var(--term-color-11)"></div>
      <div class="palette-swatch" style="background:var(--term-color-12)"></div>
      <div class="palette-swatch" style="background:var(--term-color-13)"></div>
      <div class="palette-swatch" style="background:var(--term-color-14)"></div>
      <div class="palette-swatch" style="background:var(--term-color-15)"></div>
    </div>
    <div class="term-preview" style="background:var(--term-color-background);color:var(--term-color-foreground)">
      <span style="color:var(--term-color-2)">user</span><span style="color:var(--term-color-foreground)">@</span><span style="color:var(--term-color-4)">host</span><span style="color:var(--term-color-foreground)"> ~ $ </span><span style="color:var(--term-color-3)">ls -la</span><br>
      <span style="color:var(--term-color-4)">drwxr-xr-x</span><span style="color:var(--term-color-foreground)">  documents/</span><br>
      <span style="color:var(--term-color-1)">error:</span><span style="color:var(--term-color-foreground)"> file not found</span><br>
      <span style="color:var(--term-color-5)">function</span><span style="color:var(--term-color-foreground)"> hello() {</span> <span style="color:var(--term-color-8)">// comment</span>
    </div>
  </div>
  {{end}}
  </div>
</body>
</html>
`))

type themesData struct {
	pageTheme
	AppTitle  string
	AllThemes []themeInfo
}

// GET /themes
func (s *Server) handleThemesOverview() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		themesTmpl.Execute(w, themesData{
			pageTheme: resolveTheme(r),
			AppTitle:  s.cfg.AppTitle,
			AllThemes: themes,
		})
	})
}

// ---------------------------------------------------------------------------
// Recording embed page (for Mastodon/Twitter player cards)
// ---------------------------------------------------------------------------

type embedData struct {
	CastSrc      template.JS
	TermCols     int
	TermRows     int
	DarkID       string
	LightID      string
	AutoDarkBg   string
	AutoDarkFg   string
	AutoDarkRed  string
	AutoLightBg  string
	AutoLightFg  string
	AutoLightRed string
}

var embedTmpl = template.Must(template.New("embed").Parse(`<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="/static/asciinema-player.css">
  <style>
    :root { --bg: {{.AutoDarkBg}}; --fg: {{.AutoDarkFg}}; }
    @media (prefers-color-scheme: light) {
      :root { --bg: {{.AutoLightBg}}; --fg: {{.AutoLightFg}}; }
    }
    html, body { height: 100%; margin: 0; overflow: hidden; background: var(--bg); }
    #player { width: 100%; height: 100%; }
  </style>
</head>
<body>
  <div id="player"></div>
  <script src="/static/asciinema-player.min.js"></script>
  <script>
    (function() {
      var src  = {{.CastSrc}};
      var el   = document.getElementById('player');
      var darkID  = '{{.DarkID}}';
      var lightID = '{{.LightID}}';

      function create(themeID) {
        el.innerHTML = '';
        AsciinemaPlayer.create(src, el, {
          autoPlay: true,
          fit: 'both',
          theme: themeID,
          cols: {{.TermCols}},
          rows: {{.TermRows}},
        });
      }

      var mq = window.matchMedia('(prefers-color-scheme: dark)');
      create(mq.matches ? darkID : lightID);

      // Recreate player if OS mode changes while embed is open.
      mq.addEventListener('change', function(e) {
        create(e.matches ? darkID : lightID);
      });
    })();
  </script>
</body>
</html>
`))

// drawLine draws a 2px-wide line between two points using Bresenham's algorithm.

func abs(x int) int {
	if x < 0 {
		return -x
	}
	return x
}

// parseHexColor parses a "#rrggbb" hex color string into an image/color.RGBA.
func parseHexColor(s string) color.RGBA {
	s = strings.TrimPrefix(s, "#")
	if len(s) != 6 {
		return color.RGBA{R: 0xcc, G: 0xcc, B: 0xcc, A: 0xff}
	}
	var r, g, b uint8
	fmt.Sscanf(s[:2], "%02x", &r)
	fmt.Sscanf(s[2:4], "%02x", &g)
	fmt.Sscanf(s[4:6], "%02x", &b)
	return color.RGBA{R: r, G: g, B: b, A: 0xff}
}

// blendColor pre-blends fg onto bg at the given opacity (0–255), returning a
// fully opaque color. This avoids the blue fringe artifact from font
// antialiasing when compositing semi-transparent colors onto a background.
func blendColor(fg, bg color.RGBA, alpha uint8) color.RGBA {
	a := float64(alpha) / 255.0
	return color.RGBA{
		R: uint8(float64(fg.R)*a + float64(bg.R)*(1-a)),
		G: uint8(float64(fg.G)*a + float64(bg.G)*(1-a)),
		B: uint8(float64(fg.B)*a + float64(bg.B)*(1-a)),
		A: 0xff,
	}
}

// ---------------------------------------------------------------------------
// Terminal cast playback (avt-go integration)
// ---------------------------------------------------------------------------

// castPlayback plays back a .cast file up to targetSecs and returns the
// terminal view (visible rows) and the terminal dimensions.
// castData is the raw (uncompressed) .cast bytes.
func castPlayback(castData []byte, targetSecs float64) ([]*types.Line, int, int) {
	dec := json.NewDecoder(bytes.NewReader(castData))

	// Parse header.
	var header map[string]any
	if err := dec.Decode(&header); err != nil {
		return nil, 80, 24
	}
	cols := int(jsonFloat(header, "width"))
	rows := int(jsonFloat(header, "height"))
	if cols <= 0 {
		cols = 80
	}
	if rows <= 0 {
		rows = 24
	}

	vt := avt.New(cols, rows)

	// Feed output events up to targetSecs.
	for {
		var event []any
		if err := dec.Decode(&event); err != nil {
			break // EOF or non-JSON line
		}
		if len(event) < 3 {
			continue
		}
		ts, ok := event[0].(float64)
		if !ok {
			continue
		}
		if ts > targetSecs {
			break
		}
		evType, ok := event[1].(string)
		if !ok || evType != "o" {
			continue
		}
		data, ok := event[2].(string)
		if !ok {
			continue
		}
		vt.FeedStr(data)
	}

	return vt.View(), cols, rows
}

// parseDuration parses a duration string with sub-second resolution for the
// ?time= query parameter. Accepts Go duration strings like "1m5s500ms" or
// plain seconds as a float like "65.5".
func parseDuration(s string) (float64, error) {
	if s == "" {
		return -1, nil // sentinel: use end of recording
	}
	// Try Go duration syntax first (handles "1m5s", "500ms", "1h2m3s4ms", etc.)
	d, err := time.ParseDuration(s)
	if err == nil {
		return d.Seconds(), nil
	}
	// Fall back to plain float seconds.
	f, err := strconv.ParseFloat(s, 64)
	if err != nil {
		return 0, fmt.Errorf("invalid time %q: use Go duration syntax like '1m5s500ms' or plain seconds", s)
	}
	return f, nil
}

// xterm256Color returns the standard xterm-256 color for index n (0–255).
// Indices 0–15 are the ANSI colors (handled separately via theme), so this
// is mainly for 16–255.
func xterm256Color(n uint8) color.RGBA {
	if n < 16 {
		// Shouldn't be called for 0-15, but handle gracefully.
		return color.RGBA{0x80, 0x80, 0x80, 0xff}
	}
	if n >= 232 {
		// Grayscale ramp: 232=0x08, 253=0xee, step=10
		v := uint8(8 + 10*(int(n)-232))
		return color.RGBA{v, v, v, 0xff}
	}
	// 6×6×6 color cube
	idx := int(n) - 16
	b := idx % 6
	g := (idx / 6) % 6
	r := idx / 36
	cube := [6]uint8{0, 95, 135, 175, 215, 255}
	return color.RGBA{cube[r], cube[g], cube[b], 0xff}
}

// resolveColor resolves a terminal Color (possibly nil) to an RGBA using the
// theme palette. isFg=true means "nil → theme foreground", isFg=false means
// "nil → theme background".
func resolveColor(c types.Color, theme themeInfo, isFg bool) color.RGBA {
	if c == nil {
		if isFg {
			return parseHexColor(theme.Foreground)
		}
		return parseHexColor(theme.Background)
	}
	switch v := c.(type) {
	case types.ColorIndexed:
		if v.N < 16 {
			return parseHexColor(theme.Color[v.N])
		}
		return xterm256Color(v.N)
	case types.ColorRGB:
		return color.RGBA{v.R, v.G, v.B, 0xff}
	}
	if isFg {
		return parseHexColor(theme.Foreground)
	}
	return parseHexColor(theme.Background)
}

// GET /a/{token}/preview.png — PNG preview image for Mastodon og:image.
// Mastodon rejects SVG, so we render the same design as a PNG using gomono font.
//
// Query params:
//   - type=cover (default) — info card with title/duration/dimensions
//   - type=preview         — full terminal grid render at the given time
//   - time=<duration>      — timestamp for preview mode; Go duration syntax
//     e.g. "1m5s500ms" or plain seconds "65.5"; default = end of recording
func (s *Server) handleRecordingPreviewPNG() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := r.PathValue("token")
		a, err := getAsciicastBySecretToken(s.db, token)
		if err != nil || a == nil {
			http.NotFound(w, r)
			return
		}

		darkID, lightID := resolveEmbedThemes(r, s.db, a.UserID)
		// Pick dark or light based on the request — default to dark.
		// (no prefers-color-scheme in PNG; owner's dark theme is the canonical preview)
		_ = lightID
		theme := themesByID[darkID]

		title := "recording"
		if a.Title.Valid && a.Title.String != "" {
			title = a.Title.String
		}

		previewType := r.URL.Query().Get("type")
		if previewType == "" {
			previewType = "cover"
		}

		var img *image.RGBA
		var disposition string
		safeTitle := strings.ReplaceAll(title, "/", "")
		switch previewType {
		case "preview":
			// Parse ?time= query param.
			targetSecs, err := parseDuration(r.URL.Query().Get("time"))
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			if targetSecs < 0 {
				targetSecs = a.Duration // default: end of recording
			}

			// Load and decompress cast data.
			castData, err := s.readCastBlob(a.ID)
			if err != nil {
				http.Error(w, "Server error", http.StatusInternalServerError)
				return
			}

			lines, cols, rows := castPlayback(castData, targetSecs)
			img = renderTerminalPNG(lines, cols, rows, theme)
			timeStr := r.URL.Query().Get("time")
			if timeStr == "" {
				timeStr = formatDuration(a.Duration)
			}
			disposition = safeTitle + " (Preview at " + timeStr + ").png"

		default: // "cover"
			img, err = renderCoverPNG(a, title, theme, s.cfg.AppTitle)
			if err != nil {
				http.Error(w, "render error", http.StatusInternalServerError)
				return
			}
			disposition = safeTitle + " (Cover).png"
		}

		var buf bytes.Buffer
		if err := png.Encode(&buf, img); err != nil {
			http.Error(w, "render error", http.StatusInternalServerError)
			return
		}
		data := buf.Bytes()

		etag := fmt.Sprintf(`"%x"`, md5.Sum(data))
		w.Header().Set("ETag", etag)
		w.Header().Set("Cache-Control", "no-cache")
		w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename*=UTF-8''%s`, url.PathEscape(disposition)))
		if r.Header.Get("If-None-Match") == etag {
			w.WriteHeader(http.StatusNotModified)
			return
		}
		w.Header().Set("Content-Type", "image/png")
		w.Write(data)
	})
}

// renderCoverPNG renders the existing info-card style PNG preview.
func renderCoverPNG(a *Asciicast, title string, theme themeInfo, appTitle string) (*image.RGBA, error) {
	dur := formatDuration(a.Duration)

	bg := parseHexColor(theme.Background)
	fg := parseHexColor(theme.Foreground)
	red := parseHexColor(theme.Red)
	grn := parseHexColor(theme.Green)
	yel := parseHexColor(theme.Yellow)

	const W, H = 1200, 675
	img := image.NewRGBA(image.Rect(0, 0, W, H))

	// Fill background.
	draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)

	// Text rendering setup.
	face, err := opentype.NewFace(gomonoBoldFont, &opentype.FaceOptions{Size: 36, DPI: 96})
	if err != nil {
		return nil, err
	}
	defer face.Close()
	d := &font.Drawer{Dst: img, Face: face}

	drawText := func(x, y int, c color.RGBA, text string) int {
		d.Dot = fixed.P(x, y)
		d.Src = &image.Uniform{c}
		d.DrawString(text)
		return int(d.Dot.X.Ceil())
	}
	measureText := func(text string) int {
		return int(d.MeasureString(text).Ceil())
	}

	// Header strip — height derived from font metrics so the title always fits.
	hMetrics := face.Metrics()
	hAscent := int(hMetrics.Ascent.Ceil())
	hDescent := int(hMetrics.Descent.Ceil())
	headerH := (hAscent + hDescent) * 12 / 10
	draw.Draw(img, image.Rect(0, 0, W, headerH), &image.Uniform{bg}, image.Point{}, draw.Src)

	// AppTitle centered in header — baseline at vertical center + ascent.
	titleW := measureText(appTitle)
	titleY := (headerH-hAscent-hDescent)/2 + hAscent
	drawText((W-titleW)/2, titleY, fg, appTitle)

	// Draw X close button — two diagonal lines via Bresenham.
	xCol := blendColor(fg, bg, 120)
	xCx, xCy, xR := W-36, headerH/2, 7
	bresenham := func(x0, y0, x1, y1 int, c color.RGBA) {
		dx, dy := abs(x1-x0), abs(y1-y0)
		sx, sy := 1, 1
		if x0 > x1 {
			sx = -1
		}
		if y0 > y1 {
			sy = -1
		}
		bErr := dx - dy
		for {
			img.SetRGBA(x0, y0, c)
			if x0 == x1 && y0 == y1 {
				break
			}
			e2 := 2 * bErr
			if e2 > -dy {
				bErr -= dy
				x0 += sx
			}
			if e2 < dx {
				bErr += dx
				y0 += sy
			}
		}
	}
	bresenham(xCx-xR, xCy-xR, xCx+xR, xCy+xR, xCol)
	bresenham(xCx+xR, xCy-xR, xCx-xR, xCy+xR, xCol)

	// Separator line below header.
	draw.Draw(img, image.Rect(0, headerH, W, headerH+1), &image.Uniform{blendColor(fg, bg, 60)}, image.Point{}, draw.Src)

	// Line height derived from font metrics with 20% leading, same as terminal renderer.
	fMetrics := face.Metrics()
	lineH := (int(fMetrics.Ascent.Ceil()) + int(fMetrics.Descent.Ceil())) * 12 / 10
	// 4 lines total (1 + 1 + blank + 1 + 1), content block height ≈ lineH*5.
	// Center it vertically in the area below the header.
	contentH := lineH * 5
	y := headerH + (H-headerH-contentH)/2 + int(fMetrics.Ascent.Ceil())

	dim := blendColor(fg, bg, 140)
	dimmer := blendColor(fg, bg, 100)

	// Line 1: > play "title"
	x := drawText(60, y, dim, "> play ")
	drawText(x, y, red, `"`+title+`"`)
	y += lineH

	// Line 2: playing terminal recording (dimmed)
	drawText(60, y, dimmer, "playing terminal recording")
	y += lineH * 2

	// Line 3: dimensions
	x = drawText(60, y, dim, "dimensions: ")
	x = drawText(x, y, grn, fmt.Sprintf("%d cols", a.TermCols))
	x = drawText(x, y, dim, " x ")
	drawText(x, y, grn, fmt.Sprintf("%d rows", a.TermRows))
	y += lineH

	// Line 4: duration
	x = drawText(60, y, dim, "duration:   ")
	drawText(x, y, yel, dur)

	return img, nil
}

// cellGeometry holds the pre-computed metrics needed to paint terminal cells.
type cellGeometry struct {
	padX, padY   int
	cellW, cellH int
	ascent       int
	face         font.Face
}

// usedDimensions computes the bounding box of non-default cells, ignoring
// trailing whitespace. Returns at least (1, 1).
func usedDimensions(lines []*types.Line) (usedCols, usedRows int) {
	usedCols = 1
	usedRows = 0
	for r, line := range lines {
		for c := len(line.Cells) - 1; c >= 0; c-- {
			if !line.Cells[c].IsDefault() {
				if c+1 > usedCols {
					usedCols = c + 1
				}
				if r+1 > usedRows {
					usedRows = r + 1
				}
				break
			}
		}
	}
	if usedRows == 0 {
		usedRows = 1
	}
	return
}

// paintTerminal draws terminal cells into img using geom for layout.
// It stops early once pixel coordinates exceed the image bounds.
func paintTerminal(img *image.RGBA, geom cellGeometry, lines []*types.Line, usedCols, usedRows int, theme themeInfo) {
	bounds := img.Bounds()
	d := &font.Drawer{Dst: img, Face: geom.face}
	glyphOffX := 0 // cellW == advPx always, so offset is 0

	for row, line := range lines {
		if row >= usedRows {
			break
		}
		py := geom.padY + row*geom.cellH
		if py >= bounds.Max.Y {
			break
		}
		col := 0
		for i := 0; i < len(line.Cells); i++ {
			cell := line.Cells[i]
			if col >= usedCols {
				break
			}
			px := geom.padX + col*geom.cellW
			if px >= bounds.Max.X {
				break
			}

			pen := cell.Pen()
			cellBg := resolveColor(pen.Background, theme, false)
			cellFg := resolveColor(pen.Foreground, theme, true)

			if pen.IsInverse() {
				cellBg, cellFg = cellFg, cellBg
			}
			if pen.IsFaint() {
				cellFg = blendColor(cellFg, cellBg, 140)
			}

			cellCols := 1
			if cell.Occupancy() == types.OccupancyWideHead {
				cellCols = 2
			} else if cell.Occupancy() == types.OccupancyWideTail {
				col++
				continue
			}

			cellPxW := geom.cellW * cellCols

			if pen.Background != nil || pen.IsInverse() {
				draw.Draw(img, image.Rect(px, py, px+cellPxW, py+geom.cellH), &image.Uniform{cellBg}, image.Point{}, draw.Src)
			}

			ch := cell.Char()
			if ch != ' ' && ch != 0 {
				textX := px + glyphOffX
				if cellCols == 2 {
					wideAdv := int(d.MeasureString(string(ch)).Ceil())
					textX = px + (cellPxW-wideAdv)/2
					if textX < px {
						textX = px
					}
				}
				d.Dot = fixed.P(textX, py+geom.ascent)
				d.Src = &image.Uniform{cellFg}
				d.DrawString(string(ch))
			}

			col += cellCols
		}
	}
}

// newCellGeometry creates a cellGeometry for the given font size and padding.
// The caller is responsible for closing geom.face when done.
func newCellGeometry(fontSize float64, padX, padY int) (cellGeometry, error) {
	face, err := opentype.NewFace(gomonoBoldFont, &opentype.FaceOptions{Size: fontSize, DPI: 72})
	if err != nil {
		return cellGeometry{}, err
	}
	d := &font.Drawer{Face: face}
	advPx := int(d.MeasureString("M").Ceil())
	m := face.Metrics()
	ascent := int(m.Ascent.Ceil())
	descent := int(m.Descent.Ceil())
	return cellGeometry{
		padX:   padX,
		padY:   padY,
		cellW:  advPx,
		cellH:  (ascent + descent) * 12 / 10,
		ascent: ascent,
		face:   face,
	}, nil
}

// renderTerminalPNG renders a full terminal grid as a 1200×675 PNG image,
// fitting the font size to the used content area.
func renderTerminalPNG(lines []*types.Line, cols, rows int, theme themeInfo) *image.RGBA {
	const W, H = 1200, 675
	const padX, padY = 20, 20
	const minFontSize, maxFontSize = 14.0, 32.0

	availW := W - 2*padX
	availH := H - 2*padY

	usedCols, usedRows := usedDimensions(lines)

	// Find the largest font size that fits usedCols×usedRows into availW×availH.
	fitFontSize := func(maxPx int, count int, measureFn func(font.Face) int) float64 {
		for fontSize := maxFontSize; fontSize >= minFontSize; fontSize -= 0.5 {
			f, err := opentype.NewFace(gomonoBoldFont, &opentype.FaceOptions{Size: fontSize, DPI: 72})
			if err != nil {
				break
			}
			px := measureFn(f)
			f.Close()
			if px*count <= maxPx {
				return fontSize
			}
		}
		return minFontSize
	}

	fontSizeW := fitFontSize(availW, usedCols, func(f font.Face) int {
		return int((&font.Drawer{Face: f}).MeasureString("M").Ceil())
	})
	fontSizeH := fitFontSize(availH, usedRows, func(f font.Face) int {
		m := f.Metrics()
		return (int(m.Ascent.Ceil()) + int(m.Descent.Ceil())) * 12 / 10
	})

	fontSize := fontSizeW
	if fontSizeH < fontSize {
		fontSize = fontSizeH
	}

	bg := parseHexColor(theme.Background)
	img := image.NewRGBA(image.Rect(0, 0, W, H))
	draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)

	geom, err := newCellGeometry(fontSize, padX, padY)
	if err != nil {
		return img
	}
	defer geom.face.Close()

	paintTerminal(img, geom, lines, usedCols, usedRows, theme)
	return img
}

// renderStreamPreviewPNG renders a terminal snapshot at a fixed font size,
// sizing the image to exactly fit the used content (trimming trailing whitespace).
func renderStreamPreviewPNG(lines []*types.Line, theme themeInfo) *image.RGBA {
	const fontSize = 14.0
	const padX, padY = 12, 12

	usedCols, usedRows := usedDimensions(lines)

	geom, err := newCellGeometry(fontSize, padX, padY)
	if err != nil {
		// Fallback: 1×1 blank image
		return image.NewRGBA(image.Rect(0, 0, 1, 1))
	}
	defer geom.face.Close()

	W := padX*2 + usedCols*geom.cellW
	H := padY*2 + usedRows*geom.cellH

	bg := parseHexColor(theme.Background)
	img := image.NewRGBA(image.Rect(0, 0, W, H))
	draw.Draw(img, img.Bounds(), &image.Uniform{bg}, image.Point{}, draw.Src)

	paintTerminal(img, geom, lines, usedCols, usedRows, theme)
	return img
}

// GET /a/{token}/preview.svg — stylized terminal SVG for og:image social previews.
func (s *Server) handleRecordingPreview() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := r.PathValue("token")
		a, err := getAsciicastBySecretToken(s.db, token)
		if err != nil || a == nil {
			http.NotFound(w, r)
			return
		}

		darkID, lightID := resolveEmbedThemes(r, s.db, a.UserID)
		dark := themesByID[darkID]
		light := themesByID[lightID]

		title := "recording"
		if a.Title.Valid && a.Title.String != "" {
			title = a.Title.String
		}

		dur := formatDuration(a.Duration)
		cols := a.TermCols
		rows := a.TermRows

		svgEsc := strings.NewReplacer("&", "&amp;", "<", "&lt;", ">", "&gt;", `"`, "&quot;")
		titleEsc := svgEsc.Replace(title)
		appTitleEsc := svgEsc.Replace(s.cfg.AppTitle)

		svg := fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="675" viewBox="0 0 1200 675">
  <defs>
    <style>
      .bg     { fill: %s } .fg  { fill: %s } .red { fill: %s }
      .grn    { fill: %s } .yel { fill: %s } .blu { fill: %s }
      .border { stroke: %s; stroke-opacity: 0.5 }
      @media (prefers-color-scheme: light) {
        .bg     { fill: %s } .fg  { fill: %s } .red { fill: %s }
        .grn    { fill: %s } .yel { fill: %s } .blu { fill: %s }
        .border { stroke: %s }
      }
    </style>
  </defs>
  <!-- background -->
  <rect width="1200" height="675" class="bg"/>
  <!-- clip path for the box interior -->
  <clipPath id="box-clip">
    <rect x="60" y="60" width="1080" height="555" rx="14" ry="14"/>
  </clipPath>
  <!-- box background fill -->
  <rect x="60" y="60" width="1080" height="555" rx="14" ry="14" class="bg"/>
  <!-- header strip clipped to box -->
  <rect x="60" y="60" width="1080" height="48" class="bg" clip-path="url(#box-clip)"/>
  <!-- title in header using fg color -->
  <text x="600" y="92" font-family="monospace" font-size="16" text-anchor="middle" class="fg">%s</text>
  <!-- close button -->
  <text x="1108" y="92" font-family="monospace" font-size="16" text-anchor="middle" class="fg" opacity="0.6">✕</text>
  <!-- border drawn last so it cleanly frames everything -->
  <rect x="60" y="60" width="1080" height="555" rx="14" ry="14" fill="none" class="border" stroke-width="2"/>
  <!-- content -->
  <text x="120" y="247" font-family="monospace" font-size="24">
    <tspan class="fg" opacity="0.5">▶ play </tspan><tspan class="red">&quot;%s&quot;</tspan>
  </text>
  <text x="120" y="302" font-family="monospace" font-size="24" class="fg" opacity="0.35">playing terminal recording</text>
  <text x="120" y="392" font-family="monospace" font-size="24">
    <tspan class="fg" opacity="0.5">dimensions: </tspan><tspan class="grn">%d cols</tspan><tspan class="fg" opacity="0.5"> × </tspan><tspan class="grn">%d rows</tspan>
  </text>
  <text x="120" y="457" font-family="monospace" font-size="24">
    <tspan class="fg" opacity="0.5">duration:   </tspan><tspan class="yel">%s</tspan>
  </text>
</svg>`,
			// dark
			dark.Background, dark.Foreground, dark.Red,
			dark.Green, dark.Yellow, dark.Blue,
			dark.Foreground,
			// light overrides
			light.Background, light.Foreground, light.Red,
			light.Green, light.Yellow, light.Blue,
			light.Foreground,
			// content: header shows appTitle, body shows recording title
			appTitleEsc, titleEsc,
			cols, rows,
			dur,
		)

		etag := fmt.Sprintf(`"%x"`, md5.Sum([]byte(svg)))
		w.Header().Set("ETag", etag)
		w.Header().Set("Cache-Control", "no-cache")
		safeTitle := strings.ReplaceAll(title, "/", "")
		w.Header().Set("Content-Disposition", fmt.Sprintf(`inline; filename*=UTF-8''%s`, url.PathEscape(safeTitle+" (Preview).svg")))
		if r.Header.Get("If-None-Match") == etag {
			w.WriteHeader(http.StatusNotModified)
			return
		}
		w.Header().Set("Content-Type", "image/svg+xml")
		w.Write([]byte(svg))
	})
}

// GET /a/{token}/embed — bare player page for use in Mastodon/Twitter iframes.
func (s *Server) handleRecordingEmbed() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		token := r.PathValue("token")
		a, err := getAsciicastBySecretToken(s.db, token)
		if err != nil || a == nil {
			http.NotFound(w, r)
			return
		}

		// Theme resolution: query params → owner's DB preferences → defaults.
		// Viewer cookies are not used — third-party cookie partitioning means
		// they are never sent in cross-origin iframes anyway.
		darkID, lightID := resolveEmbedThemes(r, s.db, a.UserID)
		if themesByID[lightID].ID == "" {
			lightID = defaultLightThemeID
		}

		dark := themesByID[darkID]
		light := themesByID[lightID]

		src, _ := json.Marshal("/a/" + a.SecretToken + ".cast")

		// No X-Frame-Options — this page must be embeddable in third-party iframes.
		w.Header().Set("Content-Security-Policy", "frame-ancestors *")
		w.Header().Set("Content-Type", "text/html; charset=utf-8")
		embedTmpl.Execute(w, embedData{
			CastSrc:      template.JS(src),
			TermCols:     a.TermCols,
			TermRows:     a.TermRows,
			DarkID:       darkID,
			LightID:      lightID,
			AutoDarkBg:   dark.Background,
			AutoDarkFg:   dark.Foreground,
			AutoDarkRed:  dark.Red,
			AutoLightBg:  light.Background,
			AutoLightFg:  light.Foreground,
			AutoLightRed: light.Red,
		})
	})
}

// ---------------------------------------------------------------------------
// Router
// ---------------------------------------------------------------------------

func (s *Server) routes() http.Handler {
	mux := http.NewServeMux()

	// Root + login
	mux.Handle("/", s.handleRoot())
	mux.Handle("GET /login", s.handleLoginShow())
	mux.Handle("POST /login", s.handleLoginSubmit())
	mux.Handle("POST /reset-password", s.handlePasswordReset())

	// Static assets (embedded)
	serveStatic := func(data []byte, contentType string) http.HandlerFunc {
		etag := fmt.Sprintf(`"%x"`, md5.Sum(data))
		return func(w http.ResponseWriter, r *http.Request) {
			w.Header().Set("ETag", etag)
			w.Header().Set("Cache-Control", "no-cache")
			if r.Header.Get("If-None-Match") == etag {
				w.WriteHeader(http.StatusNotModified)
				return
			}
			w.Header().Set("Content-Type", contentType)
			w.Write(data)
		}
	}
	mux.HandleFunc("GET /static/asciinema-player.css", serveStatic(staticPlayerCSS, "text/css; charset=utf-8"))
	mux.HandleFunc("GET /static/asciinema-player.min.js", serveStatic(staticPlayerJS, "application/javascript; charset=utf-8"))
	mux.HandleFunc("GET /static/live-player.js", serveStatic(staticLivePlayerJS, "application/javascript; charset=utf-8"))
	mux.HandleFunc("GET /static/vt_js.js", serveStatic(staticVtJS, "application/javascript; charset=utf-8"))
	mux.HandleFunc("GET /static/vt_js_bg.wasm", serveStatic(staticVtWasm, "application/wasm"))

	// Theme overview
	mux.Handle("GET /themes", s.handleThemesOverview())

	// Recording playback (browser + raw cast download)
	mux.Handle("/a/", s.handleRecordingShow())
	// Embed page for Mastodon/Twitter player cards
	mux.Handle("GET /a/{token}/embed", s.handleRecordingEmbed())
	// SVG preview image for og:image social previews
	mux.Handle("GET /a/{token}/preview.svg", s.handleRecordingPreview())
	mux.Handle("GET /a/{token}/preview.png", s.handleRecordingPreviewPNG())

	// Recording management (browser/session auth)
	mux.Handle("GET /user/my-recordings", s.handleUserRecordingsList())
	mux.Handle("POST /recordings/{token}/delete", s.handleRecordingBrowserDelete())
	mux.Handle("POST /recordings/{token}/rename", s.handleRecordingBrowserRename())
	mux.Handle("POST /user/delete-account", s.handleUserDeleteAccount())

	// CLI linking / registration
	mux.Handle("GET /connect/{install_id}", s.handleConnectShow())
	mux.Handle("POST /connect/{install_id}/register", s.handleConnectRegister())
	mux.Handle("POST /connect/{install_id}/login", s.handleConnectLogin())
	mux.Handle("POST /connect/{install_id}/link", s.handleConnectLink())
	mux.Handle("POST /logout", s.handleLogout())

	// API v1 — recordings
	mux.Handle("POST /api/v1/recordings", s.handleRecordingCreate())
	mux.Handle("PATCH /api/v1/recordings/{id}", s.handleRecordingUpdate())
	mux.Handle("DELETE /api/v1/recordings/{id}", s.handleRecordingDelete())

	// API v1 — live streams
	mux.Handle("POST /api/v1/streams", s.handleStreamCreate())
	mux.Handle("PATCH /api/v1/streams/{id}", s.handleStreamUpdate())
	mux.Handle("GET /api/v1/user/streams", s.handleUserStreamsList())
	mux.Handle("POST /streams/{public_token}/rename", s.handleStreamBrowserRename())
	mux.Handle("POST /streams/{public_token}/delete", s.handleStreamBrowserDelete())

	// Live stream WebSocket endpoints
	mux.Handle("GET /ws/S/{producer_token}", s.handleProducerWS())
	mux.Handle("GET /ws/s/{public_token}", s.handleConsumerWS())

	// Live stream player page + snapshot
	mux.Handle("GET /s/{public_token}/current.png", s.handleLiveStreamPreviewPNG())
	mux.Handle("GET /s/{public_token}", s.handleLiveStreamShow())

	// API legacy (CLI 2.x)
	mux.Handle("POST /api/asciicasts", s.handleRecordingCreate())

	// Wrap with no-cache middleware — static assets and cast files set their
	// own Cache-Control via ETag handlers above; this covers everything else.
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-cache")
		mux.ServeHTTP(w, r)
	})
}

// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------

func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, `Usage: asciinema-server <command>

Commands:
  serve           Start the HTTP server
  create-invite   Create an invite token for a new user
  delete-user     Delete a user and all their recordings
  reset-password  Reset a user's password via a new invite token
  alis-watch      Watch a live stream, printing decoded ALiS events

Environment variables (for all commands):
  DATABASE_PATH      Path to the SQLite database (default: asciinema.db)
  BASE_URL           Public base URL, e.g. https://asciinema.example.com

Environment variables (for serve only):
  PORT               Port to listen on (default: 4000)
  LISTEN_ADDR        Full listen address, overrides PORT (default: 127.0.0.1:PORT)
  APP_TITLE          Title shown in the UI (default: asciinema)
  UPLOAD_SIZE_LIMIT  Max upload size in bytes (default: 10485760)
`)
		os.Exit(1)
	}
	switch os.Args[1] {
	case "serve":
		runServer()
	case "create-invite":
		runCreateInvite(os.Args[2:])
	case "delete-user":
		runDeleteUser(os.Args[2:])
	case "reset-password":
		runResetPassword(os.Args[2:])
	case "alis-watch":
		runAlisWatch(os.Args[2:])
	default:
		fmt.Fprintf(os.Stderr, "unknown command: %s\n", os.Args[1])
		os.Exit(1)
	}
}

func runAlisWatch(args []string) {
	if len(args) != 1 {
		fmt.Fprintf(os.Stderr, "Usage: asciinema-server alis-watch <url>\n")
		fmt.Fprintf(os.Stderr, "  url: stream page URL, e.g. http://localhost:4000/s/<token>\n")
		os.Exit(1)
	}

	rawURL := args[0]
	u, err := url.Parse(rawURL)
	if err != nil {
		fmt.Fprintf(os.Stderr, "invalid URL: %v\n", err)
		os.Exit(1)
	}

	// Rewrite /s/{token} → /ws/s/{token} and http → ws.
	if strings.HasPrefix(u.Path, "/s/") {
		u.Path = "/ws" + u.Path
	}
	switch u.Scheme {
	case "http":
		u.Scheme = "ws"
	case "https":
		u.Scheme = "wss"
	}
	wsURL := u.String()

	// Connect — use the origin equal to the server itself to pass the
	// x/net/websocket origin check on the server side (our handshake
	// bypasses it, but the client also needs a valid origin header).
	origin := u.Scheme + "://" + u.Host
	cfg, err := websocket.NewConfig(wsURL, origin)
	if err != nil {
		fmt.Fprintf(os.Stderr, "websocket config error: %v\n", err)
		os.Exit(1)
	}
	cfg.Protocol = []string{"v1.alis"}

	ws, err := websocket.DialConfig(cfg)
	if err != nil {
		fmt.Fprintf(os.Stderr, "connect error: %v\n", err)
		os.Exit(1)
	}
	defer ws.Close()

	fmt.Printf("connected to %s\n\n", wsURL)

	gotMagic := false
	for {
		var msg []byte
		if err := websocket.Message.Receive(ws, &msg); err != nil {
			fmt.Printf("[disconnected: %v]\n", err)
			return
		}

		// Magic header
		if !gotMagic {
			if len(msg) == 5 && string(msg) == "ALiS\x01" {
				gotMagic = true
				fmt.Println("[magic] ALiS v1")
				continue
			}
			fmt.Printf("[error] expected magic, got %d bytes\n", len(msg))
			return
		}

		ev, ok := parseALiSMessage(msg)
		if !ok {
			fmt.Printf("[unknown] %d bytes: %x\n", len(msg), msg)
			continue
		}

		switch ev.kind {
		case "init":
			fmt.Printf("[init]   id=%-6d time=%-10s cols=%-4d rows=%-4d data=%d bytes\n",
				ev.lastID,
				formatMicros(ev.time),
				ev.cols, ev.rows,
				len(ev.initData),
			)
		case "output":
			fmt.Printf("[output] id=%-6d rel=%-10s %s\n",
				ev.id, formatMicros(ev.time), formatALiSData(ev.data))
		case "input":
			fmt.Printf("[input]  id=%-6d rel=%-10s %s\n",
				ev.id, formatMicros(ev.time), formatALiSData(ev.data))
		case "resize":
			fmt.Printf("[resize] id=%-6d rel=%-10s cols=%d rows=%d\n",
				ev.id, formatMicros(ev.time), ev.cols, ev.rows)
		case "marker":
			fmt.Printf("[marker] id=%-6d rel=%-10s %s\n",
				ev.id, formatMicros(ev.time), formatALiSData(ev.data))
		case "exit":
			fmt.Printf("[exit]   id=%-6d rel=%-10s status=%d\n",
				ev.id, formatMicros(ev.time), ev.status)
		case "eot":
			fmt.Printf("[eot]    rel=%s\n", formatMicros(ev.time))
			return
		}
	}
}

// formatMicros formats a microsecond duration as a human-readable string.
func formatMicros(micros uint64) string {
	d := time.Duration(micros) * time.Microsecond
	if d < time.Millisecond {
		return fmt.Sprintf("%dµs", micros)
	}
	if d < time.Second {
		return fmt.Sprintf("%.1fms", float64(micros)/1000)
	}
	return fmt.Sprintf("%.3fs", float64(micros)/1_000_000)
}

// ANSI color helpers used by formatALiSData.
const (
	ansiReset  = "\x1b[0m"
	ansiDim    = "\x1b[2m"
	ansiYellow = "\x1b[33m"
	ansiBold   = "\x1b[1m"
)

// sgrColor maps SGR color indices to ANSI escape codes for inline colorization.
var sgrColorNames = [16]string{
	"black", "red", "green", "yellow", "blue", "magenta", "cyan", "white",
	"bright-black", "bright-red", "bright-green", "bright-yellow",
	"bright-blue", "bright-magenta", "bright-cyan", "bright-white",
}
var sgrColorAnsi = [16]string{
	"\x1b[30m", "\x1b[31m", "\x1b[32m", "\x1b[33m", "\x1b[34m", "\x1b[35m", "\x1b[36m", "\x1b[37m",
	"\x1b[90m", "\x1b[91m", "\x1b[92m", "\x1b[93m", "\x1b[94m", "\x1b[95m", "\x1b[96m", "\x1b[97m",
}

// seq emits a named escape sequence token in yellow.
func seq(name string) string {
	return ansiYellow + "⟨" + name + "⟩" + ansiReset
}

// ctrl emits a C0 control token in dim.
func ctrl(name string) string {
	return ansiDim + "⟨" + name + "⟩" + ansiReset
}

// parseSGR parses CSI SGR parameters and returns a human-readable description
// with inline colors for fg/bg values.
func parseSGR(params []int) string {
	if len(params) == 0 || (len(params) == 1 && params[0] == 0) {
		return "SGR reset"
	}
	var parts []string
	i := 0
	for i < len(params) {
		p := params[i]
		switch {
		case p == 0:
			parts = append(parts, "reset")
		case p == 1:
			parts = append(parts, ansiBold+"bold"+ansiReset+ansiYellow)
		case p == 2:
			parts = append(parts, "dim")
		case p == 3:
			parts = append(parts, "italic")
		case p == 4:
			parts = append(parts, "ul")
		case p == 5:
			parts = append(parts, "blink")
		case p == 7:
			parts = append(parts, "inv")
		case p == 8:
			parts = append(parts, "invis")
		case p == 9:
			parts = append(parts, "strike")
		case p == 22:
			parts = append(parts, "no-bold")
		case p == 23:
			parts = append(parts, "no-italic")
		case p == 24:
			parts = append(parts, "no-ul")
		case p == 27:
			parts = append(parts, "no-inv")
		case p >= 30 && p <= 37:
			idx := p - 30
			parts = append(parts, sgrColorAnsi[idx]+"fg="+sgrColorNames[idx]+ansiReset+ansiYellow)
		case p == 38 && i+2 < len(params) && params[i+1] == 5:
			idx := params[i+2]
			name := fmt.Sprintf("fg=color%d", idx)
			if idx < 16 {
				name = sgrColorAnsi[idx] + "fg=" + sgrColorNames[idx] + ansiReset + ansiYellow
			}
			parts = append(parts, name)
			i += 2
		case p == 38 && i+4 < len(params) && params[i+1] == 2:
			parts = append(parts, fmt.Sprintf("fg=rgb(%d,%d,%d)", params[i+2], params[i+3], params[i+4]))
			i += 4
		case p == 39:
			parts = append(parts, "fg=default")
		case p >= 40 && p <= 47:
			idx := p - 40
			parts = append(parts, sgrColorAnsi[idx]+"bg="+sgrColorNames[idx]+ansiReset+ansiYellow)
		case p == 48 && i+2 < len(params) && params[i+1] == 5:
			idx := params[i+2]
			name := fmt.Sprintf("bg=color%d", idx)
			if idx < 16 {
				name = sgrColorAnsi[idx] + "bg=" + sgrColorNames[idx] + ansiReset + ansiYellow
			}
			parts = append(parts, name)
			i += 2
		case p == 48 && i+4 < len(params) && params[i+1] == 2:
			parts = append(parts, fmt.Sprintf("bg=rgb(%d,%d,%d)", params[i+2], params[i+3], params[i+4]))
			i += 4
		case p == 49:
			parts = append(parts, "bg=default")
		case p >= 90 && p <= 97:
			idx := p - 90 + 8
			parts = append(parts, sgrColorAnsi[idx]+"fg="+sgrColorNames[idx]+ansiReset+ansiYellow)
		case p >= 100 && p <= 107:
			idx := p - 100 + 8
			parts = append(parts, sgrColorAnsi[idx]+"bg="+sgrColorNames[idx]+ansiReset+ansiYellow)
		default:
			parts = append(parts, fmt.Sprintf("%d", p))
		}
		i++
	}
	result := "SGR"
	if len(parts) > 0 {
		result += " " + strings.Join(parts, " ")
	}
	return result
}

// parseCSIParams parses semicolon-separated integer params from a CSI sequence.
func parseCSIParams(s string) []int {
	if s == "" {
		return []int{0}
	}
	var result []int
	for _, part := range strings.Split(s, ";") {
		part = strings.TrimSpace(part)
		if part == "" {
			result = append(result, 0)
			continue
		}
		n, err := strconv.Atoi(part)
		if err != nil {
			result = append(result, 0)
		} else {
			result = append(result, n)
		}
	}
	return result
}

// formatALiSData formats a terminal data string with named escape sequences.
// Printable text is shown as-is; escape sequences are shown as ⟨NAME args⟩ in
// yellow; C0 controls as dim ⟨NAME⟩. Long output is truncated.
func formatALiSData(s string) string {
	const maxVisible = 120
	var out strings.Builder
	visible := 0 // count of visible (non-escape) runes for truncation

	i := 0
	runes := []rune(s)
	n := len(runes)

	for i < n && visible < maxVisible {
		r := runes[i]

		// C0 controls
		switch r {
		case '\r':
			out.WriteString(ctrl("CR"))
			i++
			continue
		case '\n':
			out.WriteString(ctrl("LF"))
			i++
			continue
		case '\t':
			out.WriteString(ctrl("HT"))
			i++
			continue
		case '\x07':
			out.WriteString(ctrl("BEL"))
			i++
			continue
		case '\x08':
			out.WriteString(ctrl("BS"))
			i++
			continue
		case '\x0e':
			out.WriteString(ctrl("SO"))
			i++
			continue
		case '\x0f':
			out.WriteString(ctrl("SI"))
			i++
			continue
		}

		// ESC sequences
		if r == '\x1b' {
			if i+1 >= n {
				out.WriteString(seq("ESC"))
				i++
				continue
			}
			next := runes[i+1]

			// ESC followed by a single char (not '[' or '(')
			switch next {
			case '7':
				out.WriteString(seq("SC"))
				i += 2
				continue
			case '8':
				out.WriteString(seq("RC"))
				i += 2
				continue
			case 'c':
				out.WriteString(seq("RIS"))
				i += 2
				continue
			case 'M':
				out.WriteString(seq("RI"))
				i += 2
				continue
			case '=':
				out.WriteString(seq("DECKPAM"))
				i += 2
				continue
			case '>':
				out.WriteString(seq("DECKPNM"))
				i += 2
				continue
			}

			// ESC ( charset
			if next == '(' && i+2 < n {
				ch := runes[i+2]
				switch ch {
				case 'B':
					out.WriteString(seq("CHARSET ascii"))
				case '0':
					out.WriteString(seq("CHARSET gfx"))
				default:
					out.WriteString(seq(fmt.Sprintf("CHARSET %c", ch)))
				}
				i += 3
				continue
			}

			// CSI — ESC [
			if next == '[' {
				// Collect until final byte (0x40–0x7e)
				j := i + 2
				for j < n && (runes[j] < 0x40 || runes[j] > 0x7e) {
					j++
				}
				if j >= n {
					out.WriteString(ansiDim + "⟨ESC[…⟩" + ansiReset)
					i = j
					continue
				}
				params := string(runes[i+2 : j])
				final := runes[j]
				i = j + 1

				// Private sequences ESC [ ? ...
				isPrivate := strings.HasPrefix(params, "?")
				privParams := strings.TrimPrefix(params, "?")

				switch {
				case final == 'm':
					nums := parseCSIParams(params)
					out.WriteString(ansiYellow + "⟨" + parseSGR(nums) + "⟩" + ansiReset)

				case final == 'H' || final == 'f':
					ps := parseCSIParams(params)
					row, col := 1, 1
					if len(ps) >= 1 && ps[0] != 0 {
						row = ps[0]
					}
					if len(ps) >= 2 && ps[1] != 0 {
						col = ps[1]
					}
					out.WriteString(seq(fmt.Sprintf("CUP %d,%d", row, col)))

				case final == 'A':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CUU %d", max1(ps))))
				case final == 'B':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CUD %d", max1(ps))))
				case final == 'C':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CUF %d", max1(ps))))
				case final == 'D':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CUB %d", max1(ps))))
				case final == 'E':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CNL %d", max1(ps))))
				case final == 'F':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CPL %d", max1(ps))))
				case final == 'G':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("CHA %d", max1(ps))))
				case final == 'd':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("VPA %d", max1(ps))))

				case final == 'J':
					ps := parseCSIParams(params)
					names := []string{"below", "above", "all", "saved"}
					p := 0
					if len(ps) > 0 {
						p = ps[0]
					}
					name := fmt.Sprintf("%d", p)
					if p < len(names) {
						name = names[p]
					}
					out.WriteString(seq("ED " + name))

				case final == 'K':
					ps := parseCSIParams(params)
					names := []string{"right", "left", "all"}
					p := 0
					if len(ps) > 0 {
						p = ps[0]
					}
					name := fmt.Sprintf("%d", p)
					if p < len(names) {
						name = names[p]
					}
					out.WriteString(seq("EL " + name))

				case final == 'L':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("IL %d", max1(ps))))
				case final == 'M':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("DL %d", max1(ps))))
				case final == 'P':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("DCH %d", max1(ps))))
				case final == '@':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("ICH %d", max1(ps))))
				case final == 'X':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("ECH %d", max1(ps))))
				case final == 'S':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("SU %d", max1(ps))))
				case final == 'T':
					ps := parseCSIParams(params)
					out.WriteString(seq(fmt.Sprintf("SD %d", max1(ps))))

				case final == 'r':
					ps := parseCSIParams(params)
					top, bot := 1, 1
					if len(ps) >= 1 {
						top = ps[0]
					}
					if len(ps) >= 2 {
						bot = ps[1]
					}
					out.WriteString(seq(fmt.Sprintf("DECSTBM %d,%d", top, bot)))

				case final == 's':
					out.WriteString(seq("SC"))
				case final == 'u':
					out.WriteString(seq("RC"))

				case final == 'h' && isPrivate:
					out.WriteString(seq(decprivName(privParams, true)))
				case final == 'l' && isPrivate:
					out.WriteString(seq(decprivName(privParams, false)))

				case final == 'n' && params == "6":
					out.WriteString(seq("CPR"))

				default:
					out.WriteString(ansiDim + "⟨CSI " + params + string(final) + "⟩" + ansiReset)
				}
				visible += 4 // count sequence as a small fixed cost
				continue
			}

			// OSC — ESC ]
			if next == ']' {
				j := i + 2
				for j < n {
					if runes[j] == '\x07' {
						j++
						break
					}
					if runes[j] == '\x1b' && j+1 < n && runes[j+1] == '\\' {
						j += 2
						break
					}
					j++
				}
				inner := string(runes[i+2 : j])
				if len(inner) > 20 {
					inner = inner[:20] + "…"
				}
				out.WriteString(seq("OSC " + inner))
				i = j
				visible += 4
				continue
			}

			// Unknown ESC x
			out.WriteString(ansiDim + fmt.Sprintf("⟨ESC %c⟩", next) + ansiReset)
			i += 2
			continue
		}

		// Printable
		if r >= 0x20 && r != 0x7f {
			out.WriteRune(r)
			visible++
		} else {
			// Other non-printable
			out.WriteString(ansiDim + fmt.Sprintf("⟨%02X⟩", r) + ansiReset)
		}
		i++
	}

	if i < n {
		remaining := len(string(runes[i:]))
		out.WriteString(ansiDim + fmt.Sprintf(" … (+%d bytes)", remaining) + ansiReset)
	}

	return out.String()
}

// decprivName returns a human-readable name for a DEC private mode.
func decprivName(param string, set bool) string {
	action := map[bool]string{true: "show", false: "hide"}
	on := map[bool]string{true: "on", false: "off"}
	enter := map[bool]string{true: "enter", false: "exit"}
	switch param {
	case "1":
		return "DECCKM " + on[set]
	case "3":
		return "DECCOLM " + on[set]
	case "6":
		return "DECOM " + on[set]
	case "7":
		return "DECAWM " + on[set]
	case "25":
		return "DECTCEM " + action[set]
	case "1000":
		return "MOUSE " + on[set]
	case "1002":
		return "MOUSE-BTN " + on[set]
	case "1006":
		return "MOUSE-SGR " + on[set]
	case "1049":
		return "ALTBUF " + enter[set]
	case "2004":
		return "BPASTE " + on[set]
	case "2026":
		return "SYNC " + on[set]
	default:
		return fmt.Sprintf("DEC?%s %s", param, on[set])
	}
}

// max1 returns the first param or 1 if empty/zero.
func max1(ps []int) int {
	if len(ps) == 0 || ps[0] == 0 {
		return 1
	}
	return ps[0]
}

// openSubcommandDB opens the SQLite database for a CLI subcommand.
// On error it prints to stderr and calls os.Exit(1).
func openSubcommandDB() (*sql.DB, Config) {
	cfg := loadConfig()
	db, err := sql.Open("sqlite", sqliteDSN(cfg.DatabasePath))
	if err != nil {
		fmt.Fprintf(os.Stderr, "open db: %v\n", err)
		os.Exit(1)
	}
	if _, err := db.Exec(schema); err != nil {
		fmt.Fprintf(os.Stderr, "schema: %v\n", err)
		os.Exit(1)
	}
	return db, cfg
}

// mustLookupUserID looks up a user by username, printing an error and
// calling os.Exit(1) if not found or on DB error.
func mustLookupUserID(db *sql.DB, username string) int64 {
	var userID int64
	err := db.QueryRow(`SELECT id FROM users WHERE username = ?`, username).Scan(&userID)
	if errors.Is(err, sql.ErrNoRows) {
		fmt.Fprintf(os.Stderr, "user %q not found\n", username)
		os.Exit(1)
	}
	if err != nil {
		fmt.Fprintf(os.Stderr, "query: %v\n", err)
		os.Exit(1)
	}
	return userID
}

// mustExec executes a DB statement, printing an error and calling os.Exit(1) on failure.
func mustExec(db *sql.DB, label, query string, args ...any) {
	if _, err := db.Exec(query, args...); err != nil {
		fmt.Fprintf(os.Stderr, "%s: %v\n", label, err)
		os.Exit(1)
	}
}

func runCreateInvite(args []string) {
	fs := flag.NewFlagSet("create-invite", flag.ExitOnError)
	username := fs.String("username", "", "Username to reserve for this invite (required)")
	fs.Parse(args)
	if *username == "" {
		fmt.Fprintln(os.Stderr, "Usage: asciinema-server create-invite -username NAME")
		os.Exit(1)
	}

	db, cfg := openSubcommandDB()
	defer db.Close()

	token := randomToken(24)
	if err := createInvite(db, *username, token); err != nil {
		fmt.Fprintf(os.Stderr, "create invite: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Invite token for %s: %s\n", *username, token)
	fmt.Printf("Registration URL: %s/connect/<install_id>\n", cfg.BaseURL)
	fmt.Printf("(User visits that URL after running 'asciinema upload')\n")
}

func runDeleteUser(args []string) {
	fs := flag.NewFlagSet("delete-user", flag.ExitOnError)
	username := fs.String("username", "", "Username to delete (required)")
	fs.Parse(args)
	if *username == "" {
		fmt.Fprintln(os.Stderr, "Usage: asciinema-server delete-user -username NAME")
		os.Exit(1)
	}

	db, _ := openSubcommandDB()
	defer db.Close()

	userID := mustLookupUserID(db, *username)

	count, err := deleteUserAndEverything(db, userID)
	if err != nil {
		fmt.Fprintf(os.Stderr, "delete: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Deleted user %s and %d recording(s).\n", *username, count)
}

func runResetPassword(args []string) {
	fs := flag.NewFlagSet("reset-password", flag.ExitOnError)
	username := fs.String("username", "", "Username to reset password for (required)")
	fs.Parse(args)
	if *username == "" {
		fmt.Fprintln(os.Stderr, "Usage: asciinema-server reset-password -username NAME")
		os.Exit(1)
	}

	db, _ := openSubcommandDB()
	defer db.Close()

	userID := mustLookupUserID(db, *username)

	// Remove all invites for this username (used or not) so we can create a fresh one
	mustExec(db, "delete old invite", `DELETE FROM invites WHERE username = ?`, *username)

	// Clear the password hash so old password no longer works
	mustExec(db, "clear password", `UPDATE users SET password_hash = NULL WHERE id = ?`, userID)

	// Create a new invite token
	token := randomToken(24)
	if err := createInvite(db, *username, token); err != nil {
		fmt.Fprintf(os.Stderr, "create invite: %v\n", err)
		os.Exit(1)
	}

	fmt.Printf("Password reset token for %s: %s\n", *username, token)
	fmt.Printf("User visits /connect/<install_id> and uses this token to set a new password.\n")
}

func runServer() {
	cfg := loadConfig()

	srv, err := openServer(cfg)
	if err != nil {
		log.Fatalf("open server: %v", err)
	}
	defer srv.close()

	port := getenv("PORT", "4000")
	addr := getenv("LISTEN_ADDR", "127.0.0.1:"+port)
	log.Printf("asciinema-server listening on %s (base URL: %s)", addr, cfg.BaseURL)
	if err := http.ListenAndServe(addr, srv.routes()); err != nil {
		log.Fatal(err)
	}
}