Pre-launch — Gluecron is in final validation. Public signups and git hosting for non-owner users open after launch review.
CodeIssuesDiscussionsWikiPull RequestsProjectsCommitsActionsReleasesContributorsPulse● GatesSecuritySettingsDeploymentsPipelineInsightsAgents✨ Explain✨ Ask AI✨ Workspace✨ Spec✨ Tests▓ Debt Map✨ NL Search🏛 Archaeology
claude/adoring-hopper-5x74bqclaude/affectionate-feynman-ykrf1hclaude/architecture-audit-design-wxprenclaude/build-status-update-3MXsfclaude/charming-meitner-mllb5rclaude/compare-gate-gluecron-s4mFQclaude/confident-faraday-tikcwbclaude/continue-work-XMTlIclaude/crontech-gluecron-deploy-7MIECclaude/crontech-platform-setup-SeKfwclaude/design-2026claude/ecstatic-ptolemy-jMdigclaude/enhance-github-integration-QNHdGclaude/fix-aa-loop-issue-PonMQclaude/fix-actions-and-processclaude/fix-desktop-errors-XqoW8claude/fix-red-workflowsclaude/fix-website-access-6FKJNclaude/gatetest-integration-hardeningclaude/github-audit-improvements-bDFr9claude/gluecron-launch-status-FoMRlclaude/hopeful-lamport-olfCTclaude/issue-to-pr-and-protectionsclaude/jolly-heisenberg-2sg1Qclaude/launch-preparation-QmTb6claude/new-session-xk1l7claude/plan-platform-architecture-kkN4yclaude/platform-analysis-roadmap-1nUGLclaude/platform-launch-assessment-8dWV8claude/polish-platform-release-AeDrUclaude/resume-previous-work-KzyLwclaude/review-crontech-handoff-qYEVqclaude/review-project-completeness-lHhS2claude/review-readme-docs-ulqPKclaude/serene-edison-rj87weclaude/setup-multi-repo-dev-BCwNQclaude/ship-fixes-and-tests-Jvz1cclaude/site-audit-competitive-pctlwgclaude/site-migration-vercel-XstpKclaude/standalone-product-repos-XHFTDcopilot/feat-smart-empty-states-keyboard-first-enhancementcopilot/feat-smart-morning-digest-review-context-restorecopilot/fix-and-process-workflowscopilot/update-ai-powered-code-reviewfeat/debt-mapfeat/push-policy-codeowners-hardeningfeat/smart-digest-contextfeat/stage-impactfeat/t1-secret-migrationfeat/u-polishfeat/w-self-hostfeat/w2-claude-configfix/agent-journey-orphan-sweepgatetest/auto-fix-1776586424172gatetest/auto-fix-1776586534814gatetest/auto-fix-1776590685143gatetest/auto-fix-1776590808199mainops/redeploy-retriggerstyle/dxt-cta-themeworktree-agent-a3377aad30d55da26worktree-agent-a7ef607b7ee1d6c74
issues.tsx87.0 KB · 2570 lines
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
/**
 * Issue tracker routes — list, create, view, comment, close/reopen.
 */

import { Hono } from "hono";
import { eq, and, desc, asc, sql, ilike, inArray, or } from "drizzle-orm";
import { db } from "../db";
import { fireWebhooks } from "./webhooks";
import {
  issues,
  issueComments,
  repositories,
  users,
  labels,
  issueLabels,
  pullRequests,
  milestones,
} from "../db/schema";
import { Layout } from "../views/layout";
import { RepoHeader, RepoNav } from "../views/components";
import { PendingCommentsBanner } from "../views/pending-comments-banner";
import { ReactionsBar } from "../views/reactions";
import { summariseReactions } from "../lib/reactions";
import { loadIssueTemplate } from "../lib/templates";
import { renderMarkdown } from "../lib/markdown";
import { liveCommentBannerScript } from "../lib/sse-client";
import { mentionAutocompleteScript } from "../lib/mention-autocomplete";
import { markdownPreviewScript } from "../lib/markdown-preview";
import { ctrlEnterSubmitScript, codeBlockCopyScript } from "../lib/keyboard-ux";
import { triggerIssueTriage, ISSUE_TRIAGE_MARKER } from "../lib/issue-triage";
import { softAuth, requireAuth } from "../middleware/auth";
import type { AuthEnv } from "../middleware/auth";
import { requireRepoAccess } from "../middleware/repo-access";
import {
  decideInitialStatus,
  notifyOwnerOfPendingComment,
  countPendingForRepo,
} from "../lib/comment-moderation";
import {
  Flex,
  Container,
  PageHeader,
  Form,
  FormGroup,
  Input,
  TextArea,
  Button,
  LinkButton,
  Badge,
  EmptyState,
  TabNav,
  FilterTabs,
  List,
  ListItem,
  Alert,
  CommentBox,
  CommentForm,
  formatRelative,
} from "../views/ui";
import { getDefaultBranch, resolveRef, updateRef } from "../git/repository";
import { BOT_USERNAME } from "../lib/bot-user";
import { isAiAvailable } from "../lib/ai-client";

const issueRoutes = new Hono<AuthEnv>();

// ---------------------------------------------------------------------------
// Visual polish: inline CSS scoped to `.issues-*` so it never collides with
// other routes/shared views. All design tokens come from :root in layout.tsx.
// ---------------------------------------------------------------------------
const issuesStyles = `
  /* Hero card — list page */
  .issues-hero {
    position: relative;
    margin: 4px 0 24px;
    padding: 28px 32px;
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
  }
  .issues-hero::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, #5b6ee8 30%, #5f8fa0 70%, transparent 100%);
    opacity: 0.7;
    pointer-events: none;
  }
  .issues-hero-bg {
    position: absolute;
    inset: -30% -10% auto auto;
    width: 360px;
    height: 360px;
    pointer-events: none;
    z-index: 0;
  }
  .issues-hero-orb {
    position: absolute;
    inset: 0;
    background: radial-gradient(circle, rgba(91,110,232,0.18), rgba(95,143,160,0.09) 45%, transparent 70%);
    filter: blur(80px);
    opacity: 0.7;
    animation: issuesHeroOrb 14s ease-in-out infinite;
  }
  @keyframes issuesHeroOrb {
    0%, 100% { transform: scale(1) translate(0, 0); opacity: 0.6; }
    50%      { transform: scale(1.1) translate(-12px, 8px); opacity: 0.85; }
  }
  @media (prefers-reduced-motion: reduce) {
    .issues-hero-orb { animation: none; }
  }
  .issues-hero-inner {
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    gap: 24px;
    flex-wrap: wrap;
  }
  .issues-hero-text { flex: 1; min-width: 280px; }
  .issues-hero-eyebrow {
    font-size: 12.5px;
    color: var(--text-muted);
    margin-bottom: 8px;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    font-weight: 600;
  }
  .issues-hero-eyebrow .issues-hero-repo {
    color: var(--accent);
    text-transform: none;
    letter-spacing: -0.005em;
    font-weight: 600;
  }
  .issues-hero-title {
    font-family: var(--font-display);
    font-size: clamp(28px, 4vw, 40px);
    font-weight: 800;
    letter-spacing: -0.028em;
    line-height: 1.05;
    margin: 0 0 10px;
    color: var(--text-strong);
  }
  .issues-hero-sub {
    font-size: 15px;
    color: var(--text-muted);
    margin: 0;
    line-height: 1.5;
    max-width: 580px;
  }
  .issues-hero-actions {
    display: flex;
    gap: 8px;
    flex-wrap: wrap;
  }
  @media (max-width: 720px) {
    .issues-hero { padding: 24px 20px; }
    .issues-hero-inner { flex-direction: column; align-items: flex-start; }
    .issues-hero-actions { width: 100%; }
    .issues-hero-actions .btn { flex: 1; min-width: 0; }
  }

  /* Mobile rules — added in the 720px sweep. Kept additive only. */
  @media (max-width: 720px) {
    .issues-toolbar { flex-direction: column; align-items: stretch; }
    .issues-filters { width: 100%; overflow-x: auto; -webkit-overflow-scrolling: touch; }
    .issues-filter { min-height: 40px; padding: 10px 14px; }
    .issues-row { padding: 12px 14px; gap: 10px; }
    .issues-row-side { flex-wrap: wrap; gap: 8px; }
    .issues-detail-hero { padding: 18px; }
    .issues-detail-attr { font-size: 13px; }
    .issues-composer-actions { gap: 8px; }
    .issues-composer-actions .btn { flex: 1; min-width: 0; min-height: 44px; }
    .issues-empty { padding: 40px 20px; }
  }

  /* Count chip + filter pills */
  .issues-toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 12px;
    flex-wrap: wrap;
    margin: 0 0 16px;
  }
  .issues-filters {
    display: inline-flex;
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 9999px;
    padding: 4px;
    gap: 2px;
  }
  .issues-filter {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 6px 14px;
    border-radius: 9999px;
    font-size: 13px;
    font-weight: 500;
    color: var(--text-muted);
    text-decoration: none;
    transition: color 120ms ease, background 120ms ease;
    line-height: 1.4;
  }
  .issues-filter:hover { color: var(--text-strong); text-decoration: none; }
  .issues-filter.is-active {
    background: rgba(91,110,232,0.14);
    color: var(--text-strong);
  }
  .issues-filter-count {
    font-variant-numeric: tabular-nums;
    font-size: 11.5px;
    color: var(--text-muted);
    background: rgba(255,255,255,0.04);
    padding: 1px 7px;
    border-radius: 9999px;
  }
  .issues-filter.is-active .issues-filter-count {
    background: rgba(91,110,232,0.18);
    color: var(--text);
  }

  /* Issue search form */
  .issues-search-form {
    display: flex;
    align-items: center;
    gap: 0;
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 9999px;
    overflow: hidden;
    flex: 1;
    max-width: 280px;
    transition: border-color 120ms ease;
  }
  .issues-search-form:focus-within { border-color: rgba(91,110,232,0.55); }
  .issues-search-input {
    flex: 1;
    background: transparent;
    color: var(--text);
    border: none;
    outline: none;
    padding: 6px 14px;
    font-size: 13px;
    font-family: var(--font-sans, inherit);
    min-width: 0;
  }
  .issues-search-input::placeholder { color: var(--text-muted); }
  .issues-search-btn {
    background: transparent;
    border: none;
    color: var(--text-muted);
    padding: 6px 12px 6px 8px;
    cursor: pointer;
    display: flex;
    align-items: center;
  }
  .issues-search-btn:hover { color: var(--text); }
  .issues-filter-banner {
    margin-bottom: 12px;
    padding: 8px 14px;
    background: rgba(91,110,232,0.06);
    border: 1px solid rgba(91,110,232,0.2);
    border-radius: 8px;
    font-size: 13px;
    color: var(--text-muted);
  }
  .issues-filter-clear {
    color: var(--accent, #5b6ee8);
    text-decoration: underline;
    cursor: pointer;
  }
  .issues-label-badge {
    display: inline-block;
    background: rgba(91,110,232,0.15);
    color: #a78bfa;
    border-radius: 9999px;
    padding: 1px 8px;
    font-size: 11.5px;
    font-weight: 600;
  }

  /* Issue list — modernised rows */
  .issues-list {
    list-style: none;
    margin: 0;
    padding: 0;
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
    background: var(--bg-elevated);
  }
  .issues-row {
    display: flex;
    align-items: flex-start;
    gap: 14px;
    padding: 14px 18px;
    border-bottom: 1px solid var(--border);
    transition: background 120ms ease, transform 120ms ease;
  }
  .issues-row:last-child { border-bottom: none; }
  .issues-row:hover { background: rgba(91,110,232,0.04); }
  .issues-row-icon {
    width: 18px;
    height: 18px;
    flex-shrink: 0;
    margin-top: 3px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
  }
  .issues-row-icon.is-open  { color: #34d399; }
  .issues-row-icon.is-closed { color: #5b6ee8; }
  .issues-row-main { flex: 1; min-width: 0; }
  .issues-row-title {
    font-family: var(--font-display);
    font-size: 15.5px;
    font-weight: 600;
    line-height: 1.35;
    letter-spacing: -0.012em;
    margin: 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    gap: 8px;
  }
  .issues-row-title a {
    color: var(--text-strong);
    text-decoration: none;
    transition: color 120ms ease;
  }
  .issues-row-title a:hover { color: var(--accent); }
  .issues-row-meta {
    margin-top: 5px;
    font-size: 12.5px;
    color: var(--text-muted);
    line-height: 1.5;
  }
  .issues-row-meta strong { color: var(--text); font-weight: 600; }
  .issues-row-side {
    display: flex;
    align-items: center;
    gap: 12px;
    color: var(--text-muted);
    font-size: 12.5px;
    flex-shrink: 0;
  }
  .issues-row-comments {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    color: var(--text-muted);
    text-decoration: none;
  }
  .issues-row-comments:hover { color: var(--accent); text-decoration: none; }

  /* Label pills (rendered inline on titles) */
  .issues-label {
    display: inline-flex;
    align-items: center;
    padding: 2px 9px;
    border-radius: 9999px;
    font-size: 11.5px;
    font-weight: 600;
    line-height: 1.4;
    background: rgba(91,110,232,0.10);
    color: var(--text-strong);
    border: 1px solid rgba(91,110,232,0.28);
    letter-spacing: 0.005em;
  }

  /* Polished empty state */
  .issues-empty {
    margin: 0;
    padding: 56px 32px;
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 16px;
    text-align: center;
    position: relative;
    overflow: hidden;
  }
  .issues-empty::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, #5b6ee8 30%, #5f8fa0 70%, transparent 100%);
    opacity: 0.55;
    pointer-events: none;
  }
  .issues-empty-art {
    width: 96px;
    height: 96px;
    margin: 0 auto 18px;
    display: block;
    opacity: 0.85;
  }
  .issues-empty-title {
    font-family: var(--font-display);
    font-size: 22px;
    font-weight: 700;
    letter-spacing: -0.018em;
    color: var(--text-strong);
    margin: 0 0 8px;
  }
  .issues-empty-sub {
    font-size: 14.5px;
    color: var(--text-muted);
    line-height: 1.55;
    margin: 0 auto 22px;
    max-width: 460px;
  }
  .issues-empty-cta { display: inline-flex; gap: 10px; flex-wrap: wrap; justify-content: center; }

  /* ─── Detail page ─── */
  .issues-detail-hero {
    position: relative;
    margin: 4px 0 20px;
    padding: 22px 26px;
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 16px;
    overflow: hidden;
  }
  .issues-detail-hero::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, transparent 0%, #5b6ee8 30%, #5f8fa0 70%, transparent 100%);
    opacity: 0.7;
    pointer-events: none;
  }
  .issues-detail-title {
    font-family: var(--font-display);
    font-size: clamp(22px, 3vw, 30px);
    font-weight: 700;
    letter-spacing: -0.022em;
    line-height: 1.18;
    color: var(--text-strong);
    margin: 0 0 12px;
  }
  .issues-detail-title .issues-detail-number {
    color: var(--text-muted);
    font-weight: 500;
    margin-left: 8px;
  }
  .issues-detail-attr {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    font-size: 14px;
    color: var(--text-muted);
  }
  .issues-detail-attr strong { color: var(--text); font-weight: 600; }
  .issues-state-pill {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    padding: 5px 12px;
    border-radius: 9999px;
    font-size: 12.5px;
    font-weight: 600;
    line-height: 1.4;
    letter-spacing: 0.005em;
  }
  .issues-state-pill.is-open {
    background: rgba(52,211,153,0.12);
    color: #34d399;
    border: 1px solid rgba(52,211,153,0.35);
  }
  .issues-state-pill.is-closed {
    background: rgba(182,157,255,0.12);
    color: #5b6ee8;
    border: 1px solid rgba(182,157,255,0.35);
  }
  .issues-detail-spacer { flex: 1; }

  /* Sub-issues / epics */
  .issues-epic-crumb {
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 12px;
    color: var(--text-muted);
    margin-bottom: var(--space-2);
  }
  .issues-epic-crumb a { color: var(--accent); text-decoration: none; }
  .issues-epic-crumb a:hover { text-decoration: underline; }
  .issues-sub-panel {
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 12px;
    margin-bottom: var(--space-4);
    overflow: hidden;
  }
  .issues-sub-panel-head {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: var(--space-3) var(--space-4);
    border-bottom: 1px solid var(--border);
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: 0.07em;
    color: var(--text-muted);
  }
  .issues-sub-row {
    display: flex;
    align-items: center;
    gap: var(--space-3);
    padding: var(--space-2) var(--space-4);
    font-size: 13px;
    transition: background 120ms;
  }
  .issues-sub-row:hover { background: var(--bg-hover); }
  .issues-sub-row-icon { font-size: 12px; flex-shrink: 0; }
  .issues-sub-row-icon.is-open   { color: #3fb950; }
  .issues-sub-row-icon.is-closed { color: #5b6ee8; }
  .issues-sub-row-title { flex: 1; min-width: 0; }
  .issues-sub-row-title a { color: var(--text); text-decoration: none; font-weight: 500; }
  .issues-sub-row-title a:hover { color: var(--accent); text-decoration: underline; }
  .issues-sub-row-num { font-size: 11px; color: var(--text-muted); white-space: nowrap; }
  .issues-sub-row-author { font-size: 11px; color: var(--text-muted); white-space: nowrap; }
  /* Epic pill on the issue list */
  .issues-tag-epic {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 2px 7px;
    font-size: 11px; font-weight: 600;
    border-radius: 9999px;
    background: rgba(210,153,34,0.12);
    color: #d29922;
    border: 1px solid rgba(210,153,34,0.35);
  }
  .issues-tag-child {
    display: inline-flex; align-items: center; gap: 4px;
    padding: 2px 7px;
    font-size: 11px; font-weight: 600;
    border-radius: 9999px;
    background: rgba(88,166,255,0.10);
    color: #58a6ff;
    border: 1px solid rgba(88,166,255,0.25);
  }

  .issues-detail-labels {
    margin-top: 12px;
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
  }

  /* Comment thread */
  .issues-thread { margin-top: 18px; }
  .issues-comment {
    position: relative;
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
    background: var(--bg-elevated);
    margin-bottom: 14px;
    transition: border-color 160ms ease, box-shadow 160ms ease;
  }
  .issues-comment:hover {
    border-color: var(--border-strong, rgba(255,255,255,0.13));
  }
  .issues-comment-header {
    background: var(--bg-secondary);
    padding: 10px 16px;
    border-bottom: 1px solid var(--border);
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 13px;
    color: var(--text-muted);
  }
  .issues-comment-header strong { color: var(--text-strong); font-weight: 600; }
  .issues-comment-body { padding: 14px 18px; }
  .issues-comment-author-pill {
    display: inline-flex;
    align-items: center;
    padding: 1px 8px;
    border-radius: 9999px;
    background: rgba(91,110,232,0.10);
    color: var(--accent);
    font-size: 11px;
    font-weight: 600;
    letter-spacing: 0.02em;
    text-transform: uppercase;
  }

  /* AI Review comment — distinct purple-accent treatment */
  .issues-comment.is-ai {
    border-color: rgba(91,110,232,0.45);
    box-shadow: 0 0 0 1px rgba(91,110,232,0.18), 0 12px 32px -16px rgba(91,110,232,0.25);
  }
  .issues-comment.is-ai::before {
    content: '';
    position: absolute;
    top: 0; left: 0; right: 0;
    height: 2px;
    background: linear-gradient(90deg, #5b6ee8 0%, #5f8fa0 100%);
    pointer-events: none;
  }
  .issues-comment.is-ai .issues-comment-header {
    background: linear-gradient(180deg, rgba(91,110,232,0.08), rgba(91,110,232,0.02));
    border-bottom-color: rgba(91,110,232,0.22);
  }
  .issues-ai-badge {
    display: inline-flex;
    align-items: center;
    gap: 5px;
    padding: 2px 9px;
    border-radius: 9999px;
    background: linear-gradient(135deg, #5b6ee8 0%, #5f8fa0 100%);
    color: #fff;
    font-size: 11px;
    font-weight: 700;
    letter-spacing: 0.04em;
    text-transform: uppercase;
    line-height: 1.4;
  }
  .issues-ai-badge::before {
    content: '';
    width: 6px;
    height: 6px;
    border-radius: 9999px;
    background: #fff;
    opacity: 0.92;
    box-shadow: 0 0 6px rgba(255,255,255,0.7);
  }

  .issues-bot-badge {
    display: inline-flex; align-items: center; gap: 3px;
    padding: 1px 7px;
    font-size: 10px;
    font-weight: 600;
    color: var(--fg-muted);
    background: var(--bg-elevated);
    border: 1px solid var(--border);
    border-radius: 9999px;
  }

  /* Composer */
  .issues-composer {
    margin-top: 22px;
    border: 1px solid var(--border);
    border-radius: 12px;
    overflow: hidden;
    background: var(--bg-elevated);
    transition: border-color 160ms ease, box-shadow 160ms ease;
  }
  .issues-composer:focus-within {
    border-color: rgba(91,110,232,0.55);
    box-shadow: 0 0 0 3px rgba(91,110,232,0.16);
  }
  .issues-composer-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 8px;
    padding: 10px 14px;
    background: var(--bg-secondary);
    border-bottom: 1px solid var(--border);
    font-size: 12.5px;
    color: var(--text-muted);
  }
  .issues-composer-tag {
    font-weight: 600;
    color: var(--text);
    letter-spacing: -0.005em;
  }
  .issues-composer-hint a {
    color: var(--text-muted);
    text-decoration: none;
    border-bottom: 1px dashed currentColor;
  }
  .issues-composer-hint a:hover { color: var(--accent); }
  .issues-composer textarea {
    display: block;
    width: 100%;
    border: 0;
    background: transparent;
    color: var(--text);
    padding: 14px 16px;
    font-family: var(--font-mono);
    font-size: 13.5px;
    line-height: 1.55;
    resize: vertical;
    outline: none;
    min-height: 140px;
  }
  .issues-composer-actions {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 10px 14px;
    border-top: 1px solid var(--border);
    background: var(--bg-secondary);
    flex-wrap: wrap;
  }

  /* Info banner inside detail */
  .issues-info-banner {
    margin: 0 0 14px;
    padding: 10px 14px;
    border-radius: 12px;
    background: rgba(91,110,232,0.08);
    border: 1px solid rgba(91,110,232,0.28);
    color: var(--text);
    font-size: 13.5px;
  }

  /* ─── Linked PRs ─── */
  .iss-linked-prs { margin-top: 16px; border: 1px solid var(--border); border-radius: 12px; overflow: hidden; }
  .iss-linked-prs-head { display: flex; align-items: center; justify-content: space-between; padding: 10px 16px; background: var(--bg-elevated); border-bottom: 1px solid var(--border); font-size: 13px; font-weight: 600; }
  .iss-linked-pr-row { display: flex; align-items: center; gap: 10px; padding: 9px 16px; border-bottom: 1px solid var(--border); font-size: 13px; text-decoration: none; color: inherit; }
  .iss-linked-pr-row:last-child { border-bottom: none; }
  .iss-linked-pr-row:hover { background: var(--bg-hover); }
  .iss-linked-pr-icon.is-open { color: #34d399; }
  .iss-linked-pr-icon.is-merged { color: #a78bfa; }
  .iss-linked-pr-icon.is-closed { color: #8b949e; }
  .iss-linked-pr-icon.is-draft { color: #8b949e; }
  .iss-linked-pr-title { flex: 1 1 auto; min-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .iss-linked-pr-num { color: var(--text-muted); font-size: 12px; }
  .iss-linked-pr-state { font-size: 11px; font-weight: 600; padding: 1px 7px; border-radius: 9999px; }
  .iss-linked-pr-state.is-open { color: #34d399; background: rgba(52,211,153,0.10); }
  .iss-linked-pr-state.is-merged { color: #a78bfa; background: rgba(167,139,250,0.10); }
  .iss-linked-pr-state.is-closed { color: #8b949e; background: var(--bg-tertiary); }
  .iss-linked-pr-state.is-draft { color: #8b949e; background: var(--bg-tertiary); }

  /* ─── Bulk action UI ─── */
  .bulk-cb { width:16px; height:16px; accent-color:var(--accent); cursor:pointer; flex-shrink:0; }
  .bulk-bar {
    display: none;
    align-items: center;
    gap: 10px;
    padding: 10px 16px;
    background: var(--bg-elevated);
    border: 1px solid var(--border-strong);
    border-radius: var(--r-md);
    margin-bottom: 12px;
    position: sticky;
    top: calc(var(--header-h) + 8px);
    z-index: 10;
    box-shadow: 0 4px 16px -4px rgba(0,0,0,0.4);
  }
  .bulk-bar-count { font-size:13px; font-weight:600; color:var(--text-strong); flex:1; }
  .bulk-bar-btn {
    padding: 6px 12px;
    border-radius: var(--r-sm);
    border: 1px solid var(--border);
    background: var(--bg-surface);
    color: var(--text);
    font-size: 13px;
    cursor: pointer;
    transition: background 120ms;
  }
  .bulk-bar-btn:hover { background: var(--bg-hover); }
  .bulk-bar-clear { background: none; border: none; color: var(--text-muted); font-size: 12px; cursor: pointer; padding: 4px 8px; }
  .bulk-bar-clear:hover { color: var(--text); }

  /* ─── Issue detail metadata sidebar ─── */
  .issue-detail-layout {
    display: flex;
    align-items: flex-start;
    gap: 24px;
  }
  .issue-detail-main {
    flex: 1;
    min-width: 0;
  }
  .issue-meta-sidebar {
    width: 240px;
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }
  .issue-meta-section {
    border-top: 1px solid var(--border);
    padding-top: 14px;
  }
  .issue-meta-section:first-child {
    border-top: none;
    padding-top: 0;
  }
  .issue-meta-label {
    font-size: 12px;
    font-weight: 600;
    color: var(--text-muted);
    text-transform: uppercase;
    letter-spacing: 0.06em;
    margin-bottom: 8px;
  }
  .issue-meta-empty {
    font-size: 13px;
    color: var(--text-subtle, var(--text-muted));
    font-style: italic;
  }
  .issue-meta-label-pill {
    display: inline-flex;
    align-items: center;
    padding: 3px 10px;
    border-radius: 9999px;
    font-size: 12px;
    font-weight: 600;
    line-height: 1.4;
    margin: 2px 3px 2px 0;
    border: 1px solid transparent;
  }
  .issue-meta-labels {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }
  .issue-meta-assignee {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 13px;
    color: var(--text);
  }
  .issue-meta-avatar {
    width: 24px;
    height: 24px;
    border-radius: 9999px;
    background: rgba(140,109,255,0.25);
    color: var(--text-strong);
    font-size: 11px;
    font-weight: 700;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    flex-shrink: 0;
    text-transform: uppercase;
  }
  .issue-meta-milestone-link {
    font-size: 13px;
    color: var(--text-link, var(--accent));
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    gap: 5px;
  }
  .issue-meta-milestone-link:hover { text-decoration: underline; }
  @media (max-width: 720px) {
    .issue-detail-layout { flex-direction: column; }
    .issue-meta-sidebar { width: 100%; order: 1; }
    .issue-detail-main { order: 0; }
  }

  /* ─── Sort controls (issue list) ─── */
  .issues-sort-row {
    display: flex;
    align-items: center;
    gap: 6px;
    margin: 0 0 12px;
    flex-wrap: wrap;
  }
  .issues-sort-label {
    font-size: 12.5px;
    color: var(--text-muted);
    font-weight: 600;
    margin-right: 2px;
  }
  .issues-sort-opt {
    font-size: 12.5px;
    color: var(--text-muted);
    text-decoration: none;
    padding: 3px 10px;
    border-radius: 9999px;
    border: 1px solid transparent;
    transition: background 120ms ease, color 120ms ease, border-color 120ms ease;
  }
  .issues-sort-opt:hover {
    background: var(--bg-hover);
    color: var(--text);
  }
  .issues-sort-opt.is-active {
    background: rgba(91,110,232,0.12);
    color: var(--text-link);
    border-color: rgba(91,110,232,0.35);
    font-weight: 600;
  }
`;

// Pre-rendered <style> tag (constant, reused per request).
const IssuesStyle = () => (
  <style dangerouslySetInnerHTML={{ __html: issuesStyles }} />
);

// Inline empty-state SVG — a softly-tinted speech-bubble icon. No external assets.
const IssuesEmptySvg = () => (
  <svg
    class="issues-empty-art"
    viewBox="0 0 96 96"
    fill="none"
    xmlns="http://www.w3.org/2000/svg"
    aria-hidden="true"
  >
    <defs>
      <linearGradient id="issuesEmptyG" x1="0" y1="0" x2="1" y2="1">
        <stop offset="0%" stop-color="#5b6ee8" stop-opacity="0.55" />
        <stop offset="100%" stop-color="#5f8fa0" stop-opacity="0.55" />
      </linearGradient>
    </defs>
    <circle cx="48" cy="48" r="42" stroke="url(#issuesEmptyG)" stroke-width="1.5" fill="rgba(91,110,232,0.04)" />
    <circle cx="48" cy="48" r="14" stroke="url(#issuesEmptyG)" stroke-width="2" fill="none" />
    <path d="M48 30v8M48 58v8M30 48h8M58 48h8" stroke="url(#issuesEmptyG)" stroke-width="2" stroke-linecap="round" />
  </svg>
);

// Detect AI Triage comments by the marker the triage helper writes.
function isAiTriageComment(body: string | null | undefined): boolean {
  if (!body) return false;
  return body.includes(ISSUE_TRIAGE_MARKER) || body.trimStart().startsWith("## AI Triage");
}

// Helper to resolve repo from :owner/:repo params
async function resolveRepo(ownerName: string, repoName: string) {
  const [owner] = await db
    .select()
    .from(users)
    .where(eq(users.username, ownerName))
    .limit(1);
  if (!owner) return null;

  const [repo] = await db
    .select()
    .from(repositories)
    .where(
      and(eq(repositories.ownerId, owner.id), eq(repositories.name, repoName))
    )
    .limit(1);
  if (!repo) return null;

  return { owner, repo };
}

// Bulk issue operations (close / reopen multiple issues at once)
issueRoutes.post("/:owner/:repo/issues/bulk", requireAuth, requireRepoAccess("write"), async (c) => {
  const { owner: ownerName, repo: repoName } = c.req.param();
  const user = c.get("user")!;
  const body = await c.req.parseBody();
  const action = String(body.action || "");
  const rawNumbers = body["numbers[]"];
  const numbers = (Array.isArray(rawNumbers) ? rawNumbers : rawNumbers ? [rawNumbers] : [])
    .map(n => parseInt(String(n), 10))
    .filter(n => !isNaN(n) && n > 0);

  if (!numbers.length || !["close","reopen"].includes(action)) {
    return c.redirect(`/${ownerName}/${repoName}/issues?error=${encodeURIComponent("Invalid bulk action")}`);
  }

  const resolved = await resolveRepo(ownerName, repoName);
  if (!resolved) return c.redirect(`/${ownerName}/${repoName}/issues`);

  const newState = action === "close" ? "closed" : "open";
  await db.update(issues)
    .set({ state: newState, closedAt: action === "close" ? new Date() : null, updatedAt: new Date() })
    .where(and(eq(issues.repositoryId, resolved.repo.id), inArray(issues.number, numbers)));

  const stateParam = action === "close" ? "open" : "closed"; // stay on current view
  return c.redirect(`/${ownerName}/${repoName}/issues?state=${stateParam === "closed" ? "closed" : "open"}&success=${encodeURIComponent(`${numbers.length} issue(s) ${action}d`)}`);
});

// Issue list
issueRoutes.get("/:owner/:repo/issues", softAuth, requireRepoAccess("read"), async (c) => {
  const { owner: ownerName, repo: repoName } = c.req.param();
  const user = c.get("user");
  const state = c.req.query("state") || "open";
  const searchQ = (c.req.query("q") || "").trim();
  const labelFilter = (c.req.query("label") || "").trim();
  const milestoneFilter = (c.req.query("milestone") || "").trim();
  const sort = (c.req.query("sort") || "newest").trim();
  // Bounded pagination — unbounded selects ran a full table scan + O(n)
  // sort on every page load; with 10k+ issues the request would hang.
  const perPage = Math.min(100, Math.max(1, Number(c.req.query("per_page")) || 50));
  const page = Math.max(1, Number(c.req.query("page")) || 1);
  const offset = (page - 1) * perPage;

  // ── Loading skeleton (flag-gated) ──
  // Renders an SSR'd row skeleton when `?skeleton=1` is set. Lets the
  // user see the shape of the issue list before the DB count + select
  // resolve. Behind a flag — we don't ship flashes.
  if (c.req.query("skeleton") === "1") {
    return c.html(
      <Layout title={`Issues — ${ownerName}/${repoName}`} user={user}>
        <IssuesStyle />
        <RepoHeader owner={ownerName} repo={repoName} />
        <IssueNav owner={ownerName} repo={repoName} active="issues" />
        <style
          dangerouslySetInnerHTML={{
            __html: `
              .issues-skel { background: linear-gradient(90deg, var(--bg-secondary) 0%, var(--bg-elevated) 50%, var(--bg-secondary) 100%); background-size: 200% 100%; animation: issuesSkelShimmer 1.4s infinite; border-radius: 6px; display: block; }
              @keyframes issuesSkelShimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
              @media (prefers-reduced-motion: reduce) { .issues-skel { animation: none; } }
              .issues-skel-hero { height: 168px; border-radius: 16px; margin: 4px 0 24px; }
              .issues-skel-toolbar { height: 44px; width: 240px; border-radius: 9999px; margin-bottom: 16px; }
              .issues-skel-list { display: flex; flex-direction: column; gap: 8px; }
              .issues-skel-row { height: 62px; border-radius: 10px; }
            `,
          }}
        />
        <div class="issues-skel issues-skel-hero" aria-hidden="true" />
        <div class="issues-skel issues-skel-toolbar" aria-hidden="true" />
        <div class="issues-skel-list" aria-hidden="true">
          {Array.from({ length: 8 }).map(() => (
            <div class="issues-skel issues-skel-row" />
          ))}
        </div>
        <span style="position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);border:0" role="status" aria-live="polite">
          Loading issues for {ownerName}/{repoName}…
        </span>
      </Layout>
    );
  }

  const resolved = await resolveRepo(ownerName, repoName);
  if (!resolved) {
    return c.html(
      <Layout title="Not Found" user={user}>
        <EmptyState title="Repository not found" />
      </Layout>,
      404
    );
  }

  const { repo } = resolved;

  // If label filter is set, find issue IDs that have that label
  let labelFilteredIds: string[] | null = null;
  if (labelFilter) {
    const [matchedLabel] = await db
      .select({ id: labels.id })
      .from(labels)
      .where(and(eq(labels.repositoryId, repo.id), ilike(labels.name, labelFilter)))
      .limit(1);
    if (matchedLabel) {
      const rows = await db
        .select({ issueId: issueLabels.issueId })
        .from(issueLabels)
        .where(eq(issueLabels.labelId, matchedLabel.id));
      labelFilteredIds = rows.map((r) => r.issueId);
    } else {
      labelFilteredIds = []; // no matches
    }
  }

  // If milestone filter is set, resolve the milestone ID
  let milestoneFilterId: string | null = null;
  if (milestoneFilter) {
    const [matchedMs] = await db
      .select({ id: milestones.id })
      .from(milestones)
      .where(and(eq(milestones.repositoryId, repo.id), eq(milestones.id, milestoneFilter)))
      .limit(1);
    milestoneFilterId = matchedMs?.id ?? null;
  }

  const baseWhere = and(
    eq(issues.repositoryId, repo.id),
    state === "open" || state === "closed" ? eq(issues.state, state) : undefined,
    searchQ ? ilike(issues.title, `%${searchQ}%`) : undefined,
    labelFilteredIds !== null && labelFilteredIds.length > 0
      ? inArray(issues.id, labelFilteredIds)
      : labelFilteredIds !== null && labelFilteredIds.length === 0
        ? sql`false`
        : undefined,
    milestoneFilterId ? eq(issues.milestoneId, milestoneFilterId) : undefined
  );

  const issueList = await db
    .select({
      issue: issues,
      author: { username: users.username },
    })
    .from(issues)
    .innerJoin(users, eq(issues.authorId, users.id))
    .where(baseWhere)
    .orderBy(
      sort === "oldest" ? asc(issues.createdAt)
        : sort === "updated" ? desc(issues.updatedAt)
        : desc(issues.createdAt) // newest (default)
    )
    .limit(perPage)
    .offset(offset);

  // Batch-load sub-issue counts for epics in this list page
  const issueIds = issueList.map((r) => r.issue.id);
  const subCountMap = new Map<string, number>();
  const parentNumberMap = new Map<string, number>(); // childIssueId → parentIssueNumber
  if (issueIds.length > 0) {
    const [subRows, parentRows] = await Promise.all([
      // Count children per parent (to show "N sub-issues" on epics)
      db
        .select({
          parentId: issues.parentIssueId,
          cnt: sql<number>`count(*)::int`,
        })
        .from(issues)
        .where(
          and(
            inArray(issues.parentIssueId, issueIds),
            eq(issues.repositoryId, repo.id)
          )
        )
        .groupBy(issues.parentIssueId),
      // Resolve parent numbers for children (to show "Part of #N")
      issueList
        .filter((r) => r.issue.parentIssueId !== null)
        .length > 0
        ? db
            .select({ id: issues.id, number: issues.number })
            .from(issues)
            .where(
              inArray(
                issues.id,
                issueList
                  .filter((r) => r.issue.parentIssueId !== null)
                  .map((r) => r.issue.parentIssueId as string)
              )
            )
        : Promise.resolve([]),
    ]);
    subRows.forEach((r) => {
      if (r.parentId) subCountMap.set(r.parentId, Number(r.cnt));
    });
    parentRows.forEach((p) => parentNumberMap.set(p.id, p.number));
  }

  // Count open/closed
  const [counts] = await db
    .select({
      open: sql<number>`count(*) filter (where ${issues.state} = 'open')`,
      closed: sql<number>`count(*) filter (where ${issues.state} = 'closed')`,
    })
    .from(issues)
    .where(eq(issues.repositoryId, repo.id));

  // Count open milestones for the "N Milestones" link
  const [milestoneCounts] = await db
    .select({
      open: sql<number>`count(*) filter (where ${milestones.state} = 'open')::int`,
    })
    .from(milestones)
    .where(eq(milestones.repositoryId, repo.id));

  const viewerIsOwnerOnList = !!(user && user.id === resolved.owner.id);
  const pendingCountList = viewerIsOwnerOnList
    ? await countPendingForRepo(repo.id)
    : 0;

  return c.html(
    <Layout title={`Issues — ${ownerName}/${repoName}`} user={user}>
      <IssuesStyle />
      <RepoHeader owner={ownerName} repo={repoName} />
      <IssueNav owner={ownerName} repo={repoName} active="issues" />
      <PendingCommentsBanner
        owner={ownerName}
        repo={repoName}
        count={pendingCountList}
      />
      <section class="issues-hero">
        <div class="issues-hero-bg" aria-hidden="true">
          <div class="issues-hero-orb" />
        </div>
        <div class="issues-hero-inner">
          <div class="issues-hero-text">
            <div class="issues-hero-eyebrow">
              Issue tracker \u00B7{" "}
              <span class="issues-hero-repo">
                {ownerName}/{repoName}
              </span>
            </div>
            <h1 class="issues-hero-title">
              Track <span class="gradient-text">what matters</span>.
            </h1>
            <p class="issues-hero-sub">
              {(Number(counts?.open ?? 0) + Number(counts?.closed ?? 0)) === 0
                ? "Bugs, ideas, and roadmap items live here. Open the first one and AI Triage will draft a starter classification within seconds."
                : `${Number(counts?.open ?? 0)} open \u00B7 ${Number(counts?.closed ?? 0)} closed. AI Triage suggests labels, priority, and possible duplicates the moment an issue is filed.`}
            </p>
          </div>
          <div class="issues-hero-actions">
            {user && (
              <a
                href={`/${ownerName}/${repoName}/issues/new`}
                class="btn btn-primary"
              >
                + New issue
              </a>
            )}
            <a
              href={`/${ownerName}/${repoName}/milestones`}
              class="btn"
              title="View milestones for this repository"
            >
              Milestones
              {Number(milestoneCounts?.open ?? 0) > 0 && (
                <span style="margin-left:5px;font-size:11.5px;background:rgba(91,110,232,0.18);color:#a78bfa;padding:1px 7px;border-radius:9999px">
                  {Number(milestoneCounts?.open ?? 0)}
                </span>
              )}
            </a>
            <a href={`/${ownerName}/${repoName}`} class="btn">
              Back to code
            </a>
          </div>
        </div>
      </section>

      <div class="issues-toolbar">
        <div class="issues-filters" role="tablist" aria-label="Issue state filter">
          <a
            class={`issues-filter${state === "open" ? " is-active" : ""}`}
            href={`/${ownerName}/${repoName}/issues?state=open`}
            role="tab"
            aria-selected={state === "open" ? "true" : "false"}
          >
            <span aria-hidden="true">{"\u25CB"}</span>
            <span>Open</span>
            <span class="issues-filter-count">{Number(counts?.open ?? 0)}</span>
          </a>
          <a
            class={`issues-filter${state === "closed" ? " is-active" : ""}`}
            href={`/${ownerName}/${repoName}/issues?state=closed`}
            role="tab"
            aria-selected={state === "closed" ? "true" : "false"}
          >
            <span aria-hidden="true">{"\u2713"}</span>
            <span>Closed</span>
            <span class="issues-filter-count">{Number(counts?.closed ?? 0)}</span>
          </a>
        </div>
        <form method="get" action={`/${ownerName}/${repoName}/issues`} class="issues-search-form">
          <input type="hidden" name="state" value={state} />
          <input
            type="search"
            name="q"
            value={searchQ}
            placeholder="Search issues\u2026"
            class="issues-search-input"
            aria-label="Search issues by title"
          />
          {labelFilter && <input type="hidden" name="label" value={labelFilter} />}
          <button type="submit" class="issues-search-btn" aria-label="Search">
            <svg viewBox="0 0 16 16" width="14" height="14" fill="currentColor" aria-hidden="true">
              <path d="M10.68 11.74a6 6 0 0 1-7.922-8.982 6 6 0 0 1 8.982 7.922l3.04 3.04a.749.749 0 0 1-.326 1.275.749.749 0 0 1-.734-.215ZM11.5 7a4.499 4.499 0 1 0-8.997 0A4.499 4.499 0 0 0 11.5 7Z" />
            </svg>
          </button>
        </form>
      </div>
      {(searchQ || labelFilter) && (
        <div class="issues-filter-banner">
          Filtering{searchQ ? <> by "<strong>{searchQ}</strong>"</> : null}
          {labelFilter ? <> label: <span class="issues-label-badge">{labelFilter}</span></> : null}
          {" \u00B7 "}
          <a href={`/${ownerName}/${repoName}/issues?state=${state}`} class="issues-filter-clear">Clear filters</a>
        </div>
      )}

      <div class="issues-sort-row">
        <span class="issues-sort-label">Sort:</span>
        {(["newest", "oldest", "updated"] as const).map((s) => (
          <a
            href={`/${ownerName}/${repoName}/issues?state=${state}&sort=${s}${searchQ ? `&q=${encodeURIComponent(searchQ)}` : ""}${labelFilter ? `&label=${encodeURIComponent(labelFilter)}` : ""}`}
            class={`issues-sort-opt${sort === s ? " is-active" : ""}`}
          >
            {s === "newest" ? "Newest" : s === "oldest" ? "Oldest" : "Recently updated"}
          </a>
        ))}
      </div>

      {issueList.length === 0 ? (
        <div class="issues-empty">
          <IssuesEmptySvg />
          <h2 class="issues-empty-title">
            {state === "closed"
              ? "No closed issues yet"
              : (Number(counts?.open ?? 0) + Number(counts?.closed ?? 0)) === 0
                ? "No issues \u2014 yet"
                : "Nothing open right now"}
          </h2>
          <p class="issues-empty-sub">
            {state === "closed"
              ? "Closed issues will show up here once the team starts shipping fixes."
              : (Number(counts?.open ?? 0) + Number(counts?.closed ?? 0)) === 0
                ? "File the first one and AI Triage will draft a starter classification \u2014 labels, priority, and a duplicate sweep \u2014 within seconds."
                : "All caught up. New filings will appear here, with AI Triage suggestions auto-posted to every thread."}
          </p>
          <div class="issues-empty-cta">
            {user && state !== "closed" && (
              <a
                href={`/${ownerName}/${repoName}/issues/new`}
                class="btn btn-primary"
              >
                + Open the first issue
              </a>
            )}
            {state === "closed" && (
              <a
                href={`/${ownerName}/${repoName}/issues?state=open`}
                class="btn"
              >
                View open issues
              </a>
            )}
          </div>
        </div>
      ) : (
        <form id="bulk-form" method="post" action={`/${ownerName}/${repoName}/issues/bulk`}>
          <input type="hidden" name="action" id="bulk-action" value="" />
          <div class="bulk-bar" id="bulk-bar" aria-hidden="true">
            <span class="bulk-bar-count" id="bulk-bar-count">0 selected</span>
            <button type="button" class="bulk-bar-btn" onclick="bulkSubmit('close')">Close selected</button>
            <button type="button" class="bulk-bar-btn" onclick="bulkSubmit('reopen')">Reopen selected</button>
            <button type="button" class="bulk-bar-clear" onclick="bulkClear()">Clear</button>
          </div>
          <ul class="issues-list">
            {issueList.map(({ issue, author }) => (
              <li class="issues-row">
                <input type="checkbox" name="numbers[]" value={String(issue.number)} class="bulk-cb" aria-label={`Select issue #${issue.number}`} />
                <div
                  class={`issues-row-icon ${issue.state === "open" ? "is-open" : "is-closed"}`}
                  aria-hidden="true"
                  title={issue.state === "open" ? "Open" : "Closed"}
                >
                  {issue.state === "open" ? "\u25CB" : "\u2713"}
                </div>
                <div class="issues-row-main">
                  <h3 class="issues-row-title">
                    <a href={`/${ownerName}/${repoName}/issues/${issue.number}`}>
                      {issue.title}
                    </a>
                    {subCountMap.has(issue.id) && (
                      <span class="issues-tag-epic" title={`Epic with ${subCountMap.get(issue.id)} sub-issue${subCountMap.get(issue.id) === 1 ? "" : "s"}`}>
                        📌 Epic · {subCountMap.get(issue.id)}
                      </span>
                    )}
                    {issue.parentIssueId && parentNumberMap.has(issue.parentIssueId) && (
                      <span class="issues-tag-child" title={`Sub-issue of #${parentNumberMap.get(issue.parentIssueId)}`}>
                        ↳ #{parentNumberMap.get(issue.parentIssueId)}
                      </span>
                    )}
                  </h3>
                  <div class="issues-row-meta">
                    #{issue.number} opened by{" "}
                    <strong>{author.username}</strong>{" "}
                    {formatRelative(issue.createdAt)}
                  </div>
                </div>
              </li>
            ))}
          </ul>
          <script dangerouslySetInnerHTML={{ __html: `
function bulkSubmit(action){
  document.getElementById('bulk-action').value=action;
  document.getElementById('bulk-form').submit();
}
function bulkClear(){
  document.querySelectorAll('.bulk-cb').forEach(function(cb){cb.checked=false;});
  updateBulkBar();
}
function updateBulkBar(){
  var checked=document.querySelectorAll('.bulk-cb:checked').length;
  var bar=document.getElementById('bulk-bar');
  var cnt=document.getElementById('bulk-bar-count');
  if(bar){bar.style.display=checked>0?'flex':'none';}
  if(cnt){cnt.textContent=checked+' selected';}
}
document.addEventListener('change',function(e){if(e.target&&e.target.classList.contains('bulk-cb'))updateBulkBar();});
` }} />
        </form>
      )}
    </Layout>
  );
});

// New issue form
issueRoutes.get(
  "/:owner/:repo/issues/new",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const user = c.get("user")!;
    const error = c.req.query("error");
    const template = await loadIssueTemplate(ownerName, repoName);

    // Load open milestones for the dropdown
    const resolved = await resolveRepo(ownerName, repoName);
    const openMilestones = resolved
      ? await db
          .select({ id: milestones.id, title: milestones.title })
          .from(milestones)
          .where(and(eq(milestones.repositoryId, resolved.repo.id), eq(milestones.state, "open")))
          .orderBy(milestones.title)
      : [];

    return c.html(
      <Layout title={`New issue — ${ownerName}/${repoName}`} user={user}>
        <IssuesStyle />
        <RepoHeader owner={ownerName} repo={repoName} />
        <IssueNav owner={ownerName} repo={repoName} active="issues" />
        <Container maxWidth={800}>
          <section class="issues-hero" style="margin-top:4px">
            <div class="issues-hero-bg" aria-hidden="true">
              <div class="issues-hero-orb" />
            </div>
            <div class="issues-hero-inner">
              <div class="issues-hero-text">
                <div class="issues-hero-eyebrow">
                  New issue ·{" "}
                  <span class="issues-hero-repo">
                    {ownerName}/{repoName}
                  </span>
                </div>
                <h1 class="issues-hero-title">
                  File <span class="gradient-text">it cleanly</span>.
                </h1>
                <p class="issues-hero-sub">
                  AI Triage will read the body the moment you submit and post
                  suggested labels, priority, and possible duplicates within
                  seconds. You stay in control — nothing is applied.
                </p>
              </div>
            </div>
          </section>
          {error && (
            <Alert variant="error">{decodeURIComponent(error)}</Alert>
          )}
          <Form method="post" action={`/${ownerName}/${repoName}/issues/new`}>
            <FormGroup>
              <Input
                type="text"
                name="title"
                required
                placeholder="Title"
                style="font-size:16px;padding:10px 14px"
                aria-label="Issue title"
              />
            </FormGroup>
            <FormGroup>
              <TextArea
                name="body"
                rows={12}
                placeholder="Leave a comment... (Markdown supported)"
                mono
              />
            </FormGroup>
            {openMilestones.length > 0 && (
              <FormGroup>
                <label
                  for="milestone_id"
                  style="display:block;font-size:13px;font-weight:600;color:var(--text);margin-bottom:6px"
                >
                  Milestone <span style="font-weight:400;color:var(--text-muted)">(optional)</span>
                </label>
                <select
                  id="milestone_id"
                  name="milestone_id"
                  style="background:var(--bg-surface);border:1px solid var(--border);border-radius:8px;color:var(--text);font-size:14px;padding:8px 12px;outline:none;width:100%;max-width:340px"
                >
                  <option value="">No milestone</option>
                  {openMilestones.map((ms) => (
                    <option value={ms.id}>{ms.title}</option>
                  ))}
                </select>
              </FormGroup>
            )}
            <Button type="submit" variant="primary">
              Submit new issue
            </Button>
          </Form>
        </Container>
      </Layout>
    );
  }
);

// Create issue
issueRoutes.post(
  "/:owner/:repo/issues/new",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const user = c.get("user")!;
    const body = await c.req.parseBody();
    const title = String(body.title || "").trim();
    const issueBody = String(body.body || "").trim();
    const milestoneIdRaw = String(body.milestone_id || "").trim() || null;

    if (!title) {
      return c.redirect(
        `/${ownerName}/${repoName}/issues/new?error=Title+is+required`
      );
    }

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}`);

    // Validate milestone belongs to this repo if provided
    let validatedMilestoneId: string | null = null;
    if (milestoneIdRaw) {
      const [msRow] = await db
        .select({ id: milestones.id })
        .from(milestones)
        .where(and(eq(milestones.id, milestoneIdRaw), eq(milestones.repositoryId, resolved.repo.id)))
        .limit(1);
      validatedMilestoneId = msRow?.id ?? null;
    }

    const [issue] = await db
      .insert(issues)
      .values({
        repositoryId: resolved.repo.id,
        authorId: user.id,
        title,
        body: issueBody || null,
        milestoneId: validatedMilestoneId,
      })
      .returning();

    // Update issue count
    await db
      .update(repositories)
      .set({ issueCount: resolved.repo.issueCount + 1 })
      .where(eq(repositories.id, resolved.repo.id));

    void fireWebhooks(resolved.repo.id, "issue", {
      action: "opened",
      number: issue.number,
      title,
    });

    // Fire-and-forget AI triage. Posts a "## AI Triage" comment with
    // suggested labels, priority, summary, and a possible-duplicate
    // callout. Suggestions only — nothing applied automatically.
    triggerIssueTriage({
      ownerName,
      repoName,
      repositoryId: resolved.repo.id,
      issueId: issue.id,
      issueNumber: issue.number,
      authorId: user.id,
      title,
      body: issueBody,
    }).catch((err) => {
      console.warn(
        `[issue-triage] triage trigger failed for issue ${issue.id}:`,
        err instanceof Error ? err.message : err
      );
    });

    return c.redirect(
      `/${ownerName}/${repoName}/issues/${issue.number}`
    );
  }
);

// View single issue
issueRoutes.get("/:owner/:repo/issues/:number", softAuth, requireRepoAccess("read"), async (c) => {
  const { owner: ownerName, repo: repoName } = c.req.param();
  const issueNum = parseInt(c.req.param("number"), 10);
  const user = c.get("user");

  const resolved = await resolveRepo(ownerName, repoName);
  if (!resolved) {
    return c.html(
      <Layout title="Not Found" user={user}>
        <EmptyState title="Not found" />
      </Layout>,
      404
    );
  }

  const [issue] = await db
    .select()
    .from(issues)
    .where(
      and(
        eq(issues.repositoryId, resolved.repo.id),
        eq(issues.number, issueNum)
      )
    )
    .limit(1);

  if (!issue) {
    return c.html(
      <Layout title="Not Found" user={user}>
        <EmptyState title="Issue not found" />
      </Layout>,
      404
    );
  }

  const [author] = await db
    .select()
    .from(users)
    .where(eq(users.id, issue.authorId))
    .limit(1);

  // Get comments. We pull every row and filter by moderation_status +
  // viewer identity client-side (in the JSX below) so a moderator/owner
  // sees them all while non-author viewers only ever see 'approved'.
  const allComments = await db
    .select({
      comment: issueComments,
      author: { id: users.id, username: users.username },
    })
    .from(issueComments)
    .innerJoin(users, eq(issueComments.authorId, users.id))
    .where(eq(issueComments.issueId, issue.id))
    .orderBy(asc(issueComments.createdAt));

  const viewerIsOwner = !!(user && user.id === resolved.owner.id);
  const comments = allComments.filter(({ comment, author: cAuthor }) => {
    // Owner always sees everything (so they can spot conversations going
    // sideways even before they hit the queue page).
    if (viewerIsOwner) return true;
    if (comment.moderationStatus === "approved") return true;
    // The comment's own author sees their pending comment so they know
    // it landed (with an "Awaiting approval" badge in the render below).
    if (user && cAuthor.id === user.id && comment.moderationStatus === "pending") {
      return true;
    }
    return false;
  });

  // Pending banner — when the viewer is the repo owner, show a strip at
  // the top of the page nudging them to the moderation queue. Inline on
  // this page because RepoNav is locked (see CLAUDE.md / build bible).
  const pendingCount = viewerIsOwner
    ? await countPendingForRepo(resolved.repo.id)
    : 0;

  // Sub-issues / epics — load parent issue (if this is a child) and
  // any child issues (if this is an epic), in parallel with reactions.
  const [parentIssueRow, subIssueRows] = await Promise.all([
    issue.parentIssueId
      ? db
          .select({ id: issues.id, number: issues.number, title: issues.title, state: issues.state })
          .from(issues)
          .where(eq(issues.id, issue.parentIssueId))
          .limit(1)
          .then((r) => r[0] ?? null)
      : Promise.resolve(null),
    db
      .select({
        id: issues.id,
        number: issues.number,
        title: issues.title,
        state: issues.state,
        authorUsername: users.username,
      })
      .from(issues)
      .innerJoin(users, eq(issues.authorId, users.id))
      .where(and(eq(issues.parentIssueId, issue.id), eq(issues.repositoryId, resolved.repo.id)))
      .orderBy(asc(issues.number)),
  ]);

  // Load reactions for the issue + each comment in parallel.
  const [issueReactions, ...commentReactions] = await Promise.all([
    summariseReactions("issue", issue.id, user?.id),
    ...comments.map((row) =>
      summariseReactions("issue_comment", row.comment.id, user?.id)
    ),
  ]);

  const canManage =
    user &&
    (user.id === resolved.owner.id || user.id === issue.authorId);
  const info = c.req.query("info");

  // Labels attached to this issue.
  const issueDetailLabels = await db
    .select({ id: labels.id, name: labels.name, color: labels.color })
    .from(issueLabels)
    .innerJoin(labels, eq(issueLabels.labelId, labels.id))
    .where(eq(issueLabels.issueId, issue.id));

  // Milestone for this issue (if any).
  const issueMilestone = issue.milestoneId
    ? await db
        .select({ id: milestones.id, title: milestones.title })
        .from(milestones)
        .where(eq(milestones.id, issue.milestoneId))
        .limit(1)
        .then((rows) => rows[0] ?? null)
    : null;

  // Linked PRs — find PRs in this repo whose title or body reference this issue number.
  const issueRefPattern = `%#${issue.number}%`;
  const linkedPrs = await db
    .select({
      number: pullRequests.number,
      title: pullRequests.title,
      state: pullRequests.state,
      isDraft: pullRequests.isDraft,
    })
    .from(pullRequests)
    .where(
      and(
        eq(pullRequests.repositoryId, resolved.repo.id),
        or(
          ilike(pullRequests.title, issueRefPattern),
          ilike(pullRequests.body, issueRefPattern),
        )
      )
    )
    .orderBy(desc(pullRequests.createdAt))
    .limit(8);

  return c.html(
    <Layout
      title={`${issue.title} #${issue.number} — ${ownerName}/${repoName}`}
      user={user}
    >
      <IssuesStyle />
      <RepoHeader owner={ownerName} repo={repoName} />
      <IssueNav owner={ownerName} repo={repoName} active="issues" />
      <PendingCommentsBanner
        owner={ownerName}
        repo={repoName}
        count={pendingCount}
      />
      <div
        id="live-comment-banner"
        class="alert"
        style="display:none;margin:12px 0;padding:10px 14px;border-radius:6px;background:var(--accent);color:var(--bg);font-size:14px"
      >
        <strong class="js-live-count">0</strong> new comment(s) —{" "}
        <a class="js-live-link" href="#" style="color:inherit;text-decoration:underline">
          reload to view
        </a>
      </div>
      <script
        dangerouslySetInnerHTML={{
          __html: liveCommentBannerScript({
            topic: `repo:${resolved.repo.id}:issue:${issue.number}`,
            bannerElementId: "live-comment-banner",
          }),
        }}
      />
      <script dangerouslySetInnerHTML={{ __html: mentionAutocompleteScript() }} />
      <script dangerouslySetInnerHTML={{ __html: markdownPreviewScript() }} />
      <script dangerouslySetInnerHTML={{ __html: ctrlEnterSubmitScript() + codeBlockCopyScript() }} />
      <div class="issue-detail">
        {info && (
          <div class="issues-info-banner">
            {decodeURIComponent(info)}
          </div>
        )}

        <section class="issues-detail-hero">
          {parentIssueRow && (
            <div class="issues-epic-crumb">
              <span>📌 Part of epic</span>
              <a href={`/${ownerName}/${repoName}/issues/${parentIssueRow.number}`}>
                #{parentIssueRow.number} — {parentIssueRow.title}
              </a>
            </div>
          )}
          <h1 class="issues-detail-title">
            {issue.title}
            <span class="issues-detail-number">#{issue.number}</span>
          </h1>
          <div class="issues-detail-attr">
            <span
              class={`issues-state-pill ${issue.state === "open" ? "is-open" : "is-closed"}`}
              title={issue.state === "open" ? "Open" : "Closed"}
            >
              <span aria-hidden="true">
                {issue.state === "open" ? "\u25CB" : "\u2713"}
              </span>
              {issue.state === "open" ? "Open" : "Closed"}
            </span>
            <span>
              <strong>{author?.username || "unknown"}</strong> opened this
              issue {formatRelative(issue.createdAt)}
            </span>
            <span class="issues-detail-spacer" />
            {issue.state === "open" && user && user.id === resolved.owner.id && (
              <a
                href={`/${ownerName}/${repoName}/spec?fromIssue=${issue.number}`}
                class="btn btn-primary"
                style="font-size:13px;padding:6px 12px"
                title="Generate a draft pull request from this issue using Claude"
              >
                Build with AI
              </a>
            )}
            {issue.state === "open" && user && isAiAvailable() && (
              <form
                method="post"
                action={`/${ownerName}/${repoName}/issues/${issue.number}/ship`}
                style="display:inline"
                title="Let AI implement this feature automatically"
              >
                <button
                  type="submit"
                  class="btn btn-primary"
                  style="font-size:13px;padding:6px 12px;background:linear-gradient(135deg,#5b6ee8,#5f8fa0);border:none;cursor:pointer"
                  onclick="return confirm('Ship Agent will read the codebase, write code, and open a PR automatically. Review the PR before merging. Continue?')"
                >
                  Ship It
                </button>
              </form>
            )}
            {issue.state === "open" && user && (
              <details class="issue-branch-dropdown" style="position:relative;display:inline-block">
                <summary
                  class="btn"
                  style="font-size:13px;padding:6px 12px;cursor:pointer;list-style:none"
                  title="Create a new branch for this issue"
                >
                  Create branch
                </summary>
                <div style="position:absolute;right:0;top:calc(100% + 4px);background:var(--bg-elevated);border:1px solid var(--border);border-radius:8px;padding:12px 14px;min-width:280px;z-index:100;box-shadow:0 4px 12px rgba(0,0,0,.3)">
                  <form method="post" action={`/${ownerName}/${repoName}/issues/${issue.number}/branch`}>
                    <label style="display:block;font-size:12px;color:var(--fg-muted);margin-bottom:4px">Branch name</label>
                    <input
                      type="text"
                      name="branchName"
                      class="input"
                      style="width:100%;font-size:13px;padding:5px 8px;margin-bottom:8px"
                      value={`issue-${issue.number}-${issue.title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 40)}`}
                      pattern="[a-zA-Z0-9._\\-/]+"
                      required
                    />
                    <button type="submit" class="btn btn-primary" style="width:100%;font-size:13px">
                      Create branch
                    </button>
                  </form>
                </div>
              </details>
            )}
          </div>
        </section>

        <div class="issue-detail-layout">
        <div class="issue-detail-main">

        {subIssueRows.length > 0 && (
          <div class="issues-sub-panel">
            <div class="issues-sub-panel-head">
              <span>Sub-issues</span>
              <span style="font-size:11px;background:var(--bg-inset);border:1px solid var(--border);border-radius:10px;padding:1px 8px;font-weight:500;letter-spacing:0">
                {subIssueRows.filter((s) => s.state === "open").length}/{subIssueRows.length} open
              </span>
            </div>
            {subIssueRows.map((sub) => (
              <div class="issues-sub-row" key={sub.id}>
                <span class={`issues-sub-row-icon ${sub.state === "open" ? "is-open" : "is-closed"}`}>
                  {sub.state === "open" ? "○" : "✓"}
                </span>
                <span class="issues-sub-row-title">
                  <a href={`/${ownerName}/${repoName}/issues/${sub.number}`}>{sub.title}</a>
                </span>
                <span class="issues-sub-row-author">{sub.authorUsername}</span>
                <span class="issues-sub-row-num">#{sub.number}</span>
              </div>
            ))}
          </div>
        )}

        <div class="issues-thread">
          {issue.body && (
            <article class="issues-comment">
              <header class="issues-comment-header">
                <strong>{author?.username || "unknown"}</strong>
                <span class="issues-comment-author-pill">Author</span>
                <span>commented {formatRelative(issue.createdAt)}</span>
              </header>
              <div class="issues-comment-body">
                <div
                  class="markdown-body"
                  dangerouslySetInnerHTML={{ __html: renderMarkdown(issue.body) }}
                />
              </div>
            </article>
          )}

          {comments.map(({ comment, author: commentAuthor }) => {
            const isAi = isAiTriageComment(comment.body);
            const isPending = comment.moderationStatus === "pending";
            return (
              <article class={`issues-comment${isAi ? " is-ai" : ""}${isPending ? " modq-comment-pending" : ""}`}>
                <header class="issues-comment-header">
                  <strong>{commentAuthor.username}</strong>
                  {commentAuthor.username === BOT_USERNAME && (
                    <span class="issues-bot-badge">&#x1F916; bot</span>
                  )}
                  {isAi ? (
                    <span class="issues-ai-badge" title="Generated by Gluecron AI Triage">
                      AI Review
                    </span>
                  ) : null}
                  {isPending ? (
                    <span class="modq-pending-badge" title="This comment is awaiting the repository owner's approval — only you and the owner can see it.">
                      Awaiting approval
                    </span>
                  ) : null}
                  <span>commented {formatRelative(comment.createdAt)}</span>
                </header>
                <div class="issues-comment-body">
                  <div
                    class="markdown-body"
                    dangerouslySetInnerHTML={{
                      __html: renderMarkdown(comment.body),
                    }}
                  />
                </div>
              </article>
            );
          })}
        </div>

        {linkedPrs.length > 0 && (
          <div class="iss-linked-prs">
            <div class="iss-linked-prs-head">
              <span>Linked pull requests</span>
              <span>{linkedPrs.length}</span>
            </div>
            {linkedPrs.map((lpr) => {
              const prState = lpr.isDraft ? "draft" : lpr.state;
              const prIcon = prState === "merged" ? "⮬" : prState === "closed" ? "✕" : prState === "draft" ? "◌" : "○";
              return (
                <a
                  href={`/${ownerName}/${repoName}/pulls/${lpr.number}`}
                  class="iss-linked-pr-row"
                >
                  <span class={`iss-linked-pr-icon is-${prState}`} aria-hidden="true">{prIcon}</span>
                  <span class="iss-linked-pr-title">{lpr.title}</span>
                  <span class="iss-linked-pr-num">#{lpr.number}</span>
                  <span class={`iss-linked-pr-state is-${prState}`}>{prState}</span>
                </a>
              );
            })}
          </div>
        )}

        {user && (
          <form
            class="issues-composer"
            method="post"
            action={`/${ownerName}/${repoName}/issues/${issue.number}/comment`}
          >
            <div class="issues-composer-header">
              <span class="issues-composer-tag">Add a comment</span>
              <span class="issues-composer-hint">
                <a
                  href="https://docs.github.com/en/get-started/writing-on-github"
                  target="_blank"
                  rel="noopener noreferrer"
                  title="Markdown supported: **bold**, _italic_, `code`, links, lists, > quotes"
                >
                  Markdown supported
                </a>
              </span>
            </div>
            <textarea
              name="body"
              rows={6}
              required
              data-md-preview=""
              placeholder="Leave a comment... fenced code blocks, lists, links, and quotes all supported."
            />
            <div class="issues-composer-actions">
              <button type="submit" class="btn btn-primary">
                Comment
              </button>
              {canManage && (
                <button
                  type="submit"
                  formaction={`/${ownerName}/${repoName}/issues/${issue.number}/${issue.state === "open" ? "close" : "reopen"}`}
                  class={`btn ${issue.state === "open" ? "btn-danger" : ""}`}
                >
                  {issue.state === "open" ? "Close issue" : "Reopen issue"}
                </button>
              )}
              {canManage && issue.state === "open" && (
                <button
                  type="submit"
                  formaction={`/${ownerName}/${repoName}/issues/${issue.number}/ai-retriage`}
                  formnovalidate
                  class="btn"
                  title="Re-run AI triage. Posts a fresh suggestions comment (use after editing the issue body)."
                >
                  Re-run AI triage
                </button>
              )}
            </div>
          </form>
        )}
        </div>{/* /issue-detail-main */}

        {/* Metadata sidebar — Labels, Assignees, Milestone */}
        <aside class="issue-meta-sidebar">
          {/* Labels */}
          <div class="issue-meta-section">
            <div class="issue-meta-label">Labels</div>
            {issueDetailLabels.length === 0 ? (
              <span class="issue-meta-empty">None yet</span>
            ) : (
              <div class="issue-meta-labels">
                {issueDetailLabels.map((lbl) => {
                  // Compute luminance from hex color to choose dark/light text
                  const hex = lbl.color.replace("#", "");
                  const r = parseInt(hex.slice(0, 2), 16) / 255;
                  const g = parseInt(hex.slice(2, 4), 16) / 255;
                  const b = parseInt(hex.slice(4, 6), 16) / 255;
                  const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
                  const textColor = lum > 0.45 ? "#1a1a1a" : "#ffffff";
                  return (
                    <span
                      class="issue-meta-label-pill"
                      style={`background:${lbl.color};color:${textColor};border-color:${lbl.color}`}
                    >
                      {lbl.name}
                    </span>
                  );
                })}
              </div>
            )}
          </div>

          {/* Assignees — field not yet in schema; placeholder */}
          <div class="issue-meta-section">
            <div class="issue-meta-label">Assignees</div>
            <span class="issue-meta-empty">No one assigned</span>
          </div>

          {/* Milestone */}
          <div class="issue-meta-section">
            <div class="issue-meta-label">Milestone</div>
            {issueMilestone ? (
              <a
                href={`/${ownerName}/${repoName}/milestones/${issueMilestone.id}`}
                class="issue-meta-milestone-link"
              >
                &#x25CE; {issueMilestone.title}
              </a>
            ) : (
              <span class="issue-meta-empty">No milestone</span>
            )}
          </div>
          {/* Epic / parent issue */}
          {viewerIsOwner && (
            <div class="issue-meta-section">
              <div class="issue-meta-label">Epic (parent issue)</div>
              {parentIssueRow ? (
                <div style="font-size:12px;color:var(--text-secondary);margin-bottom:6px">
                  <a href={`/${ownerName}/${repoName}/issues/${parentIssueRow.number}`} style="color:var(--accent);text-decoration:none">
                    #{parentIssueRow.number} {parentIssueRow.title.slice(0, 40)}{parentIssueRow.title.length > 40 ? "…" : ""}
                  </a>
                </div>
              ) : (
                <span class="issue-meta-empty">None</span>
              )}
              <form
                method="post"
                action={`/${ownerName}/${repoName}/issues/${issue.number}/set-parent`}
                style="display:flex;gap:6px;margin-top:6px"
              >
                <input
                  type="number"
                  name="parent_number"
                  placeholder={parentIssueRow ? "Clear (enter 0)" : "Issue #"}
                  style="width:100%;padding:4px 8px;font-size:12px;border:1px solid var(--border);border-radius:6px;background:var(--bg-inset);color:var(--text)"
                  min="0"
                />
                <button type="submit" class="btn" style="font-size:12px;padding:4px 10px;white-space:nowrap">
                  Set
                </button>
              </form>
            </div>
          )}
        </aside>
        </div>{/* /issue-detail-layout */}
      </div>
      {/* Issue keyboard hints bar */}
      <div class="kbd-hints" aria-label="Keyboard shortcuts for this issue">
        <kbd>c</kbd> comment &middot; <kbd>e</kbd> edit title &middot; <kbd>x</kbd> close/reopen &middot; <kbd>?</kbd> shortcuts
      </div>
      <style dangerouslySetInnerHTML={{ __html: `
        .kbd-hints {
          position: fixed;
          bottom: 0;
          left: 0;
          right: 0;
          z-index: 90;
          padding: 6px 24px;
          background: var(--bg-secondary);
          border-top: 1px solid var(--border);
          font-size: 12px;
          color: var(--text-muted);
          display: flex;
          align-items: center;
          gap: 8px;
          flex-wrap: wrap;
        }
        .kbd-hints kbd {
          font-family: var(--font-mono);
          font-size: 10px;
          background: var(--bg-elevated);
          border: 1px solid var(--border);
          border-bottom-width: 2px;
          border-radius: 4px;
          padding: 1px 5px;
          color: var(--text);
          line-height: 1.5;
        }
        main { padding-bottom: 40px; }
      ` }} />
      {/* Repo context commands for command palette */}
      <script
        id="cmdk-repo-context"
        dangerouslySetInnerHTML={{
          __html: `window.__CMDK_REPO_COMMANDS = ${JSON.stringify([
            { label: `New issue in ${repoName}`, href: `/${ownerName}/${repoName}/issues/new`, kw: "create add bug" },
            { label: `New pull request in ${repoName}`, href: `/${ownerName}/${repoName}/pulls/new`, kw: "pr branch merge" },
            { label: `Browse code — ${ownerName}/${repoName}`, href: `/${ownerName}/${repoName}`, kw: "files tree" },
            { label: `Issues — ${ownerName}/${repoName}`, href: `/${ownerName}/${repoName}/issues`, kw: "bugs tasks" },
            { label: `Pull requests — ${ownerName}/${repoName}`, href: `/${ownerName}/${repoName}/pulls`, kw: "prs reviews" },
          ])};`,
        }}
      />
      {/* Issue keyboard shortcuts */}
      <script dangerouslySetInnerHTML={{ __html: `
        (function(){
          function isTyping(t){
            t = t || {};
            var tag = (t.tagName || '').toLowerCase();
            return tag === 'input' || tag === 'textarea' || t.isContentEditable;
          }
          document.addEventListener('keydown', function(e){
            if (isTyping(e.target)) return;
            if (e.metaKey || e.ctrlKey || e.altKey) return;
            if (e.key === 'c') {
              e.preventDefault();
              var box = document.querySelector('textarea[name="body"]');
              if (box) { box.focus(); box.scrollIntoView({block:'center'}); }
            }
            if (e.key === 'e') {
              e.preventDefault();
              // Focus the issue title and make it editable if possible
              var titleEl = document.querySelector('.issues-title');
              if (titleEl) titleEl.scrollIntoView({block:'center'});
            }
            if (e.key === 'x') {
              e.preventDefault();
              var closeBtn = document.querySelector('button[formaction*="/close"], button[formaction*="/reopen"]');
              if (closeBtn) {
                var confirmed = window.confirm('Close/reopen this issue?');
                if (confirmed) closeBtn.click();
              }
            }
            if (e.key === 'Escape') {
              var focused = document.activeElement;
              if (focused) focused.blur();
            }
          });
        })();
      ` }} />
    </Layout>
  );
});

// Add comment.
//
// Permission model: we accept comments from ANY authenticated user (read
// access required — public repos satisfy that, private repos still need a
// collaborator row). The moderation gate in `decideInitialStatus`
// determines whether the comment is published immediately or queued for
// the repo owner's approval. See `src/lib/comment-moderation.ts` for the
// "anti-impersonation" rationale.
issueRoutes.post(
  "/:owner/:repo/issues/:number/comment",
  softAuth,
  requireAuth,
  requireRepoAccess("read"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const issueNum = parseInt(c.req.param("number"), 10);
    const user = c.get("user")!;
    const body = await c.req.parseBody();
    const commentBody = String(body.body || "").trim();

    if (!commentBody) {
      return c.redirect(
        `/${ownerName}/${repoName}/issues/${issueNum}`
      );
    }

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}`);

    const [issue] = await db
      .select()
      .from(issues)
      .where(
        and(
          eq(issues.repositoryId, resolved.repo.id),
          eq(issues.number, issueNum)
        )
      )
      .limit(1);

    if (!issue) return c.redirect(`/${ownerName}/${repoName}/issues`);

    // Decide moderation status BEFORE insert so the row lands in the right
    // initial state. Collaborators, the issue author, and trusted users
    // get 'approved'; banned users get 'rejected' (silent drop); everyone
    // else gets 'pending'.
    const decision = await decideInitialStatus({
      commenterUserId: user.id,
      repositoryId: resolved.repo.id,
      kind: "issue",
      threadId: issue.id,
    });

    const [inserted] = await db
      .insert(issueComments)
      .values({
        issueId: issue.id,
        authorId: user.id,
        body: commentBody,
        moderationStatus: decision.status,
      })
      .returning();

    // Live update only when visible. Don't leak pending/rejected via SSE.
    if (inserted && decision.status === "approved") {
      void fireWebhooks(resolved.repo.id, "issue", {
        action: "commented",
        number: issueNum,
      });
      try {
        const { publish } = await import("../lib/sse");
        publish(`repo:${resolved.repo.id}:issue:${issueNum}`, {
          event: "issue-comment",
          data: {
            issueId: issue.id,
            commentId: inserted.id,
            authorId: user.id,
            authorUsername: user.username,
          },
        });
      } catch {
        /* SSE is best-effort */
      }
      // Notify the issue author — fire-and-forget, never blocks the response.
      if (issue.authorId && issue.authorId !== user.id) {
        void import("../lib/notify").then(({ createNotification }) =>
          createNotification({
            userId: issue.authorId,
            type: "issue_comment",
            title: `New comment on "${issue.title}"`,
            body: commentBody.length > 200 ? commentBody.slice(0, 200) + "…" : commentBody,
            url: `/${ownerName}/${repoName}/issues/${issueNum}`,
            repoId: resolved.repo.id,
          })
        ).catch(() => { /* never block the response */ });
      }
    }

    if (decision.status === "pending") {
      // Notify repo owner that a comment is awaiting review.
      void notifyOwnerOfPendingComment({
        repositoryId: resolved.repo.id,
        commenterUsername: user.username,
        kind: "issue",
        threadNumber: issueNum,
        ownerUsername: ownerName,
        repoName,
      });
      return c.redirect(
        `/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent("Comment awaiting author approval")}`
      );
    }
    if (decision.status === "rejected") {
      // Silent ban — the commenter is on the banned list. Don't reveal
      // the gate; just send them back to the page as if it posted.
      return c.redirect(
        `/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent("Comment awaiting author approval")}`
      );
    }

    return c.redirect(
      `/${ownerName}/${repoName}/issues/${issueNum}`
    );
  }
);

// Close issue
issueRoutes.post(
  "/:owner/:repo/issues/:number/close",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const issueNum = parseInt(c.req.param("number"), 10);

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}`);

    await db
      .update(issues)
      .set({ state: "closed", closedAt: new Date(), updatedAt: new Date() })
      .where(
        and(
          eq(issues.repositoryId, resolved.repo.id),
          eq(issues.number, issueNum)
        )
      );
    void fireWebhooks(resolved.repo.id, "issue", {
      action: "closed",
      number: issueNum,
    });

    return c.redirect(
      `/${ownerName}/${repoName}/issues/${issueNum}`
    );
  }
);

// Reopen issue
issueRoutes.post(
  "/:owner/:repo/issues/:number/reopen",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const issueNum = parseInt(c.req.param("number"), 10);

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}`);

    await db
      .update(issues)
      .set({ state: "open", closedAt: null, updatedAt: new Date() })
      .where(
        and(
          eq(issues.repositoryId, resolved.repo.id),
          eq(issues.number, issueNum)
        )
      );
    void fireWebhooks(resolved.repo.id, "issue", {
      action: "reopened",
      number: issueNum,
    });

    return c.redirect(
      `/${ownerName}/${repoName}/issues/${issueNum}`
    );
  }
);

// Shared nav component with issues tab
const IssueNav = ({
  owner,
  repo,
  active,
}: {
  owner: string;
  repo: string;
  active: "code" | "commits" | "issues";
}) => (
  <TabNav
    tabs={[
      { label: "Code", href: `/${owner}/${repo}`, active: active === "code" },
      { label: "Issues", href: `/${owner}/${repo}/issues`, active: active === "issues" },
      { label: "Commits", href: `/${owner}/${repo}/commits`, active: active === "commits" },
    ]}
  />
);

// Re-run AI triage on demand (e.g. after the issue body has been edited).
// Bypasses ISSUE_TRIAGE_MARKER via { force: true }. Write-access only.
issueRoutes.post(
  "/:owner/:repo/issues/:number/ai-retriage",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const issueNum = parseInt(c.req.param("number"), 10);
    const user = c.get("user")!;
    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}`);

    const [issue] = await db
      .select()
      .from(issues)
      .where(
        and(
          eq(issues.repositoryId, resolved.repo.id),
          eq(issues.number, issueNum)
        )
      )
      .limit(1);
    if (!issue) {
      return c.redirect(`/${ownerName}/${repoName}/issues`);
    }

    triggerIssueTriage(
      {
        ownerName,
        repoName,
        repositoryId: resolved.repo.id,
        issueId: issue.id,
        issueNumber: issue.number,
        authorId: user.id,
        title: issue.title,
        body: issue.body || "",
      },
      { force: true }
    ).catch((err) => {
      console.warn(
        `[issue-triage] re-triage failed for issue ${issue.id}:`,
        err instanceof Error ? err.message : err
      );
    });

    return c.redirect(
      `/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent(
        "AI re-triage queued. The new comment will appear in 10-30s; reload to see it."
      )}`
    );
  }
);

// ─── Create branch from issue ─────────────────────────────────────────────────
// POST /:owner/:repo/issues/:number/branch
// Creates a new git branch from the repo default branch, pre-named after the
// issue. Write access required. Zero-config — no new DB tables.

issueRoutes.post(
  "/:owner/:repo/issues/:number/branch",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const issueNum = parseInt(c.req.param("number"), 10);

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}/issues`);

    const [issue] = await db
      .select({ id: issues.id, number: issues.number, title: issues.title })
      .from(issues)
      .where(
        and(
          eq(issues.repositoryId, resolved.repo.id),
          eq(issues.number, issueNum)
        )
      )
      .limit(1);

    if (!issue) {
      return c.redirect(`/${ownerName}/${repoName}/issues`);
    }

    const body = await c.req.formData().catch(() => null);
    const rawName = (body?.get("branchName") as string | null)?.trim();

    // Derive a slug from the issue title
    const titleSlug = issue.title
      .toLowerCase()
      .replace(/[^a-z0-9]+/g, "-")
      .replace(/^-+|-+$/g, "")
      .slice(0, 40);
    const suggested = `issue-${issue.number}-${titleSlug}`;
    const branchName = rawName && /^[a-zA-Z0-9._\-/]+$/.test(rawName)
      ? rawName
      : suggested;

    const defaultBranch = (await getDefaultBranch(ownerName, repoName)) ?? "main";
    const sha = await resolveRef(ownerName, repoName, defaultBranch);

    if (!sha) {
      return c.redirect(
        `/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent(
          "Cannot create branch: repository has no commits yet."
        )}`
      );
    }

    const ok = await updateRef(ownerName, repoName, `refs/heads/${branchName}`, sha);
    if (!ok) {
      return c.redirect(
        `/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent(
          `Failed to create branch '${branchName}'. It may already exist.`
        )}`
      );
    }

    return c.redirect(
      `/${ownerName}/${repoName}/tree/${branchName}?info=${encodeURIComponent(
        `Branch '${branchName}' created from ${defaultBranch}.`
      )}`
    );
  }
);

// POST /:owner/:repo/issues/:number/set-parent
// Sets or clears the parent (epic) for an issue.
issueRoutes.post(
  "/:owner/:repo/issues/:number/set-parent",
  softAuth,
  requireAuth,
  requireRepoAccess("write"),
  async (c) => {
    const { owner: ownerName, repo: repoName } = c.req.param();
    const issueNum = parseInt(c.req.param("number"), 10);
    const form = await c.req.formData();
    const parentNum = form.get("parent_number")?.toString().trim() ?? "";

    const resolved = await resolveRepo(ownerName, repoName);
    if (!resolved) return c.redirect(`/${ownerName}/${repoName}/issues`);

    const [issue] = await db
      .select({ id: issues.id })
      .from(issues)
      .where(and(eq(issues.repositoryId, resolved.repo.id), eq(issues.number, issueNum)))
      .limit(1);
    if (!issue) return c.redirect(`/${ownerName}/${repoName}/issues`);

    // Clear parent
    if (!parentNum || parentNum === "0") {
      await db.update(issues).set({ parentIssueId: null }).where(eq(issues.id, issue.id));
      return c.redirect(`/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent("Removed from epic.")}`);
    }

    const pNum = parseInt(parentNum, 10);
    if (isNaN(pNum) || pNum === issueNum) {
      return c.redirect(`/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent("Invalid parent issue number.")}`);
    }

    const [parent] = await db
      .select({ id: issues.id })
      .from(issues)
      .where(and(eq(issues.repositoryId, resolved.repo.id), eq(issues.number, pNum)))
      .limit(1);
    if (!parent) {
      return c.redirect(`/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent(`Issue #${pNum} not found.`)}`);
    }

    await db.update(issues).set({ parentIssueId: parent.id }).where(eq(issues.id, issue.id));
    return c.redirect(`/${ownerName}/${repoName}/issues/${issueNum}?info=${encodeURIComponent(`Added to epic #${pNum}.`)}`);
  }
);

export default issueRoutes;
export { IssueNav };