Ariver
2026-07-07 ae7fcc35862edb366ed7775d3dc7e93e53e59290
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
import SwiftUI
import AppKit
import Carbon
 
// MARK: - Application Entry Point
 
@main
struct TagLauncherApp: App {
    private static let singletonLockFile = TagLauncherProcessSingleton.acquireOrHandOffAndExit()
    @NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
 
    init() {
        _ = Self.singletonLockFile
    }
 
    var body: some Scene {
        Settings {
            PreferencesView()
        }
        .defaultSize(width: 1000, height: 640)
        .commands {
            CommandGroup(replacing: .systemServices) { }
            CommandGroup(replacing: .appVisibility) { }
            CommandGroup(replacing: .help) { }
        }
    }
}
 
// MARK: - App Delegate (menubar + overlay window + hotkey)
 
private enum HotkeyRegistrationAttempt {
    case success(EventHotKeyRef)
    case failure(OSStatus)
}
 
final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
    static private(set) weak var shared: AppDelegate?
 
    private static let showDockIconKey = "showDockIcon"
    private static let statusItemAutosaveName = AppIdentity.statusItemAutosaveName
    private static let statusItemButtonIdentifier = NSUserInterfaceItemIdentifier("TagLauncherStatusItemButton")
    private static let statusItemAccessibilityLabel = AppIdentity.displayName
    private static let showAppListMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherShowAppListMenuItem")
    private static let proStatusMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherProStatusMenuItem")
    private static let helpMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherHelpMenu")
    private static let downloadHelpMenuItemIdentifier = NSUserInterfaceItemIdentifier("TagLauncherDownloadHelpMenuItem")
    private static let externalActivationNotification = Notification.Name("TagLauncherExternalActivationRequested")
    private static let externalActivationObject = AppIdentity.bundleIdentifier
    private static let externalInvocationScheme = "taglauncher"
    private static let externalInvocationShowHost = "show"
    private static let duplicateLaunchSuppressReopenKey = "duplicateLaunchSuppressReopenAt"
    private static let overlaySpaceHotkeyID: UInt32 = 3
    private static let launcherOverlayLevel = NSWindow.Level(rawValue: NSWindow.Level.mainMenu.rawValue - 1)
    private static let overlayDefaultLevel = launcherOverlayLevel
    private static let overlayTextInputLevel = launcherOverlayLevel
    private static let settingsContentSize = NSSize(width: 1000, height: 640)
 
    private var statusItem: NSStatusItem?
    private var overlayKeyMonitor: Any?
    private var quickSearchLocalMouseMonitor: Any?
    private var quickSearchExternalMouseMonitor: Any?
    private var settingsWindow: NSWindow?    // Track Settings window to keep it above overlay
    private var explicitPreferencesOpenRequestedAt = Date.distantPast
    private var mainHotkeyRef: EventHotKeyRef?
    private var quickSearchHotkeyRef: EventHotKeyRef?
    private var overlaySpaceHotkeyRef: EventHotKeyRef?
    private var hotkeyEventHandlerInstalled = false
    private var configuredHotkeysSuspendedForRecording = false
    private var isQuickSearchOpen = false
    private var quickSearchShouldHideOverlayOnClose = false
    private var quickSearchOnlyOverlaySession = false
    private var lastQuickSearchHotkeyAt = Date.distantPast
    private var isModalInteractionActive = false
    private var isInEditMode = false  // Suppress auto-dismiss during editing
    private var isEditingAppNote = false
    private var isConfiguringApplicationMenu = false
    private var lastShowDockIcon: Bool?
    private var statusMenuScreenForNextOverlay: NSScreen?
    private var suppressReopenUntil = Date.distantPast
    private var overlayOpenedByQuickSearchOnly = false
    private var didFinishLaunching = false
    private var pendingShowOverlayInvocation = false
 
    override init() {
        super.init()
        Self.shared = self
    }
 
    private lazy var overlayController = OverlayWindowController(
        dependencies: OverlayWindowController.Dependencies(
            shouldStageAsAccessory: { [weak self] in
                self?.shouldStageOverlayAsAccessory ?? false
            },
            isSettingsVisible: { [weak self] in
                self?.isSettingsVisible ?? false
            },
            settingsWindow: { [weak self] in
                self?.settingsWindow
            },
            canHideOverlay: { [weak self] in
                self?.isInEditMode == false
            },
            currentOverlayLevel: { [weak self] in
                self?.currentOverlayLevel ?? Self.overlayDefaultLevel
            },
            overlayLevel: { [weak self] initialQuickSearchSource in
                self?.overlayLevel(initialQuickSearchSource: initialQuickSearchSource) ?? Self.overlayDefaultLevel
            },
            makeContentView: { [weak self] initialQuickSearchSource in
                DismissibleHostingView(
                    rootView: ContentView(
                        hideOverlay: { [weak self] in
                            self?.hideOverlay(force: true)
                        },
                        initialQuickSearchSource: initialQuickSearchSource
                    ),
                    onBackdropTap: { [weak self] in
                        self?.hideOverlay()
                    }
                )
            },
            handleOverlayKeyEvent: { [weak self] event in
                self?.handleOverlayKeyEvent(event) ?? false
            },
            installOverlayKeyMonitor: { [weak self] in
                self?.installOverlayKeyMonitor()
            },
            removeOverlayKeyMonitor: { [weak self] in
                self?.removeOverlayKeyMonitor()
            },
            removeQuickSearchMouseMonitor: { [weak self] in
                Diagnostics.log("app.quickSearch.removeMouseMonitor", [
                    "quickSearchOpen": self?.isQuickSearchOpen,
                    "quickSearchOnlyOverlaySession": self?.quickSearchOnlyOverlaySession,
                    "quickSearchShouldHideOverlayOnClose": self?.quickSearchShouldHideOverlayOnClose
                ])
                self?.removeQuickSearchExternalMouseMonitor()
                self?.quickSearchShouldHideOverlayOnClose = false
                self?.quickSearchOnlyOverlaySession = false
            },
            detachSettingsWindow: { [weak self] window in
                self?.detachSettingsWindow(window)
            },
            prepareSettingsWindow: { [weak self] window in
                self?.prepareSettingsWindow(window)
            },
            refreshChromeState: { [weak self] activate, avoidSpaceSwitch in
                self?.refreshLauncherChromeState(activate: activate, avoidSpaceSwitch: avoidSpaceSwitch)
            },
            onWillHide: { [weak self] in
                self?.unregisterOverlaySpaceHotkey()
                TagDatabase.flushPendingCategorySchemeBackupBatch()
            },
            onDidHide: { [weak self] in
                self?.overlayOpenedByQuickSearchOnly = false
                NotificationCenter.default.post(name: .tagLauncherOverlayDidHide, object: nil)
            },
            onDidShow: { [weak self] in
                self?.refreshOverlaySpaceHotkeyRegistration()
                NotificationCenter.default.post(name: .tagLauncherOverlayDidShow, object: nil)
            }
        )
    )
 
    private var overlayWindow: NSWindow? {
        overlayController.window
    }
 
    private var overlayGeneration: Int {
        overlayController.generation
    }
 
    private var overlayAvoidsSpaceSwitch: Bool {
        get { overlayController.avoidsSpaceSwitch }
        set { overlayController.avoidsSpaceSwitch = newValue }
    }
 
    private var isOverlayVisible: Bool {
        overlayWindow?.isVisible == true
    }
 
    private var isSettingsVisible: Bool {
        settingsWindow?.isVisible == true
    }
 
    private var requiresForegroundOwnership: Bool {
        isOverlayVisible || isSettingsVisible
    }
 
    private var shouldStageOverlayAsAccessory: Bool {
        !isSettingsVisible && !UserDefaults.standard.bool(forKey: Self.showDockIconKey)
    }
 
    private var currentOverlayLevel: NSWindow.Level {
        if isEditingAppNote || isQuickSearchOpen {
            return Self.overlayTextInputLevel
        }
        return Self.overlayDefaultLevel
    }
 
    private func overlayLevel(initialQuickSearchSource: String? = nil) -> NSWindow.Level {
        if initialQuickSearchSource != nil {
            return Self.overlayTextInputLevel
        }
        return currentOverlayLevel
    }
 
    static func refreshChromeSettings() {
        (NSApp.delegate as? AppDelegate)?.syncChromeSettings(force: true)
    }
 
    static func openPreferencesWindow() {
        (NSApp.delegate as? AppDelegate)?.openPreferences()
    }
 
    func applicationDidFinishLaunching(_ notification: Notification) {
        AppDefaults.register()
        L10n.setup()
        ProEntitlementCenter.shared.start()
        migrateDefaultGroupName()
        TagDatabase.seedDefaultTags()
        _ = TagDatabase.relocalizeSystemTagsForCurrentLanguage()
        syncChromeSettings(force: true)
        observeHotkeyStatusChanges()
        registerConfiguredHotkeys()
        observeOtherWindows()
        observeSettingsClose()
        observeEditMode()
        observeAppNoteEditing()
        observeQuickSearch()
        observePreferencesRequests()
        observeExternalActivationRequests()
        observeApplicationMenuChanges()
        observeChromeSettings()
        observeLanguageChanges()
        observeProEntitlementChanges()
        setupLaunchAtLogin()
        suppressReopenUntil = Date().addingTimeInterval(1.0)
        didFinishLaunching = true
        closeRestoredPreferencesWindowsDuringLaunch()
        consumePendingShowOverlayInvocationIfNeeded()
        configureApplicationMenuWhenAvailable(retries: 200)
        warmAppIndexInBackground()
        relocalizeDefaultAppNotesForCurrentLanguageAsync()
    }
 
    /// Pre-scan application folders so the first App Grid open can hydrate from cache quickly.
    private func warmAppIndexInBackground() {
        DispatchQueue.global(qos: .utility).async {
            _ = AppIndexer.scan(useCache: true)
        }
    }
 
    func applicationDidBecomeActive(_ notification: Notification) {
        configureApplicationMenuWhenAvailable(retries: 12)
    }
 
    /// Dock icon reopen is an explicit App Grid entry only when the user chooses to show the Dock icon.
    /// Duplicate-instance handoff suppresses this path so repeated launches do not show App Grid.
    func applicationShouldHandleReopen(_ sender: NSApplication, hasVisibleWindows flag: Bool) -> Bool {
        guard Date() >= suppressReopenUntil else { return false }
        let lastDuplicateLaunch = UserDefaults.standard.double(forKey: Self.duplicateLaunchSuppressReopenKey)
        if lastDuplicateLaunch > 0,
           Date().timeIntervalSince1970 - lastDuplicateLaunch < 2.0 {
            suppressReopenUntil = Date().addingTimeInterval(1.0)
            return false
        }
        guard UserDefaults.standard.bool(forKey: Self.showDockIconKey) else { return false }
        guard isRecentUserClickNearDockArea() else { return false }
        showOrFocusOverlay()
        return false  // Suppress default "unhide all windows" behavior
    }
 
    func application(_ application: NSApplication, open urls: [URL]) {
        for url in urls {
            handleExternalInvocationURL(url)
        }
    }
 
    private enum ExternalInvocationRoute {
        case showOverlay
    }
 
    private func handleExternalInvocationURL(_ url: URL) {
        guard externalInvocationRoute(for: url) == .showOverlay else {
            Diagnostics.log("app.externalInvocation.ignored", [
                "url": url.absoluteString
            ])
            return
        }
        requestShowOverlayFromExternalInvocation()
    }
 
    private func externalInvocationRoute(for url: URL) -> ExternalInvocationRoute? {
        guard url.scheme?.lowercased() == Self.externalInvocationScheme else {
            return nil
        }
        let host = url.host?.lowercased()
        let path = url.path
        if host == Self.externalInvocationShowHost, path.isEmpty || path == "/" {
            return .showOverlay
        }
        return nil
    }
 
    private func requestShowOverlayFromExternalInvocation() {
        guard didFinishLaunching else {
            pendingShowOverlayInvocation = true
            return
        }
        pendingShowOverlayInvocation = false
        suppressReopenUntil = Date().addingTimeInterval(1.0)
        dismissQuickSearchIfNeeded()
        showOrFocusOverlay()
    }
 
    private func consumePendingShowOverlayInvocationIfNeeded() {
        guard pendingShowOverlayInvocation else { return }
        requestShowOverlayFromExternalInvocation()
    }
 
    private func isRecentUserClickNearDockArea() -> Bool {
        let lastMouseDown = CGEventSource.secondsSinceLastEventType(
            .combinedSessionState,
            eventType: .leftMouseDown
        )
        let lastMouseUp = CGEventSource.secondsSinceLastEventType(
            .combinedSessionState,
            eventType: .leftMouseUp
        )
        let recentMouseClick = min(lastMouseDown, lastMouseUp) < 0.9
        return recentMouseClick && isPointerNearDockArea()
    }
 
    private func isPointerNearDockArea() -> Bool {
        let mouse = NSEvent.mouseLocation
        let dockOrientation = UserDefaults(suiteName: "com.apple.dock")?
            .string(forKey: "orientation") ?? "bottom"
        let hiddenDockEdgeTolerance: CGFloat = 96
        return NSScreen.screens.contains { screen in
            let frame = screen.frame
            let visible = screen.visibleFrame
            guard NSMouseInRect(mouse, frame, false) else { return false }
            let bottomDock = visible.minY > frame.minY
                && mouse.y >= frame.minY
                && mouse.y <= visible.minY + 24
            let leftDock = visible.minX > frame.minX
                && mouse.x >= frame.minX
                && mouse.x <= visible.minX + 24
            let rightDock = visible.maxX < frame.maxX
                && mouse.x <= frame.maxX
                && mouse.x >= visible.maxX - 24
            let hiddenDockFallback: Bool
            switch dockOrientation {
            case "left":
                hiddenDockFallback = mouse.x <= frame.minX + hiddenDockEdgeTolerance
            case "right":
                hiddenDockFallback = mouse.x >= frame.maxX - hiddenDockEdgeTolerance
            default:
                hiddenDockFallback = mouse.y <= frame.minY + hiddenDockEdgeTolerance
            }
            return bottomDock || leftDock || rightDock || hiddenDockFallback
        }
    }
 
    func applicationWillTerminate(_ notification: Notification) {
        hideOverlay(force: true, discardWindow: true)
        unregisterHotkey(for: .main)
        unregisterHotkey(for: .quickSearch)
        unregisterOverlaySpaceHotkey()
        TagDatabase.flushPendingCategorySchemeBackupBatch()
        removeOverlayKeyMonitor()
        removeQuickSearchExternalMouseMonitor()
        DistributedNotificationCenter.default().removeObserver(
            self,
            name: Self.externalActivationNotification,
            object: Self.externalActivationObject
        )
    }
 
    /// Ensure defaultGroupName is always the language-neutral key "Other".
    /// Translates known old values back to "Other" so switching languages works.
    private func migrateDefaultGroupName() {
        let key = "defaultGroupName"
        let stored = UserDefaults.standard.string(forKey: key)
        // "Other" is the neutral key — nothing to do
        if stored == nil || stored == "Other" { return }
        // Check if the stored value is a translated version of "group.uncategorized"
        for (code, _) in L10n.supported {
            let loc = L10n.loadedTranslation("group.uncategorized", for: code)
            if stored == loc {
                UserDefaults.standard.set("Other", forKey: key)
                return
            }
        }
        // User has set a custom name — keep it
    }
 
    /// Observe Dock visibility changes so they take effect immediately.
    private func observeChromeSettings() {
        NotificationCenter.default.addObserver(
            forName: UserDefaults.didChangeNotification,
            object: nil, queue: .main
        ) { [weak self] _ in
            self?.syncChromeSettings()
        }
    }
 
    private func syncChromeSettings(force: Bool = false) {
        let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey)
        let dockChanged = lastShowDockIcon != showDock
 
        if force || dockChanged {
            lastShowDockIcon = showDock
            refreshLauncherChromeState()
        }
 
        if force {
            setupMenuBar()
        }
    }
 
    private func foregroundWindowForActivationPolicyRestore() -> NSWindow? {
        if let settingsWindow, settingsWindow.isVisible {
            return settingsWindow
        }
        if let overlayWindow, overlayWindow.isVisible {
            return overlayWindow
        }
        return NSApp.keyWindow
    }
 
    private func setLauncherActivationPolicy(_ desiredPolicy: NSApplication.ActivationPolicy) {
        guard NSApp.activationPolicy() != desiredPolicy else { return }
 
        let restoreWindow = desiredPolicy == .accessory && NSApp.isActive
            ? foregroundWindowForActivationPolicyRestore()
            : nil
 
        // Deactivate before switching regular -> accessory; otherwise Dock can
        // keep a stale running tile until Dock itself restarts.
        if desiredPolicy == .accessory && NSApp.isActive {
            NSApp.deactivate()
        }
 
        NSApp.setActivationPolicy(desiredPolicy)
 
        guard desiredPolicy == .accessory,
              let restoreWindow,
              restoreWindow.isVisible
        else { return }
 
        DispatchQueue.main.async { [weak self, weak restoreWindow] in
            guard let self,
                  let restoreWindow,
                  restoreWindow.isVisible,
                  self.requiresForegroundOwnership
            else { return }
            NSApp.activate(ignoringOtherApps: true)
            restoreWindow.makeKeyAndOrderFront(nil)
            restoreWindow.orderFrontRegardless()
        }
    }
 
    private func beginLauncherForegroundOwnership(activate: Bool = true, keyWindow: NSWindow? = nil) {
        let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey)
        let desiredPolicy: NSApplication.ActivationPolicy = showDock ? .regular : .accessory
        if NSApp.activationPolicy() != desiredPolicy {
            setLauncherActivationPolicy(desiredPolicy)
        }
        if activate, showDock {
            claimLauncherForeground(keyWindow: keyWindow)
        } else if activate {
            NSApp.activate(ignoringOtherApps: true)
            keyWindow?.makeKeyAndOrderFront(nil)
            keyWindow?.orderFrontRegardless()
        }
    }
 
    private func claimLauncherForeground(
        keyWindow: NSWindow? = nil,
        retries: Int = 0,
        overlayGeneration expectedOverlayGeneration: Int? = nil
    ) {
        if NSApp.activationPolicy() != .regular {
            setLauncherActivationPolicy(.regular)
        }
 
        if isOverlayVisible && !NSApp.presentationOptions.contains(.hideDock) {
            NSApp.presentationOptions = [.hideDock]
        }
 
        NSApp.unhide(nil)
        NSApp.activate(ignoringOtherApps: true)
 
        if let keyWindow, keyWindow.isVisible {
            keyWindow.makeKeyAndOrderFront(nil)
            keyWindow.makeMain()
            keyWindow.orderFrontRegardless()
        }
        configureApplicationMenuWhenAvailable(retries: 4)
 
        let overlayShouldYieldToSettings = keyWindow == overlayWindow && isSettingsVisible
        let keyWindowStillNeedsFocus = !overlayShouldYieldToSettings
            && keyWindow?.isVisible == true
            && keyWindow?.isKeyWindow == false
        let shouldRetry = !NSApp.isActive
            || !NSApp.presentationOptions.contains(.hideDock)
            || keyWindowStillNeedsFocus
        guard retries > 0, isOverlayVisible else { return }
        guard shouldRetry else { return }
 
        let retryWindow = keyWindow
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.08) { [weak self] in
            guard let self, self.isOverlayVisible else { return }
            if let expectedOverlayGeneration,
               expectedOverlayGeneration != self.overlayGeneration {
                return
            }
            self.refreshLauncherChromeState()
            self.claimLauncherForeground(
                keyWindow: retryWindow,
                retries: retries - 1,
                overlayGeneration: expectedOverlayGeneration
            )
        }
    }
 
    private func refreshLauncherChromeState(activate: Bool = false, avoidSpaceSwitch: Bool = false) {
        let showDock = UserDefaults.standard.bool(forKey: Self.showDockIconKey)
        lastShowDockIcon = showDock
 
        let shouldStayAccessoryForCurrentFullscreenSpace = isOverlayVisible
            && (avoidSpaceSwitch || overlayAvoidsSpaceSwitch)
        let shouldStayAccessoryForHiddenDockChrome = requiresForegroundOwnership
            && !showDock
        let shouldStayAccessoryForQuickOnlySearch = isOverlayVisible
            && quickSearchOnlyOverlaySession
            && !showDock
        let desiredPolicy: NSApplication.ActivationPolicy = shouldStayAccessoryForCurrentFullscreenSpace
            ? .accessory
            : (shouldStayAccessoryForHiddenDockChrome ? .accessory
            : (shouldStayAccessoryForQuickOnlySearch ? .accessory
            : (requiresForegroundOwnership
            ? .regular
            : (showDock ? .regular : .accessory))))
        if NSApp.activationPolicy() != desiredPolicy {
            setLauncherActivationPolicy(desiredPolicy)
        }
 
        let desiredPresentation: NSApplication.PresentationOptions = isOverlayVisible ? [.hideDock] : []
        if NSApp.presentationOptions != desiredPresentation {
            NSApp.presentationOptions = desiredPresentation
        }
 
        if activate && requiresForegroundOwnership
            && !shouldStayAccessoryForCurrentFullscreenSpace
            && !shouldStayAccessoryForQuickOnlySearch {
            let keyWindow = isSettingsVisible ? settingsWindow : (isOverlayVisible ? overlayWindow : nil)
            if shouldStayAccessoryForHiddenDockChrome {
                beginLauncherForegroundOwnership(activate: true, keyWindow: keyWindow)
            } else {
                claimLauncherForeground(
                    keyWindow: keyWindow,
                    retries: isOverlayVisible && !isSettingsVisible ? 5 : 0,
                    overlayGeneration: isOverlayVisible ? overlayGeneration : nil
                )
            }
        }
    }
 
    private func handleApplicationDidResignActive() {
        guard !isOverlayVisible else {
            return
        }
 
        if isQuickSearchOpen {
            NotificationCenter.default.post(
                name: .tagLauncherQuickSearchDismissRequested,
                object: nil,
                userInfo: ["source": QuickSearchDismissSource.programmatic]
            )
        }
 
        if !requiresForegroundOwnership {
            refreshLauncherChromeState()
        }
    }
 
    /// Keep app chrome in sync when language changes from any entry point.
    private func observeLanguageChanges() {
        NotificationCenter.default.addObserver(
            forName: .appLanguageDidChange,
            object: nil, queue: .main
        ) { [weak self] _ in
            self?.setupMenuBar()
            self?.configureApplicationMenuWhenAvailable()
            self?.relocalizeDefaultAppNotesForCurrentLanguageAsync()
        }
    }
 
    private func relocalizeDefaultAppNotesForCurrentLanguageAsync() {
        DispatchQueue.global(qos: .utility).async {
            let apps = AppIndexer.scan(useCache: true)
            let appleChanged = AppleDefaultAppCatalog.relocalizeDefaultNotesForCurrentLanguage(apps: apps)
            let smartStartChanged = SmartStartService.relocalizeDefaultNotesForCurrentLanguage(apps: apps)
            guard appleChanged || smartStartChanged else { return }
            DispatchQueue.main.async {
                NotificationCenter.default.post(name: .tagLauncherDataDidChange, object: nil)
            }
        }
    }
 
    // MARK: - Launch at Login (LaunchAgent, zero permissions)
 
    private static let launchAgentLabel = AppIdentity.launchAgentLabel
    static var supportsLaunchAtLogin: Bool {
        ProcessInfo.processInfo.environment["APP_SANDBOX_CONTAINER_ID"] == nil
    }
 
    private static var launchAgentURL: URL {
        FileManager.default.homeDirectoryForCurrentUser
            .appendingPathComponent("Library/LaunchAgents/\(launchAgentLabel).plist")
    }
 
    static func enableLaunchAtLogin() {
        guard supportsLaunchAtLogin else { return }
        let plist: [String: Any] = [
            "Label": Self.launchAgentLabel,
            "ProgramArguments": Self.expectedLaunchAgentProgramArguments(),
            "RunAtLoad": true,
        ]
        let dir = Self.launchAgentURL.deletingLastPathComponent()
        try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
        (plist as NSDictionary).write(to: Self.launchAgentURL, atomically: true)
 
        let uid = getuid()
        let bootoutTask = Process()
        bootoutTask.launchPath = "/bin/launchctl"
        bootoutTask.arguments = ["bootout", "gui/\(uid)/\(Self.launchAgentLabel)"]
        try? bootoutTask.run()
        bootoutTask.waitUntilExit()
 
        let task = Process()
        task.launchPath = "/bin/launchctl"
        task.arguments = ["bootstrap", "gui/\(uid)", Self.launchAgentURL.path]
        try? task.run()
    }
 
    static func disableLaunchAtLogin() {
        guard supportsLaunchAtLogin else { return }
        let uid = getuid()
        let task = Process()
        task.launchPath = "/bin/launchctl"
        task.arguments = ["bootout", "gui/\(uid)/\(Self.launchAgentLabel)"]
        try? task.run()
        try? FileManager.default.removeItem(at: Self.launchAgentURL)
    }
 
    private static func launchAgentProgramArguments() -> [String]? {
        guard let plist = NSDictionary(contentsOf: Self.launchAgentURL) as? [String: Any] else {
            return nil
        }
        return plist["ProgramArguments"] as? [String]
    }
 
    private static func expectedLaunchAgentProgramArguments() -> [String] {
        let executablePath = Bundle.main.executablePath
            ?? Bundle.main.bundleURL
                .appendingPathComponent("Contents/MacOS/\(AppIdentity.displayName)")
                .path
        return [executablePath, "--hide"]
    }
 
    /// On first launch, enable login item by default via LaunchAgent.
    /// Does NOT require App Management permission.
    private func setupLaunchAtLogin() {
        guard Self.supportsLaunchAtLogin else {
            if UserDefaults.standard.object(forKey: "launchAtLogin") == nil {
                UserDefaults.standard.set(false, forKey: "launchAtLogin")
            }
            return
        }
        let key = "launchAtLogin"
        guard UserDefaults.standard.bool(forKey: key) else {
            Self.disableLaunchAtLogin()
            return
        }
 
        let expectedArguments = Self.expectedLaunchAgentProgramArguments()
        if !AppDefaults.hasStoredValue(for: key)
            || Self.launchAgentProgramArguments() != expectedArguments {
            Self.enableLaunchAtLogin()
        }
    }
 
    // MARK: - Menu Bar
 
    private func setupMenuBar() {
        if statusItem == nil {
            statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
        } else {
            statusItem?.length = NSStatusItem.squareLength
        }
        guard let statusItem else { return }
        statusItem.autosaveName = Self.statusItemAutosaveName
        statusItem.isVisible = true
 
        if let button = statusItem.button {
            button.identifier = Self.statusItemButtonIdentifier
            button.setAccessibilityIdentifier(Self.statusItemAutosaveName)
            button.setAccessibilityLabel(Self.statusItemAccessibilityLabel)
            button.image = makeMenuBarIcon()
            button.imageScaling = .scaleProportionallyDown
            button.imagePosition = .imageOnly
            button.toolTip = "TagLauncher — Tag-based app launcher"
            button.action = #selector(toggleOverlay(_:))
            button.target = self
        }
 
        let menu = NSMenu()
        menu.delegate = self
        let showItem = NSMenuItem(
            title: showAppListMenuTitle,
            action: #selector(toggleOverlayFromStatusMenu(_:)),
            keyEquivalent: ""
        )
        showItem.target = self
        menu.addItem(showItem)
        menu.addItem(.separator())
 
        // Version display
        let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "?"
        let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "?"
        let versionItem = NSMenuItem(
            title: "\(tr("menu.version")) \(appVersion) (\(buildNumber))",
            action: nil,
            keyEquivalent: ""
        )
        versionItem.isEnabled = false
        menu.addItem(versionItem)
 
        let proStatusItem = makeProStatusMenuItem()
        menu.addItem(proStatusItem)
 
        menu.addItem(.separator())
        let prefsItem = NSMenuItem(
            title: tr("menu.preferences"),
            action: #selector(openPreferences(_:)),
            keyEquivalent: ","
        )
        prefsItem.target = self
        prefsItem.keyEquivalentModifierMask = .command
        menu.addItem(prefsItem)
        menu.addItem(.separator())
 
        // Language submenu
        let langMenu = NSMenu()
        let currentLang = L10n.currentCode
        for (code, name) in L10n.supported {
            let item = NSMenuItem(title: name, action: #selector(switchLanguage(_:)), keyEquivalent: "")
            item.representedObject = code
            item.state = (code == currentLang) ? .on : .off
            langMenu.addItem(item)
        }
        let langItem = NSMenuItem(title: tr("menu.language"), action: nil, keyEquivalent: "")
        langItem.submenu = langMenu
        menu.addItem(langItem)
 
        menu.addItem(.separator())
        menu.addItem(
            NSMenuItem(
                title: tr("menu.quit"),
                action: #selector(NSApplication.terminate(_:)),
                keyEquivalent: "q"
            )
        )
        statusItem.menu = menu
    }
 
    func menuWillOpen(_ menu: NSMenu) {
        configureProStatusMenuItem(in: menu)
        statusMenuScreenForNextOverlay = overlayController.screenContainingCurrentPointer()
            ?? statusItem?.button?.window?.screen
            ?? NSScreen.main
            ?? NSScreen.screens.first
    }
 
    func menuDidClose(_ menu: NSMenu) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { [weak self] in
            self?.statusMenuScreenForNextOverlay = nil
        }
    }
 
    private func makeMenuBarIcon() -> NSImage {
        let menuBarIconSize = NSSize(width: 19, height: 19)
        if let url = Bundle.main.url(forResource: "TagLauncherMenuBarIcon", withExtension: "svg"),
           let image = NSImage(contentsOf: url) {
            image.size = menuBarIconSize
            image.isTemplate = true
            image.accessibilityDescription = "TagLauncher"
            return image
        }
 
        let image = NSImage(size: menuBarIconSize)
        image.lockFocus()
        defer { image.unlockFocus() }
 
        NSGraphicsContext.current?.shouldAntialias = true
        NSColor.black.withAlphaComponent(0.88).setStroke()
        NSColor.black.withAlphaComponent(0.88).setFill()
 
        let scale = image.size.width / 220.0
        func rectFromSVG(x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat) -> NSRect {
            NSRect(
                x: x * scale,
                y: (220.0 - y - height) * scale,
                width: width * scale,
                height: height * scale
            )
        }
 
        let outline = NSBezierPath(
            roundedRect: rectFromSVG(x: 15, y: 15, width: 190, height: 190),
            xRadius: 44 * scale,
            yRadius: 44 * scale
        )
        outline.lineWidth = 11 * scale
        outline.stroke()
 
        for rect in [
            rectFromSVG(x: 49, y: 134, width: 27, height: 27),
            rectFromSVG(x: 92, y: 134, width: 27, height: 27),
            rectFromSVG(x: 49, y: 91, width: 27, height: 27),
            rectFromSVG(x: 92, y: 91, width: 27, height: 27),
            rectFromSVG(x: 49, y: 48, width: 27, height: 27),
            rectFromSVG(x: 92, y: 48, width: 27, height: 27)
        ] {
            NSBezierPath(roundedRect: rect, xRadius: 8 * scale, yRadius: 8 * scale).fill()
        }
 
        for rect in [
            rectFromSVG(x: 132, y: 133, width: 47, height: 28),
            rectFromSVG(x: 132, y: 90.5, width: 47, height: 28),
            rectFromSVG(x: 132, y: 48, width: 47, height: 28)
        ] {
            NSBezierPath(roundedRect: rect, xRadius: 12 * scale, yRadius: 12 * scale).fill()
        }
 
        image.isTemplate = true
        image.accessibilityDescription = "TagLauncher"
        return image
    }
 
    private func makeProStatusMenuItem() -> NSMenuItem {
        let item = NSMenuItem(
            title: "",
            action: #selector(openProStatusFromStatusMenu(_:)),
            keyEquivalent: ""
        )
        item.identifier = Self.proStatusMenuItemIdentifier
        item.target = self
        configureProStatusMenuItem(item)
        return item
    }
 
    private func configureProStatusMenuItem(in menu: NSMenu) {
        guard let item = menu.items.first(where: { $0.identifier == Self.proStatusMenuItemIdentifier }) else {
            return
        }
        configureProStatusMenuItem(item)
    }
 
    private func configureProStatusMenuItem(_ item: NSMenuItem) {
        let isUnlocked = ProEntitlementPolicy.accessState().isUnlocked
        item.title = tr(isUnlocked ? "menu.proStatus.unlocked" : "menu.proStatus.free")
        item.action = #selector(openProStatusFromStatusMenu(_:))
        item.target = self
        item.isEnabled = true
        item.image = isUnlocked ? makeProStatusMenuIcon() : nil
    }
 
    private func makeProStatusMenuIcon() -> NSImage? {
        guard let symbol = NSImage(systemSymbolName: "crown.fill", accessibilityDescription: "Pro") else {
            return nil
        }
        let configuration = NSImage.SymbolConfiguration(pointSize: 13, weight: .semibold)
        let configuredSymbol = symbol.withSymbolConfiguration(configuration) ?? symbol
        let image = NSImage(size: NSSize(width: 16, height: 16))
        image.lockFocus()
        NSColor(red: 0.96, green: 0.63, blue: 0.10, alpha: 1.0).set()
        let iconRect = NSRect(x: 1.5, y: 1.5, width: 13, height: 13)
        configuredSymbol.draw(in: iconRect, from: .zero, operation: .sourceOver, fraction: 1.0)
        NSColor(red: 0.96, green: 0.63, blue: 0.10, alpha: 1.0).set()
        iconRect.fill(using: .sourceAtop)
        image.unlockFocus()
        image.isTemplate = false
        image.accessibilityDescription = "Pro"
        return image
    }
 
    private var showAppListMenuTitle: String {
        if LauncherHotkeyRegistrationStore.state(for: .main) == .failed {
            return tr("menu.showShortcutUnavailable")
        }
        return "\(tr("menu.showAppList"))  \(LauncherHotkeySettings.effectiveHotkey(for: .main).displayString)"
    }
 
    private func observeApplicationMenuChanges() {
        NotificationCenter.default.addObserver(
            forName: NSApplication.didBecomeActiveNotification,
            object: NSApp, queue: .main
        ) { [weak self] _ in
            self?.configureApplicationMenuWhenAvailable(retries: 4)
        }
 
        NotificationCenter.default.addObserver(
            forName: NSMenu.didAddItemNotification,
            object: nil, queue: .main
        ) { [weak self] notification in
            guard let self,
                  !self.isConfiguringApplicationMenu,
                  let menu = notification.object as? NSMenu,
                  menu === NSApp.mainMenu?.items.first?.submenu
            else { return }
            self.configureApplicationMenuWhenAvailable(retries: 2)
        }
    }
 
    private func configureApplicationMenuWhenAvailable(retries: Int = 20) {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in
            guard let self else { return }
            guard NSApp.mainMenu?.items.first?.submenu != nil else {
                if retries > 0 {
                    self.configureApplicationMenuWhenAvailable(retries: retries - 1)
                }
                return
            }
 
            self.configureApplicationMenu()
            self.configureHelpMenu()
            if retries > 0 && self.applicationMenuNeedsCleanup() {
                self.configureApplicationMenuWhenAvailable(retries: retries - 1)
            }
        }
    }
 
    private func configureApplicationMenu() {
        guard !isConfiguringApplicationMenu else { return }
        guard let appMenu = NSApp.mainMenu?.items.first?.submenu else { return }
 
        isConfiguringApplicationMenu = true
        defer { isConfiguringApplicationMenu = false }
 
        removeUnusedDefaultItems(from: appMenu)
        configurePreferencesMenuItem(in: appMenu)
        upsertShowAppListItem(in: appMenu)
        normalizeSeparators(in: appMenu)
    }
 
    private func applicationMenuNeedsCleanup() -> Bool {
        guard let appMenu = NSApp.mainMenu?.items.first?.submenu else { return true }
        let hasUnusedDefaultItems = appMenu.items.contains(where: isUnusedDefaultApplicationMenuItem)
        let hasShowAppListItem = appMenu.items.contains {
            $0.identifier == Self.showAppListMenuItemIdentifier
        }
        return hasUnusedDefaultItems || !hasShowAppListItem
    }
 
    private func removeUnusedDefaultItems(from menu: NSMenu) {
        for item in menu.items.reversed() where isUnusedDefaultApplicationMenuItem(item) {
            menu.removeItem(item)
        }
    }
 
    private func isUnusedDefaultApplicationMenuItem(_ item: NSMenuItem) -> Bool {
        if let servicesMenu = NSApp.servicesMenu, item.submenu === servicesMenu {
            return true
        }
        return item.action == #selector(NSApplication.hide(_:))
            || item.action == #selector(NSApplication.hideOtherApplications(_:))
            || item.action == #selector(NSApplication.unhideAllApplications(_:))
    }
 
    private func upsertShowAppListItem(in menu: NSMenu) {
        if let existingItem = menu.items.first(where: { $0.identifier == Self.showAppListMenuItemIdentifier }) {
            configureShowAppListItem(existingItem)
            return
        }
 
        let item = NSMenuItem()
        item.identifier = Self.showAppListMenuItemIdentifier
        configureShowAppListItem(item)
 
        if let settingsIndex = menu.items.firstIndex(where: { isSettingsMenuItem($0) }) {
            menu.insertItem(item, at: settingsIndex + 1)
        } else if let firstSeparatorIndex = menu.items.firstIndex(where: { $0.isSeparatorItem }) {
            menu.insertItem(item, at: firstSeparatorIndex)
        } else {
            menu.addItem(item)
        }
    }
 
    private func configureShowAppListItem(_ item: NSMenuItem) {
        item.title = showAppListMenuTitle
        item.action = #selector(toggleOverlayFromStatusMenu(_:))
        item.target = self
        item.keyEquivalent = ""
        item.keyEquivalentModifierMask = []
        item.isEnabled = true
    }
 
    private func configurePreferencesMenuItem(in menu: NSMenu) {
        let item: NSMenuItem
        if let existingItem = menu.items.first(where: { isSettingsMenuItem($0) }) {
            item = existingItem
        } else {
            item = NSMenuItem()
            if let firstSeparatorIndex = menu.items.firstIndex(where: { $0.isSeparatorItem }) {
                menu.insertItem(item, at: firstSeparatorIndex)
            } else {
                menu.addItem(item)
            }
        }
 
        item.title = tr("menu.preferences")
        item.action = #selector(openPreferences(_:))
        item.target = self
        item.keyEquivalent = ","
        item.keyEquivalentModifierMask = .command
        item.isEnabled = true
    }
 
    private func isSettingsMenuItem(_ item: NSMenuItem) -> Bool {
        item.action == Selector(("showSettingsWindow:"))
            || item.action == #selector(openPreferences(_:))
            || item.title == tr("menu.preferences")
    }
 
    private func normalizeSeparators(in menu: NSMenu) {
        var indexesToRemove: [Int] = []
        var previousWasSeparator = false
 
        for (index, item) in menu.items.enumerated() {
            guard item.isSeparatorItem else {
                previousWasSeparator = false
                continue
            }
            if index == 0 || index == menu.items.count - 1 || previousWasSeparator {
                indexesToRemove.append(index)
            }
            previousWasSeparator = true
        }
 
        for index in indexesToRemove.reversed() {
            menu.removeItem(at: index)
        }
    }
 
    private func configureHelpMenu() {
        guard let mainMenu = NSApp.mainMenu else { return }
        NSApp.helpMenu = nil
 
        for item in mainMenu.items.reversed() {
            let isHelpMenu = item.identifier == Self.helpMenuItemIdentifier
                || item.title.localizedCaseInsensitiveContains("help")
                || item.title == tr("menu.help")
                || item.submenu?.title.localizedCaseInsensitiveContains("help") == true
                || item.submenu?.title == tr("menu.help")
            if isHelpMenu {
                mainMenu.removeItem(item)
            }
        }
 
        let menuItem = NSMenuItem(title: tr("menu.help"), action: nil, keyEquivalent: "")
        let helpMenu = NSMenu(title: tr("menu.help"))
        menuItem.identifier = Self.helpMenuItemIdentifier
        menuItem.submenu = helpMenu
 
        let downloadItem = NSMenuItem()
        downloadItem.identifier = Self.downloadHelpMenuItemIdentifier
        downloadItem.title = tr("help.downloadPDF")
        downloadItem.action = #selector(openLocalizedHelp(_:))
        downloadItem.target = self
        downloadItem.keyEquivalent = ""
        downloadItem.keyEquivalentModifierMask = []
        downloadItem.isEnabled = true
        helpMenu.addItem(downloadItem)
        mainMenu.addItem(menuItem)
    }
 
    @objc private func openLocalizedHelp(_ sender: Any? = nil) {
        NSWorkspace.shared.open(HelpDocument.currentURL)
    }
 
    private func removeMenuBarItem() {
        guard let statusItem else { return }
        NSStatusBar.system.removeStatusItem(statusItem)
        self.statusItem = nil
    }
 
    // MARK: - Overlay Window
 
    @objc func toggleOverlay(_ sender: Any) {
        performToggleOverlay(preferredScreen: nil)
    }
 
    @objc func toggleOverlayFromStatusMenu(_ sender: Any) {
        let preferredScreen = statusMenuScreenForNextOverlay
        statusMenuScreenForNextOverlay = nil
        DispatchQueue.main.async { [weak self] in
            self?.performToggleOverlay(preferredScreen: preferredScreen)
        }
    }
 
    private func performToggleOverlay(preferredScreen: NSScreen?) {
        overlayOpenedByQuickSearchOnly = false
        overlayController.toggle(preferredScreen: preferredScreen)
    }
 
    private func showOrFocusOverlay(preferredScreen: NSScreen? = nil) {
        overlayOpenedByQuickSearchOnly = false
        overlayController.showOrFocus(preferredScreen: preferredScreen)
    }
 
    private func showOverlay(
        initialQuickSearchSource: String? = nil,
        preferredScreen: NSScreen? = nil,
        stagedForAllSpaces: Bool = false
    ) {
        Diagnostics.log("app.overlay.showRequest", [
            "initialQuickSearchSource": initialQuickSearchSource,
            "stagedForAllSpaces": stagedForAllSpaces,
            "isQuickSearchOpen": isQuickSearchOpen,
            "quickSearchOnlyOverlaySession": quickSearchOnlyOverlaySession,
            "overlayOpenedByQuickSearchOnly": overlayOpenedByQuickSearchOnly
        ])
        if initialQuickSearchSource == QuickSearchOpenSource.globalHidden {
            isQuickSearchOpen = true
            quickSearchShouldHideOverlayOnClose = true
            quickSearchOnlyOverlaySession = true
            overlayOpenedByQuickSearchOnly = true
        } else if initialQuickSearchSource == nil {
            overlayOpenedByQuickSearchOnly = false
        }
        overlayController.show(
            initialQuickSearchSource: initialQuickSearchSource,
            preferredScreen: preferredScreen,
            stagedForAllSpaces: stagedForAllSpaces
        )
    }
 
    private func installOverlayKeyMonitor() {
        guard overlayKeyMonitor == nil else { return }
        overlayKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in
            guard let self else { return event }
            if self.handleOverlayKeyEvent(event) {
                return nil
            }
            return event
        }
    }
 
    @discardableResult
    private func handleOverlayKeyEvent(_ event: NSEvent) -> Bool {
        guard event.type == .keyDown else { return false }
 
        if event.keyCode == UInt16(kVK_Escape),
           isQuickSearchOpen || quickSearchOnlyOverlaySession {
            return handleOverlayEscapeKey()
        }
 
        guard shouldHandleOverlayKeyEvent(event) else { return false }
 
        if event.keyCode == UInt16(kVK_Escape) {
            return handleOverlayEscapeKey()
        }
        if shouldOpenQuickSearch(for: event) {
            requestQuickSearch(source: QuickSearchOpenSource.mainOverlay)
            return true
        }
        return false
    }
 
    private func handleOverlayEscapeKey() -> Bool {
        if isQuickSearchOpen || quickSearchOnlyOverlaySession {
            dismissQuickSearchFromKeyboard()
            return true
        }
        guard !isSettingsVisible,
              !isEditingAppNote,
              !isModalInteractionActive
        else { return false }
        hideOverlay(force: true)
        return true
    }
 
    private func dismissQuickSearchFromKeyboard() {
        let shouldHideOverlayAfterDismiss = quickSearchShouldHideOverlayOnClose || quickSearchOnlyOverlaySession
        isQuickSearchOpen = false
        removeQuickSearchExternalMouseMonitor()
        updateOverlayLevelForTextInput()
        NotificationCenter.default.post(
            name: .tagLauncherQuickSearchDismissRequested,
            object: nil,
            userInfo: ["source": QuickSearchDismissSource.keyboard]
        )
        if shouldHideOverlayAfterDismiss {
            quickSearchShouldHideOverlayOnClose = false
            quickSearchOnlyOverlaySession = false
            overlayOpenedByQuickSearchOnly = true
            DispatchQueue.main.async { [weak self] in
                self?.hideOverlay(force: true, discardWindow: true)
            }
        }
    }
 
    private func requestQuickSearch(source: String) {
        isQuickSearchOpen = true
        quickSearchShouldHideOverlayOnClose = quickSearchShouldHideOverlayOnClose
            || source == QuickSearchOpenSource.globalHidden
        quickSearchOnlyOverlaySession = quickSearchOnlyOverlaySession
            || source == QuickSearchOpenSource.globalHidden
        if source == QuickSearchOpenSource.globalHidden {
            overlayOpenedByQuickSearchOnly = true
        }
        promoteOverlayToForegroundInput()
        updateOverlayLevelForTextInput()
        installQuickSearchExternalMouseMonitor()
        DispatchQueue.main.async {
            NotificationCenter.default.post(
                name: .tagLauncherQuickSearchRequested,
                object: nil,
                userInfo: ["source": source]
            )
        }
    }
 
    private func shouldHandleOverlayKeyEvent(_ event: NSEvent) -> Bool {
        guard overlayWindow?.isVisible == true else { return false }
        if !isSettingsVisible && NSApp.isActive {
            return true
        }
        if event.window == overlayWindow { return true }
        return event.window == nil && NSApp.keyWindow == overlayWindow
    }
 
    private func shouldOpenQuickSearch(for event: NSEvent) -> Bool {
        guard event.keyCode == UInt16(kVK_Space),
              !event.isARepeat,
              event.modifierFlags.intersection(.deviceIndependentFlagsMask).isEmpty,
              overlayWindow?.isVisible == true,
              !isQuickSearchOpen,
              !isInEditMode,
              !isEditingAppNote,
              !isModalInteractionActive
        else { return false }
 
        return true
    }
 
    private func removeOverlayKeyMonitor() {
        if let monitor = overlayKeyMonitor {
            NSEvent.removeMonitor(monitor)
            overlayKeyMonitor = nil
        }
    }
 
    private func hideOverlay(force: Bool = false, discardWindow: Bool = false) {
        Diagnostics.log("app.overlay.hideRequest", [
            "force": force,
            "discardWindow": discardWindow,
            "isQuickSearchOpen": isQuickSearchOpen,
            "quickSearchOnlyOverlaySession": quickSearchOnlyOverlaySession,
            "quickSearchShouldHideOverlayOnClose": quickSearchShouldHideOverlayOnClose,
            "overlayOpenedByQuickSearchOnly": overlayOpenedByQuickSearchOnly
        ])
        overlayController.hide(force: force, discardWindow: discardWindow)
    }
 
    // MARK: - Global Hotkeys
 
    private func registerConfiguredHotkeys() {
        guard !configuredHotkeysSuspendedForRecording else { return }
        installHotkeyEventHandlerIfNeeded()
        registerEffectiveHotkey(.main)
        registerEffectiveHotkey(.quickSearch)
    }
 
    func suspendConfiguredHotkeysForRecording() {
        guard !configuredHotkeysSuspendedForRecording else { return }
        configuredHotkeysSuspendedForRecording = true
        unregisterHotkey(for: .main)
        unregisterHotkey(for: .quickSearch)
    }
 
    func resumeConfiguredHotkeysAfterRecording() {
        guard configuredHotkeysSuspendedForRecording else { return }
        configuredHotkeysSuspendedForRecording = false
        registerConfiguredHotkeys()
    }
 
    private func registerEffectiveHotkey(_ kind: LauncherHotkeyKind) {
        unregisterHotkey(for: kind)
        let hotkey = LauncherHotkeySettings.effectiveHotkey(for: kind)
        registerAndStoreHotkey(hotkey, for: kind, markFailure: true)
    }
 
    @discardableResult
    func applyCustomHotkey(_ hotkey: LauncherHotkey, for kind: LauncherHotkeyKind) -> LauncherHotkeyCustomizationResult {
        guard ProEntitlementPolicy.isUnlocked(.customHotkeys) else {
            return .locked
        }
        if let error = LauncherHotkeySettings.validationError(for: hotkey, kind: kind) {
            return .invalid(error)
        }
        return activateHotkey(hotkey, for: kind, persistCustom: true)
    }
 
    @discardableResult
    func restoreDefaultHotkey(for kind: LauncherHotkeyKind) -> LauncherHotkeyCustomizationResult {
        guard ProEntitlementPolicy.isUnlocked(.customHotkeys) else {
            return .locked
        }
        return activateHotkey(LauncherHotkeySettings.defaultHotkey(for: kind), for: kind, persistCustom: false)
    }
 
    private func activateHotkey(
        _ hotkey: LauncherHotkey,
        for kind: LauncherHotkeyKind,
        persistCustom: Bool
    ) -> LauncherHotkeyCustomizationResult {
        installHotkeyEventHandlerIfNeeded()
 
        if LauncherHotkeySettings.effectiveHotkey(for: kind) == hotkey,
           hotkeyRef(for: kind) != nil {
            if persistCustom {
                LauncherHotkeySettings.save(hotkey, for: kind)
                LauncherHotkeyRegistrationStore.setActive(for: kind)
                return .saved
            }
            LauncherHotkeySettings.clearCustomHotkey(for: kind)
            LauncherHotkeyRegistrationStore.setActive(for: kind)
            return .restored
        }
 
        switch tryRegisterHotkey(hotkey, for: kind, markFailure: false) {
        case .success(let newRef):
            if let oldRef = hotkeyRef(for: kind) {
                UnregisterEventHotKey(oldRef)
            }
            setHotkeyRef(newRef, for: kind)
            if persistCustom {
                LauncherHotkeySettings.save(hotkey, for: kind)
                LauncherHotkeyRegistrationStore.setActive(for: kind)
                return .saved
            }
            LauncherHotkeySettings.clearCustomHotkey(for: kind)
            LauncherHotkeyRegistrationStore.setActive(for: kind)
            return .restored
        case .failure(let status):
            return .registrationFailed(status)
        }
    }
 
    private func registerAndStoreHotkey(
        _ hotkey: LauncherHotkey,
        for kind: LauncherHotkeyKind,
        markFailure: Bool
    ) {
        switch tryRegisterHotkey(hotkey, for: kind, markFailure: markFailure) {
        case .success(let newRef):
            setHotkeyRef(newRef, for: kind)
        case .failure:
            setHotkeyRef(nil, for: kind)
        }
    }
 
    private func tryRegisterHotkey(
        _ hotkey: LauncherHotkey,
        for kind: LauncherHotkeyKind,
        markFailure: Bool
    ) -> HotkeyRegistrationAttempt {
 
        var hotkeyID = EventHotKeyID()
        hotkeyID.signature = OSType(0x41505447) // 'APTG'
        hotkeyID.id = kind.eventID
 
        var newRef: EventHotKeyRef?
        let status = RegisterEventHotKey(
            hotkey.keyCode,
            hotkey.modifiers,
            hotkeyID,
            GetApplicationEventTarget(),
            0,
            &newRef
        )
 
        if status == noErr, let newRef {
            if markFailure {
                LauncherHotkeyRegistrationStore.setActive(for: kind)
            }
            return .success(newRef)
        } else {
            if markFailure {
                LauncherHotkeyRegistrationStore.setFailed(status, for: kind)
            }
            print("[TagLauncher] Fixed hotkey registration failed for \(kind.rawValue): \(status)")
            return .failure(status)
        }
    }
 
    private func observeHotkeyStatusChanges() {
        NotificationCenter.default.addObserver(
            forName: .tagLauncherHotkeyRegistrationChanged,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.setupMenuBar()
            self?.configureApplicationMenuWhenAvailable(retries: 2)
        }
    }
 
    private func observeProEntitlementChanges() {
        NotificationCenter.default.addObserver(
            forName: .tagLauncherProEntitlementChanged,
            object: nil,
            queue: .main
        ) { [weak self] _ in
            self?.registerConfiguredHotkeys()
            self?.setupMenuBar()
            self?.configureApplicationMenuWhenAvailable(retries: 2)
        }
    }
 
    private func installHotkeyEventHandlerIfNeeded() {
        guard !hotkeyEventHandlerInstalled else { return }
        hotkeyEventHandlerInstalled = true
 
        var eventSpec = EventTypeSpec(
            eventClass: OSType(kEventClassKeyboard),
            eventKind: UInt32(kEventHotKeyPressed)
        )
        let selfPtr = Unmanaged.passUnretained(self).toOpaque()
 
        InstallEventHandler(
            GetApplicationEventTarget(),
            { (_, event, userData) -> OSStatus in
                guard let event, let userData else { return noErr }
                var hotkeyID = EventHotKeyID()
                let status = GetEventParameter(
                    event,
                    EventParamName(kEventParamDirectObject),
                    EventParamType(typeEventHotKeyID),
                    nil,
                    MemoryLayout<EventHotKeyID>.size,
                    nil,
                    &hotkeyID
                )
                guard status == noErr else { return noErr }
 
                let delegate = Unmanaged<AppDelegate>
                    .fromOpaque(userData)
                    .takeUnretainedValue()
                DispatchQueue.main.async {
                    delegate.handleHotkeyEvent(id: hotkeyID.id)
                }
                return noErr
            },
            1,
            &eventSpec,
            selfPtr,
            nil
        )
    }
 
    private func handleHotkeyEvent(id: UInt32) {
        Diagnostics.log("app.hotkey", [
            "id": id,
            "isOverlayVisible": isOverlayVisible,
            "isQuickSearchOpen": isQuickSearchOpen,
            "quickSearchOnlyOverlaySession": quickSearchOnlyOverlaySession,
            "overlayOpenedByQuickSearchOnly": overlayOpenedByQuickSearchOnly
        ])
        if id == LauncherHotkeyKind.quickSearch.eventID {
            showQuickSearchFromGlobalHotkey()
        } else if id == Self.overlaySpaceHotkeyID {
            handleOverlaySpaceHotkey()
        } else {
            performToggleOverlay(preferredScreen: nil)
        }
    }
 
    private func handleOverlaySpaceHotkey() {
        guard canUseOverlaySpaceHotkey else { return }
        unregisterOverlaySpaceHotkey()
        requestQuickSearch(source: QuickSearchOpenSource.mainOverlay)
    }
 
    private var canUseOverlaySpaceHotkey: Bool {
        overlayWindow?.isVisible == true
            && !isSettingsVisible
            && !isQuickSearchOpen
            && !quickSearchOnlyOverlaySession
            && !isInEditMode
            && !isEditingAppNote
            && !isModalInteractionActive
    }
 
    private func showQuickSearchFromGlobalHotkey() {
        let now = Date()
        if overlayWindow?.isVisible == true,
           isQuickSearchOpen || quickSearchOnlyOverlaySession || overlayOpenedByQuickSearchOnly {
            lastQuickSearchHotkeyAt = now
            if isQuickSearchOpen || quickSearchOnlyOverlaySession {
                dismissQuickSearchFromKeyboard()
            } else {
                hideOverlay(force: true)
            }
            return
        }
 
        if now.timeIntervalSince(lastQuickSearchHotkeyAt) < 0.28 {
            promoteOverlayToForegroundInput()
            updateOverlayLevelForTextInput()
            return
        }
        lastQuickSearchHotkeyAt = now
 
        if overlayWindow?.isVisible == true {
            refreshLauncherChromeState(
                activate: !overlayAvoidsSpaceSwitch,
                avoidSpaceSwitch: overlayAvoidsSpaceSwitch
            )
            requestQuickSearch(source: QuickSearchOpenSource.globalVisible)
            return
        }
        isQuickSearchOpen = true
        quickSearchShouldHideOverlayOnClose = true
        quickSearchOnlyOverlaySession = true
        showOverlay(initialQuickSearchSource: QuickSearchOpenSource.globalHidden)
    }
 
    private func hotkeyRef(for kind: LauncherHotkeyKind) -> EventHotKeyRef? {
        switch kind {
        case .main: return mainHotkeyRef
        case .quickSearch: return quickSearchHotkeyRef
        }
    }
 
    private func setHotkeyRef(_ ref: EventHotKeyRef?, for kind: LauncherHotkeyKind) {
        switch kind {
        case .main: mainHotkeyRef = ref
        case .quickSearch: quickSearchHotkeyRef = ref
        }
    }
 
    private func unregisterHotkey(for kind: LauncherHotkeyKind) {
        if let ref = hotkeyRef(for: kind) {
            UnregisterEventHotKey(ref)
            setHotkeyRef(nil, for: kind)
        }
    }
 
    private func refreshOverlaySpaceHotkeyRegistration() {
        if canUseOverlaySpaceHotkey {
            registerOverlaySpaceHotkeyIfNeeded()
        } else {
            unregisterOverlaySpaceHotkey()
        }
    }
 
    private func registerOverlaySpaceHotkeyIfNeeded() {
        guard overlaySpaceHotkeyRef == nil else { return }
 
        var hotkeyID = EventHotKeyID()
        hotkeyID.signature = OSType(0x41505447) // 'APTG'
        hotkeyID.id = Self.overlaySpaceHotkeyID
 
        var newRef: EventHotKeyRef?
        let status = RegisterEventHotKey(
            UInt32(kVK_Space),
            0,
            hotkeyID,
            GetApplicationEventTarget(),
            0,
            &newRef
        )
 
        if status == noErr, let newRef {
            overlaySpaceHotkeyRef = newRef
        } else {
            overlaySpaceHotkeyRef = nil
            Diagnostics.log("app.overlay.spaceHotkey.failed", ["status": status])
        }
    }
 
    private func unregisterOverlaySpaceHotkey() {
        if let overlaySpaceHotkeyRef {
            UnregisterEventHotKey(overlaySpaceHotkeyRef)
            self.overlaySpaceHotkeyRef = nil
        }
    }
 
    // MARK: - Preferences
 
    /// Hide overlay when any other window becomes key (catches Cmd+, via SwiftUI Settings).
    /// Suppressed while in edit mode to prevent false dismissals.
    private func observeOtherWindows() {
        NotificationCenter.default.addObserver(
            forName: NSWindow.didBecomeKeyNotification,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let self,
                  let keyWindow = notification.object as? NSWindow,
                  keyWindow != self.overlayWindow,
                  !self.isInEditMode
            else { return }
 
            if self.isSettingsOwnedPanel(keyWindow) {
                return
            }
 
            if self.isMenuTrackingWindow(keyWindow) {
                return
            }
 
            if self.isAppOwnedDocumentWindow(keyWindow) {
                self.prepareSettingsWindow(keyWindow)
                return
            }
 
            if NSApp.windows.contains(keyWindow) {
                return
            }
 
            // Settings/Preferences window -> float it above overlay for real-time preview.
            if self.isSettingsWindowCandidate(keyWindow) {
                self.prepareSettingsWindow(keyWindow)
                return
            }
 
            self.hideOverlay()
        }
    }
 
    /// Settings must always appear centered over the current overlay view and float above it.
    private func prepareSettingsWindow(_ window: NSWindow) {
        dismissQuickSearchIfNeeded()
        let settingsSize = Self.settingsContentSize
        let settingsFrameSize = window.frameRect(
            forContentRect: NSRect(origin: .zero, size: settingsSize)
        ).size
        window.identifier = NSUserInterfaceItemIdentifier("TagLauncherPreferencesWindow")
        window.isRestorable = false
        window.restorationClass = nil
        _ = window.setFrameAutosaveName("")
        window.contentMinSize = settingsSize
        window.contentMaxSize = settingsSize
        window.minSize = settingsFrameSize
        window.maxSize = settingsFrameSize
        let currentContentSize = window.contentView?.bounds.size ?? window.contentLayoutRect.size
        if abs(currentContentSize.width - settingsSize.width) > 0.5
            || abs(currentContentSize.height - settingsSize.height) > 0.5 {
            window.setContentSize(settingsSize)
        }
 
        if let overlayWindow, overlayWindow.isVisible {
            center(window, over: overlayWindow.frame)
            attachSettingsWindow(window, to: overlayWindow)
            window.level = overlayWindow.level
        } else if let screen = screenUnderMouse() {
            center(window, over: screen.visibleFrame)
            window.level = .floating
            detachSettingsWindow(window)
        }
 
        var behavior = window.collectionBehavior
        behavior.remove(.canJoinAllSpaces)
        if overlayAvoidsSpaceSwitch {
            behavior.remove(.moveToActiveSpace)
            behavior.formUnion([.fullScreenAuxiliary, .stationary, .transient, .ignoresCycle])
        } else {
            behavior.formUnion([.fullScreenAuxiliary, .moveToActiveSpace])
        }
        window.collectionBehavior = behavior
        window.makeKeyAndOrderFront(nil)
        window.orderFrontRegardless()
        settingsWindow = window
        refreshOverlaySpaceHotkeyRegistration()
        refreshLauncherChromeState(
            activate: !overlayAvoidsSpaceSwitch,
            avoidSpaceSwitch: overlayAvoidsSpaceSwitch
        )
    }
 
    private func attachSettingsWindow(_ window: NSWindow, to overlayWindow: NSWindow) {
        if window.parent != overlayWindow {
            window.parent?.removeChildWindow(window)
            overlayWindow.addChildWindow(window, ordered: .above)
        }
    }
 
    private func detachSettingsWindow(_ window: NSWindow) {
        window.parent?.removeChildWindow(window)
    }
 
    private func isSettingsWindowCandidate(_ window: NSWindow) -> Bool {
        if window == settingsWindow { return true }
        if window.identifier?.rawValue == "TagLauncherPreferencesWindow" { return true }
        if isAppOwnedDocumentWindow(window) { return true }
        guard NSApp.windows.contains(window),
              window != overlayWindow,
              window.isVisible,
              !(window is NSPanel)
        else { return false }
        return settingsWindowTitleCandidates().contains(normalizedWindowTitle(window.title))
    }
 
    private func isAppOwnedDocumentWindow(_ window: NSWindow) -> Bool {
        NSApp.windows.contains(window)
            && window != overlayWindow
            && window.isVisible
            && !(window is NSPanel)
            && !isMenuTrackingWindow(window)
            && window.styleMask.contains(.titled)
    }
 
    private func isMenuTrackingWindow(_ window: NSWindow) -> Bool {
        let className = NSStringFromClass(type(of: window))
        return className.localizedCaseInsensitiveContains("Menu")
            || className.localizedCaseInsensitiveContains("Popup")
    }
 
    private func settingsWindowTitleCandidates() -> Set<String> {
        let keys = [
            "menu.preferences",
            "settings.language",
            "settings.general",
            "quickSearch.hotkeys",
            "settings.tags",
            "settings.data",
            "settings.about"
        ]
        return Set(keys.map { normalizedWindowTitle(tr($0)) })
    }
 
    private func normalizedWindowTitle(_ title: String) -> String {
        title
            .replacingOccurrences(of: "…", with: "")
            .trimmingCharacters(in: .whitespacesAndNewlines)
    }
 
    private func isSettingsOwnedPanel(_ window: NSWindow) -> Bool {
        guard window is NSPanel else { return false }
        if window is NSSavePanel { return true }
        guard let settingsWindow else { return false }
        return window.sheetParent == settingsWindow
            || settingsWindow.attachedSheet == window
            || window.parent == settingsWindow
    }
 
    private func center(_ window: NSWindow, over rect: NSRect) {
        let frame = window.frame
        let origin = NSPoint(
            x: rect.midX - frame.width / 2,
            y: rect.midY - frame.height / 2
        )
        window.setFrameOrigin(origin)
    }
 
    private func screenUnderMouse() -> NSScreen? {
        overlayController.screenUnderMouse()
    }
 
    /// Clean up settingsWindow reference when the Settings window closes.
    private func observeSettingsClose() {
        NotificationCenter.default.addObserver(
            forName: NSWindow.willCloseNotification,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let self,
                  let closingWindow = notification.object as? NSWindow,
                  closingWindow == self.settingsWindow
            else { return }
            let shouldRefocusOverlay = self.isOverlayVisible
            let preferredScreen = self.overlayWindow?.screen
            self.detachSettingsWindow(closingWindow)
            self.settingsWindow = nil
            self.refreshLauncherChromeState(
                activate: shouldRefocusOverlay && !self.overlayAvoidsSpaceSwitch,
                avoidSpaceSwitch: self.overlayAvoidsSpaceSwitch
            )
            self.refreshOverlaySpaceHotkeyRegistration()
            guard shouldRefocusOverlay else { return }
            DispatchQueue.main.asyncAfter(deadline: .now() + 0.12) { [weak self] in
                self?.showOrFocusOverlay(preferredScreen: preferredScreen)
            }
        }
    }
 
    /// Track whether the overlay is in edit mode to suppress auto-dismiss.
    private func observeEditMode() {
        NotificationCenter.default.addObserver(
            forName: .tagLauncherEditModeChanged,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let self else { return }
            self.isInEditMode = (notification.userInfo?["active"] as? Bool) ?? false
            self.refreshOverlaySpaceHotkeyRegistration()
        }
    }
 
    /// Keep text-input overlays at the launcher level so Quick Search stays visible in fullscreen Spaces.
    private func observeAppNoteEditing() {
        NotificationCenter.default.addObserver(
            forName: .tagLauncherAppNoteEditingChanged,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let self else { return }
            self.isEditingAppNote = (notification.userInfo?["active"] as? Bool) ?? false
            if self.isEditingAppNote {
                self.promoteOverlayToForegroundInput()
            }
            self.updateOverlayLevelForTextInput()
            self.refreshOverlaySpaceHotkeyRegistration()
        }
    }
 
    private func promoteOverlayToForegroundInput() {
        if overlayAvoidsSpaceSwitch {
            refreshLauncherChromeState(activate: false, avoidSpaceSwitch: true)
            guard let overlayWindow else { return }
            overlayWindow.makeKeyAndOrderFront(nil)
            overlayWindow.orderFrontRegardless()
            return
        }
        if quickSearchOnlyOverlaySession && !UserDefaults.standard.bool(forKey: Self.showDockIconKey) {
            refreshLauncherChromeState(activate: false)
            guard let overlayWindow else { return }
            NSApp.activate(ignoringOtherApps: true)
            overlayWindow.makeKeyAndOrderFront(nil)
            overlayWindow.orderFrontRegardless()
            return
        }
        beginLauncherForegroundOwnership()
        guard let overlayWindow else { return }
        overlayWindow.makeKeyAndOrderFront(nil)
        overlayWindow.orderFrontRegardless()
    }
 
    private func observeQuickSearch() {
        NotificationCenter.default.addObserver(
            forName: .tagLauncherQuickSearchVisibilityChanged,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let self else { return }
            let active = (notification.userInfo?["active"] as? Bool) ?? false
            let hideOverlayOnClose = (notification.userInfo?["hideOverlayOnClose"] as? Bool) ?? false
            let wasQuickSearchOnlyOverlay = self.quickSearchOnlyOverlaySession
                || self.quickSearchShouldHideOverlayOnClose
                || self.overlayOpenedByQuickSearchOnly
            Diagnostics.log("app.quickSearch.visibilityChanged", [
                "active": active,
                "hideOverlayOnClose": hideOverlayOnClose,
                "isQuickSearchOpenBefore": self.isQuickSearchOpen,
                "quickSearchOnlyOverlaySessionBefore": self.quickSearchOnlyOverlaySession,
                "quickSearchShouldHideOverlayOnCloseBefore": self.quickSearchShouldHideOverlayOnClose,
                "overlayOpenedByQuickSearchOnlyBefore": self.overlayOpenedByQuickSearchOnly,
                "wasQuickSearchOnlyOverlay": wasQuickSearchOnlyOverlay
            ])
            self.isQuickSearchOpen = active
            if active, hideOverlayOnClose {
                self.quickSearchShouldHideOverlayOnClose = true
                self.quickSearchOnlyOverlaySession = true
                self.overlayOpenedByQuickSearchOnly = true
            }
            if self.isQuickSearchOpen {
                self.promoteOverlayToForegroundInput()
            }
            self.updateOverlayLevelForTextInput()
            if self.isQuickSearchOpen {
                self.installQuickSearchExternalMouseMonitor()
            } else {
                self.removeQuickSearchExternalMouseMonitor()
                if hideOverlayOnClose || wasQuickSearchOnlyOverlay {
                    self.quickSearchShouldHideOverlayOnClose = false
                    self.quickSearchOnlyOverlaySession = false
                    self.hideOverlay(force: true, discardWindow: wasQuickSearchOnlyOverlay)
                }
            }
            self.refreshOverlaySpaceHotkeyRegistration()
        }
 
        NotificationCenter.default.addObserver(
            forName: .tagLauncherModalInteractionChanged,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            guard let self else { return }
            self.isModalInteractionActive = (notification.userInfo?["active"] as? Bool) ?? false
            self.refreshOverlaySpaceHotkeyRegistration()
        }
 
        NotificationCenter.default.addObserver(
            forName: NSApplication.didResignActiveNotification,
            object: NSApp,
            queue: .main
        ) { [weak self] _ in
            self?.handleApplicationDidResignActive()
        }
    }
 
    private func installQuickSearchExternalMouseMonitor() {
        installQuickSearchLocalMouseMonitor()
        guard quickSearchExternalMouseMonitor == nil else { return }
        quickSearchExternalMouseMonitor = NSEvent.addGlobalMonitorForEvents(
            matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
        ) { [weak self] _ in
            DispatchQueue.main.async {
                guard self?.isQuickSearchOpen == true else { return }
                NotificationCenter.default.post(
                    name: .tagLauncherQuickSearchDismissRequested,
                    object: nil,
                    userInfo: ["source": QuickSearchDismissSource.mouse]
                )
            }
        }
    }
 
    private func installQuickSearchLocalMouseMonitor() {
        guard quickSearchLocalMouseMonitor == nil else { return }
        quickSearchLocalMouseMonitor = NSEvent.addLocalMonitorForEvents(
            matching: [.leftMouseDown, .rightMouseDown, .otherMouseDown]
        ) { [weak self] event in
            guard let self, self.isQuickSearchOpen else { return event }
            if event.window === self.overlayWindow {
                return event
            }
            return event
        }
    }
 
    private func removeQuickSearchExternalMouseMonitor() {
        if let quickSearchLocalMouseMonitor {
            NSEvent.removeMonitor(quickSearchLocalMouseMonitor)
            self.quickSearchLocalMouseMonitor = nil
        }
        if let quickSearchExternalMouseMonitor {
            NSEvent.removeMonitor(quickSearchExternalMouseMonitor)
            self.quickSearchExternalMouseMonitor = nil
        }
    }
 
    private func updateOverlayLevelForTextInput() {
        guard let overlayWindow else { return }
        overlayWindow.level = currentOverlayLevel
        if let settingsWindow, settingsWindow.parent == overlayWindow {
            settingsWindow.level = overlayWindow.level
        }
    }
 
    /// The overlay buttons live inside SwiftUI; use an app-level notification like edit mode does.
    private func observePreferencesRequests() {
        NotificationCenter.default.addObserver(
            forName: .tagLauncherOpenPreferencesRequested,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            self?.openPreferences(targetTab: Self.preferencesTabTarget(from: notification))
        }
    }
 
    private static func preferencesTabTarget(from notification: Notification) -> String? {
        notification.userInfo?[SettingsTabTarget.userInfoKey] as? String
    }
 
    private func observeExternalActivationRequests() {
        DistributedNotificationCenter.default().addObserver(
            self,
            selector: #selector(handleExternalActivationRequest(_:)),
            name: Self.externalActivationNotification,
            object: Self.externalActivationObject
        )
    }
 
    @objc private func handleExternalActivationRequest(_ notification: Notification) {
        let shouldShowOverlay = notification.userInfo?["showOverlay"] as? Bool ?? false
        guard shouldShowOverlay else {
            suppressReopenUntil = Date().addingTimeInterval(1.0)
            return
        }
        showOrFocusOverlay()
    }
 
    @objc private func openPreferences(_ sender: Any? = nil) {
        openPreferences(targetTab: nil)
    }
 
    @objc private func openProStatusFromStatusMenu(_ sender: NSMenuItem) {
        openPreferences(targetTab: SettingsTabTarget.pro)
    }
 
    private func openPreferences(targetTab: String?) {
        explicitPreferencesOpenRequestedAt = Date()
        dismissQuickSearchIfNeeded()
        TagDatabase.flushPendingCategorySchemeBackupBatch()
        if overlayAvoidsSpaceSwitch {
            refreshLauncherChromeState(activate: false, avoidSpaceSwitch: true)
        } else {
            beginLauncherForegroundOwnership()
        }
        // Don't hide overlay — keep it visible for real-time setting preview.
        if let overlayWindow, overlayWindow.isVisible {
            overlayWindow.makeKeyAndOrderFront(nil)
            overlayWindow.orderFrontRegardless()
        }
 
        if let settingsWindow {
            prepareSettingsWindow(settingsWindow)
            requestPreferencesTabSelection(targetTab)
            return
        }
 
        let window = NSWindow(
            contentRect: NSRect(origin: .zero, size: Self.settingsContentSize),
            styleMask: [.titled, .closable],
            backing: .buffered,
            defer: false
        )
        window.title = tr("menu.preferences").replacingOccurrences(of: "…", with: "")
        window.contentView = NSHostingView(rootView: PreferencesView(initialTabRawValue: targetTab))
        window.isReleasedWhenClosed = false
        settingsWindow = window
        prepareSettingsWindow(window)
    }
 
    private func closeRestoredPreferencesWindowsDuringLaunch() {
        for delay in [0.25, 0.8, 1.6, 2.6] {
            DispatchQueue.main.asyncAfter(deadline: .now() + delay) { [weak self] in
                self?.closeRestoredPreferencesWindowIfNeeded()
            }
        }
    }
 
    private func closeRestoredPreferencesWindowIfNeeded() {
        guard Date().timeIntervalSince(explicitPreferencesOpenRequestedAt) > 3.0 else { return }
        for window in NSApp.windows where isSettingsWindowCandidate(window) {
            detachSettingsWindow(window)
            window.close()
            if settingsWindow == window {
                settingsWindow = nil
            }
        }
    }
 
    private func requestPreferencesTabSelection(_ targetTab: String?) {
        guard let targetTab else { return }
        NotificationCenter.default.post(
            name: .tagLauncherPreferencesTabRequested,
            object: nil,
            userInfo: [SettingsTabTarget.userInfoKey: targetTab]
        )
    }
 
    private func dismissQuickSearchIfNeeded() {
        guard isQuickSearchOpen else { return }
        isQuickSearchOpen = false
        removeQuickSearchExternalMouseMonitor()
        updateOverlayLevelForTextInput()
        quickSearchShouldHideOverlayOnClose = false
        quickSearchOnlyOverlaySession = false
        NotificationCenter.default.post(
            name: .tagLauncherQuickSearchDismissRequested,
            object: nil,
            userInfo: ["source": QuickSearchDismissSource.programmatic]
        )
    }
 
    @objc private func switchLanguage(_ sender: NSMenuItem) {
        guard let code = sender.representedObject as? String else { return }
        L10n.switchTo(code)
    }
}
 
// MARK: - NSView-level backdrop dismiss (works even if SwiftUI rendering is slow)
 
final class DismissibleHostingView<Content: View>: NSHostingView<Content> {
    private let onBackdropTap: () -> Void
    private var modalInteractionSuppressesBackdropDismiss = false
    private var quickSearchSuppressesBackdropDismiss = false
    private var modalInteractionObserver: NSObjectProtocol?
    private var quickSearchVisibilityObserver: NSObjectProtocol?
 
    private var suppressBackdropDismiss: Bool {
        modalInteractionSuppressesBackdropDismiss || quickSearchSuppressesBackdropDismiss
    }
 
    @MainActor required init(rootView: Content) {
        self.onBackdropTap = {}
        super.init(rootView: rootView)
        installWindowServerAnchorLayer()
        observeBackdropDismissSuppressionChanges()
    }
 
    init(rootView: Content, onBackdropTap: @escaping () -> Void) {
        self.onBackdropTap = onBackdropTap
        super.init(rootView: rootView)
        installWindowServerAnchorLayer()
        observeBackdropDismissSuppressionChanges()
    }
 
    deinit {
        if let modalInteractionObserver {
            NotificationCenter.default.removeObserver(modalInteractionObserver)
        }
        if let quickSearchVisibilityObserver {
            NotificationCenter.default.removeObserver(quickSearchVisibilityObserver)
        }
    }
 
    @available(*, unavailable)
    required init?(coder: NSCoder) { fatalError() }
 
    private func installWindowServerAnchorLayer() {
        wantsLayer = true
        // A near-transparent backing pixel makes the WindowServer publish the panel immediately.
        layer?.backgroundColor = NSColor.black.withAlphaComponent(0.001).cgColor
    }
 
    override func mouseDown(with event: NSEvent) {
        let location = convert(event.locationInWindow, from: nil)
        guard let hit = hitTest(location) else {
            super.mouseDown(with: event)
            return
        }
        if routeUsageTipsMouseDownIfNeeded(event) {
            return
        }
        if hit == self {
            if shouldSwallowUsageTipsBackdropClick(at: location) {
                return
            }
            if quickSearchSuppressesBackdropDismiss {
                NotificationCenter.default.post(
                    name: .tagLauncherQuickSearchDismissRequested,
                    object: nil,
                    userInfo: ["source": QuickSearchDismissSource.backdrop]
                )
                return
            }
            if suppressBackdropDismiss {
                super.mouseDown(with: event)
                return
            }
            onBackdropTap()
            return
        }
        if let floatingButton = findFloatingIconButton(at: event.locationInWindow, in: self) {
            floatingButton.mouseDown(with: event)
            return
        }
        // Recursively search hit subtree for TextFieldContainer or NSTextField.
        // NSHostingView.hitTest may return a SwiftUI-internal wrapper — the
        // actual AppKit subview may be nested deeper.
        if let container = findTextFieldContainer(in: hit) {
            container.focusTextField()
            return
        }
        if let tf = findNSTextField(in: hit) {
            let shouldSelectAll = tf.currentEditor() == nil
            tf.window?.makeFirstResponder(tf)
            if shouldSelectAll {
                tf.selectText(nil)
            }
            return
        }
        super.mouseDown(with: event)
    }
 
    private func routeUsageTipsMouseDownIfNeeded(_ event: NSEvent) -> Bool {
        guard let appGridHost = findAppGridCollectionHost(in: self) else { return false }
        return appGridHost.handleUsageTipsMouseDown(event)
    }
 
    private func findAppGridCollectionHost(in view: NSView) -> AppGridCollectionHostView? {
        if let host = view as? AppGridCollectionHostView {
            return host
        }
        for subview in view.subviews {
            if let host = findAppGridCollectionHost(in: subview) {
                return host
            }
        }
        return nil
    }
 
    private func shouldSwallowUsageTipsBackdropClick(at location: NSPoint) -> Bool {
        guard !UserDefaults.standard.bool(forKey: "hideUsageTips") else { return false }
        let height = min(bounds.height, AppGridUsageTipsMetrics.reservedHeight)
        guard height > 0 else { return false }
        let y = isFlipped ? max(0, bounds.height - height) : 0
        let region = NSRect(x: 0, y: y, width: bounds.width, height: height)
        return region.contains(location)
    }
 
    private func observeBackdropDismissSuppressionChanges() {
        modalInteractionObserver = NotificationCenter.default.addObserver(
            forName: .tagLauncherModalInteractionChanged,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            self?.modalInteractionSuppressesBackdropDismiss = (notification.userInfo?["active"] as? Bool) ?? false
        }
 
        quickSearchVisibilityObserver = NotificationCenter.default.addObserver(
            forName: .tagLauncherQuickSearchVisibilityChanged,
            object: nil,
            queue: .main
        ) { [weak self] notification in
            self?.quickSearchSuppressesBackdropDismiss = (notification.userInfo?["active"] as? Bool) ?? false
        }
    }
 
    private func findTextFieldContainer(in view: NSView) -> TextFieldContainer? {
        if let container = view as? TextFieldContainer { return container }
        for sub in view.subviews {
            if let found = findTextFieldContainer(in: sub) { return found }
        }
        return nil
    }
 
    private func findNSTextField(in view: NSView) -> NSTextField? {
        if let tf = view as? NSTextField, tf.isEditable { return tf }
        for sub in view.subviews {
            if let found = findNSTextField(in: sub) { return found }
        }
        return nil
    }
 
    private func findFloatingIconButton(at windowPoint: NSPoint, in view: NSView) -> FloatingIconButtonView? {
        for subview in view.subviews.reversed() where !subview.isHidden {
            if let found = findFloatingIconButton(at: windowPoint, in: subview) {
                return found
            }
        }
        guard let floatingButton = view as? FloatingIconButtonView else { return nil }
        let localPoint = floatingButton.convert(windowPoint, from: nil)
        if floatingButton.bounds.contains(localPoint) {
            return floatingButton
        }
        return nil
    }
 
}