worker-service 0.2.0

Worker Service - A worker administration microservice that interoperates with the worker-matcher crate
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
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{% block title %}{{ app_display }}{% endblock title %}</title>
  <link rel="stylesheet" href="/static/css/lily.css">
  <script src="/static/js/htmx.min.js" defer></script>
  <script src="/static/js/alpine.min.js" defer></script>
  <script>
    // Apply persisted theme, locale, and accent color as early as possible
    // to avoid FOUC. Accent overrides --nhs-blue on <html> so everything
    // that reads `var(--nhs-blue)` (buttons, focus rings, breadcrumb
    // arrows, etc.) recolors atomically.
    (function () {
      'use strict';
      var rtl = { ar: 1, fa: 1, ur: 1 };
      try {
        var t = localStorage.getItem('lily-theme');
        if (t === 'dark' || t === 'high-contrast') {
          document.documentElement.setAttribute('data-theme', t);
        }
        var loc = localStorage.getItem('lily-locale');
        if (loc && /^[a-z]{2}$/.test(loc)) {
          document.documentElement.setAttribute('lang', loc);
          document.documentElement.setAttribute('dir', rtl[loc] ? 'rtl' : 'ltr');
        }
        var acc = localStorage.getItem('lily-accent');
        if (acc && /^#[0-9a-fA-F]{6}$/.test(acc)) {
          document.documentElement.style.setProperty('--nhs-blue', acc);
        }
      } catch (e) { /* ignore */ }
    })();
  </script>
</head>
<body>
  <a class="skip-link" aria-label="Skip to main content" href="#main-content">Skip to main content</a>

  <div class="super-banner"
       role="alert"
       aria-live="assertive"
       aria-label="System announcement"
       data-type="warning"
       x-data='{
         id: "maintenance-2026-05-29",
         dismissed: false,
         init() {
           try {
             var key = "lily-super-banner-dismissed-" + this.id;
             this.dismissed = localStorage.getItem(key) === "1";
           } catch (e) { /* ignore */ }
         },
         dismiss() {
           this.dismissed = true;
           try {
             localStorage.setItem("lily-super-banner-dismissed-" + this.id, "1");
           } catch (e) { /* ignore */ }
           if (window.lily &amp;&amp; window.lily.toast) {
             window.lily.toast("Banner dismissed", "info");
           }
         }
       }'
       x-init="init()"
       x-show="!dismissed">
    <div class="banner-box">
      <span>
        <strong>Scheduled maintenance</strong> on 2026-05-29 02:00–04:00 UTC.
        Read-only access during the window. See
        <a href="/health" aria-label="Open system health page for status">system status</a>.
      </span>
      <button type="button"
              aria-label="Dismiss announcement"
              @click="dismiss()">Dismiss</button>
    </div>
  </div>

  <header class="header" aria-label="Site header">
    <h1>{{ app_display }}</h1>
    <nav class="navigation-menu" aria-label="Primary navigation">
      <ul>
        <li><a href="/">Home</a></li>
        <li><a href="/{{ entity_plural }}">{{ entity_plural | capitalize }}</a></li>
        <li><a href="/{{ entity_plural }}/search">Search</a></li>
        <li><a href="/{{ entity_plural }}/review-queue">Review queue</a></li>
        <li><a href="/audit">Audit</a></li>
        <li><a href="/notifications" aria-label="Notification center">Notifications</a></li>
        <li><a href="/health">Health</a></li>
        <li><a href="/metrics">Metrics</a></li>
        <li><a href="/tour">Tour</a></li>
        <li><a href="/docs">API docs</a></li>
        <li><a href="/settings">Settings</a></li>
      </ul>
    </nav>

    <div class="theme-picker" aria-label="Theme picker">
      <label class="label" for="theme-select">Theme</label>
      <select id="theme-select"
              class="theme-select"
              aria-label="Choose a visual theme">
        <option class="theme-select-option" value="">NHS UK (default)</option>
        <option class="theme-select-option" value="dark">Dark</option>
        <option class="theme-select-option" value="high-contrast">High contrast</option>
      </select>
    </div>

    <div class="locale-picker" aria-label="Locale picker">
      <label class="label" for="locale-select">Language</label>
      <select id="locale-select"
              class="select"
              aria-label="Choose a display language">
        <option value="">English (default)</option>
        <option value="ar">العربية &middot; Arabic</option>
        <option value="bg">Български &middot; Bulgarian</option>
        <option value="bh">भोजपुरी &middot; Bhojpuri</option>
        <option value="bn">বাংলা &middot; Bengali</option>
        <option value="cs">Čeština &middot; Czech</option>
        <option value="cy">Cymraeg &middot; Welsh</option>
        <option value="da">Dansk &middot; Danish</option>
        <option value="de">Deutsch &middot; German</option>
        <option value="el">Ελληνικά &middot; Greek</option>
        <option value="en">English</option>
        <option value="es">Español &middot; Spanish</option>
        <option value="et">Eesti &middot; Estonian</option>
        <option value="eu">Euskara &middot; Basque</option>
        <option value="fa">فارسی &middot; Persian</option>
        <option value="fi">Suomi &middot; Finnish</option>
        <option value="fr">Français &middot; French</option>
        <option value="ga">Gaeilge &middot; Irish</option>
        <option value="gu">ગુજરાતી &middot; Gujarati</option>
        <option value="ha">Harshen Hausa &middot; Hausa</option>
        <option value="hi">हिन्दी &middot; Hindi</option>
        <option value="hr">Hrvatski &middot; Croatian</option>
        <option value="hu">Magyar &middot; Hungarian</option>
        <option value="id">Bahasa Indonesia &middot; Indonesian</option>
        <option value="it">Italiano &middot; Italian</option>
        <option value="ja">日本語 &middot; Japanese</option>
        <option value="jv">Basa Jawa &middot; Javanese</option>
        <option value="ko">한국어 &middot; Korean</option>
        <option value="lt">Lietuvių &middot; Lithuanian</option>
        <option value="lv">Latviešu &middot; Latvian</option>
        <option value="mr">मराठी &middot; Marathi</option>
        <option value="mt">Malti &middot; Maltese</option>
        <option value="nl">Nederlands &middot; Dutch</option>
        <option value="pa">ਪੰਜਾਬੀ &middot; Punjabi</option>
        <option value="pl">Polski &middot; Polish</option>
        <option value="pt">Português &middot; Portuguese</option>
        <option value="ro">Română &middot; Romanian</option>
        <option value="ru">Русский &middot; Russian</option>
        <option value="sk">Slovenčina &middot; Slovak</option>
        <option value="sl">Slovenščina &middot; Slovenian</option>
        <option value="sv">Svenska &middot; Swedish</option>
        <option value="ta">தமிழ் &middot; Tamil</option>
        <option value="te">తెలుగు &middot; Telugu</option>
        <option value="tr">Türkçe &middot; Turkish</option>
        <option value="ur">اردو &middot; Urdu</option>
        <option value="vi">Tiếng Việt &middot; Vietnamese</option>
        <option value="zh">普通话 &middot; Mandarin</option>
      </select>
    </div>
  </header>

  <main id="main-content" class="page-wrapper">
    {% block content %}{% endblock content %}
  </main>

  <footer class="footer" aria-label="Site footer">
    <p>&copy; 2026 {{ app_display }} &mdash; styled with the
       <a href="https://lilydesignsystem.github.io">Lily Design System</a>,
       powered by <a href="https://loco.rs">Loco</a>,
       <a href="https://keats.github.io/tera/">Tera</a>,
       <a href="https://htmx.org">HTMX</a>, and
       <a href="https://alpinejs.dev">Alpine</a>.</p>
  </footer>

  <dialog id="command-palette"
          class="dialog"
          role="dialog"
          aria-modal="true"
          aria-label="Command palette"
          x-data='{
            query: "",
            activeIndex: 0,
            commands: [
              { label: "Go to Home",            hint: "Top-level landing page",       kb: ["g","h"], href: "/" },
              { label: "Go to {{ entity_plural | capitalize }}", hint: "{{ entity_plural | capitalize }} index", kb: ["g","i"], href: "/{{ entity_plural }}" },
              { label: "Search",                hint: "Full-text + filters",          kb: ["g","s"], href: "/{{ entity_plural }}/search" },
              { label: "Review queue",          hint: "Pending duplicates",           kb: ["g","r"], href: "/{{ entity_plural }}/review-queue" },
              { label: "Compare two records",   hint: "Side-by-side match",                          href: "/{{ entity_plural }}/compare?a=aaaa-1&amp;b=aaaa-2" },
              { label: "Calendar",              hint: "Records by creation date",                    href: "/{{ entity_plural }}/calendar" },
              { label: "Map",                   hint: "Geo pins",                                     href: "/{{ entity_plural }}/map" },
              { label: "Import CSV",            hint: "Bulk-import wizard",                          href: "/{{ entity_plural }}/import" },
              { label: "System audit",          hint: "Recent activity",              kb: ["g","a"], href: "/audit" },
              { label: "System health",         hint: "RAG + subsystem status",       kb: ["g","e"], href: "/health" },
              { label: "Performance metrics",   hint: "Sparklines per endpoint",                     href: "/metrics" },
              { label: "Guided tour",           hint: "8-step walkthrough",                          href: "/tour" },
              { label: "API documentation",     hint: "REST + FHIR endpoint reference",              href: "/docs" },
              { label: "Color palette",         hint: "Full NHS token customizer",                   href: "/palette" },
              { label: "Settings",              hint: "Per-browser preferences",                     href: "/settings" },
              { label: "Show keyboard shortcuts", hint: "Open the shortcuts dialog",  kb: ["?"],     action: "shortcuts" },
              { label: "Switch theme: NHS UK (default)", hint: "Light theme",                        action: "theme:" },
              { label: "Switch theme: Dark",    hint: "Inverted neutrals",                            action: "theme:dark" },
              { label: "Switch theme: High contrast", hint: "Pure black on white",                   action: "theme:high-contrast" },
              { label: "Reset palette",         hint: "Clear all token overrides",                   action: "palette:reset" }
            ],
            filtered() {
              var q = this.query.trim().toLowerCase();
              if (!q) return this.commands;
              return this.commands.filter(function (c) {
                return c.label.toLowerCase().indexOf(q) !== -1
                    || (c.hint || "").toLowerCase().indexOf(q) !== -1;
              });
            },
            invoke(c) {
              if (c.href) {
                window.location.href = c.href;
              } else if (c.action === "shortcuts") {
                document.getElementById("command-palette").close();
                document.getElementById("shortcuts-dialog").showModal();
              } else if (c.action &amp;&amp; c.action.indexOf("theme:") === 0) {
                var t = c.action.slice(6);
                if (t) {
                  document.documentElement.setAttribute("data-theme", t);
                  try { localStorage.setItem("lily-theme", t); } catch (e) {}
                } else {
                  document.documentElement.removeAttribute("data-theme");
                  try { localStorage.removeItem("lily-theme"); } catch (e) {}
                }
                if (window.lily &amp;&amp; window.lily.toast) {
                  window.lily.toast("Theme switched", "info");
                }
                document.getElementById("command-palette").close();
              } else if (c.action === "palette:reset") {
                try {
                  var stored = JSON.parse(localStorage.getItem("lily-palette") || "{}");
                  Object.keys(stored).forEach(function (k) {
                    document.documentElement.style.removeProperty("--" + k);
                  });
                  localStorage.removeItem("lily-palette");
                } catch (e) {}
                if (window.lily &amp;&amp; window.lily.toast) {
                  window.lily.toast("Palette reset", "warning");
                }
                document.getElementById("command-palette").close();
              }
            },
            step(delta) {
              var n = this.filtered().length;
              if (n === 0) return;
              this.activeIndex = (this.activeIndex + delta + n) % n;
            },
            choose() {
              var f = this.filtered();
              var pick = f[this.activeIndex] || f[0];
              if (pick) this.invoke(pick);
            }
          }'>
    <h2>Command palette</h2>
    <input class="text-input-with-search"
           type="search"
           role="searchbox"
           aria-label="Filter commands"
           placeholder="Type to filter commands&hellip;"
           autocomplete="off"
           autofocus
           x-model="query"
           @input="activeIndex = 0"
           @keydown.arrow-down.prevent="step(1)"
           @keydown.arrow-up.prevent="step(-1)"
           @keydown.enter.prevent="choose()">
    <ol class="command" aria-label="Matching commands" role="listbox">
      <template x-for="(c, i) in filtered()" :key="c.label">
        <li role="option"
            x-bind:aria-selected="i === activeIndex ? 'true' : 'false'"
            x-bind:data-active="i === activeIndex ? 'true' : 'false'"
            tabindex="-1"
            @click="activeIndex = i; choose()"
            @mouseover="activeIndex = i">
          <strong x-text="c.label"></strong>
          <template x-if="c.kb">
            <span>
              <template x-for="k in c.kb" :key="k">
                <kbd class="kbd" x-text="k"></kbd>
              </template>
            </span>
          </template>
          <br>
          <span class="hint" x-text="c.hint"></span>
        </li>
      </template>
      <li role="option" x-show="filtered().length === 0" aria-disabled="true">
        <span class="hint" aria-label="Empty filter">No commands match.</span>
      </li>
    </ol>
    <form method="dialog" class="form" aria-label="Close command palette">
      <button class="button" type="submit" aria-label="Close">Close</button>
    </form>
  </dialog>

  <dialog id="shortcuts-dialog"
          class="dialog"
          role="dialog"
          aria-modal="true"
          aria-labelledby="shortcuts-title">
    <h2 id="shortcuts-title">Keyboard shortcuts</h2>
    <ol class="summary-list" aria-label="Available shortcuts">
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">?</kbd></dt>
          <dd>Show / hide this dialog</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">Ctrl</kbd> <kbd class="kbd">K</kbd> &middot; <kbd class="kbd"></kbd> <kbd class="kbd">K</kbd></dt>
          <dd>Open the command palette (works inside inputs too)</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">/</kbd></dt>
          <dd>Focus the search field on this page</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">g</kbd> <kbd class="kbd">h</kbd></dt>
          <dd>Go to Home</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">g</kbd> <kbd class="kbd">i</kbd></dt>
          <dd>Go to the {{ entity_plural }} index</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">g</kbd> <kbd class="kbd">s</kbd></dt>
          <dd>Go to Search</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">g</kbd> <kbd class="kbd">r</kbd></dt>
          <dd>Go to the Review queue</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">g</kbd> <kbd class="kbd">a</kbd></dt>
          <dd>Go to the system Audit log</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">g</kbd> <kbd class="kbd">e</kbd></dt>
          <dd>Go to system Health</dd>
        </dl>
      </li>
      <li class="summary-list-item">
        <dl>
          <dt><kbd class="kbd">Esc</kbd></dt>
          <dd>Close any open dialog</dd>
        </dl>
      </li>
    </ol>
    <form method="dialog" class="form" aria-label="Close shortcuts">
      <button class="button" type="submit" aria-label="Close">Close</button>
    </form>
  </dialog>

  <div id="htmx-indicator" aria-live="polite">
    <div class="progress-spinner"
         role="progressbar"
         aria-label="Loading"
         aria-busy="true"></div>
    <span>Loading&hellip;</span>
  </div>

  <div id="toast-region"
       class="sonner"
       role="status"
       aria-label="Notifications"
       aria-live="polite"></div>

  <script>
    // Lily toast bridge.
    //
    // - `lily.toast(message, type)` — inserts a `<div class="toast" data-type="...">`
    //   into the `#toast-region` sonner and removes it after 5s.
    // - Listens for the HTMX `showToast` event so controllers can emit
    //   `HX-Trigger: {"showToast":{"message":"…","type":"success"}}` headers.
    (function () {
      'use strict';
      var region = document.getElementById('toast-region');
      function spawn(message, type) {
        if (!region || !message) return;
        var t = document.createElement('div');
        t.className = 'toast';
        t.setAttribute('role', 'status');
        t.setAttribute('aria-live', 'polite');
        if (type) t.setAttribute('data-type', String(type));
        t.setAttribute('aria-label', String(message));
        t.textContent = String(message);
        region.appendChild(t);
        setTimeout(function () { t.remove(); }, 5000);
      }
      window.lily = window.lily || {};
      window.lily.toast = spawn;
      document.body.addEventListener('showToast', function (evt) {
        var d = evt.detail || {};
        spawn(d.message || d.value || '', d.type || 'info');
      });
    })();

    // Lily HTMX request indicator bridge.
    //
    // Counts in-flight HTMX requests and toggles `data-active="true"` on
    // `#htmx-indicator` while any are in flight. Uses HTMX's lifecycle
    // events so the spinner stays visible across overlapping requests.
    (function () {
      'use strict';
      var indicator = document.getElementById('htmx-indicator');
      if (!indicator) return;
      var inflight = 0;
      function update() {
        if (inflight > 0) {
          indicator.setAttribute('data-active', 'true');
        } else {
          indicator.removeAttribute('data-active');
        }
      }
      document.body.addEventListener('htmx:beforeRequest', function () {
        inflight += 1;
        update();
      });
      document.body.addEventListener('htmx:afterRequest', function () {
        inflight = Math.max(0, inflight - 1);
        update();
      });
      document.body.addEventListener('htmx:responseError', function () {
        inflight = Math.max(0, inflight - 1);
        update();
        if (window.lily && window.lily.toast) {
          window.lily.toast('Request failed', 'error');
        }
      });
      document.body.addEventListener('htmx:sendError', function () {
        inflight = Math.max(0, inflight - 1);
        update();
        if (window.lily && window.lily.toast) {
          window.lily.toast('Network error', 'error');
        }
      });
    })();

    // Lily hover-card bridge.
    //
    // Any `<button class="hover-card-trigger" aria-describedby="ID">` toggles
    // `data-open="true"` on the `.hover-card` with that ID. The bridge wires
    // mouseenter/mouseleave plus focus/blur so the card works for both
    // mouse and keyboard users, and Escape closes any open card.
    (function () {
      'use strict';
      function findCard(trigger) {
        var id = trigger.getAttribute('aria-describedby');
        return id ? document.getElementById(id) : null;
      }
      function open(card) { if (card) card.setAttribute('data-open', 'true'); }
      function close(card) { if (card) card.removeAttribute('data-open'); }

      document.addEventListener('mouseover', function (evt) {
        var t = evt.target.closest('.hover-card-trigger');
        if (t) open(findCard(t));
      });
      document.addEventListener('mouseout', function (evt) {
        var t = evt.target.closest('.hover-card-trigger');
        if (t) close(findCard(t));
      });
      document.addEventListener('focusin', function (evt) {
        var t = evt.target.closest('.hover-card-trigger');
        if (t) open(findCard(t));
      });
      document.addEventListener('focusout', function (evt) {
        var t = evt.target.closest('.hover-card-trigger');
        if (t) close(findCard(t));
      });
      document.addEventListener('keydown', function (evt) {
        if (evt.key === 'Escape') {
          document.querySelectorAll('.hover-card[data-open="true"]').forEach(close);
        }
      });
    })();

    // Lily keyboard-shortcuts bridge.
    //
    // - `?` (Shift+/) toggles the #shortcuts-dialog.
    // - `/` focuses the first text/search input on the page.
    // - `g` followed by a navigation key (h/i/s/r/a/e) within 1500 ms
    //   navigates to the matching primary section.
    // All bindings are suppressed while the user is typing into an
    // input, textarea, or contenteditable element.
    (function () {
      'use strict';
      var entityPlural = "{{ entity_plural }}";
      var nav = {
        h: '/',
        i: '/' + entityPlural,
        s: '/' + entityPlural + '/search',
        r: '/' + entityPlural + '/review-queue',
        a: '/audit',
        e: '/health'
      };
      var dlg = document.getElementById('shortcuts-dialog');
      var pendingGoto = 0;

      function isTyping(target) {
        if (!target) return false;
        var tag = target.tagName;
        return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || target.isContentEditable;
      }

      document.addEventListener('keydown', function (evt) {
        // Ctrl+K / Cmd+K opens the command palette (works even inside inputs).
        if ((evt.metaKey || evt.ctrlKey) && evt.key === 'k') {
          evt.preventDefault();
          var pal = document.getElementById('command-palette');
          if (pal) {
            if (pal.open) {
              pal.close();
            } else {
              pal.showModal();
            }
          }
          return;
        }

        if (evt.metaKey || evt.ctrlKey || evt.altKey) return;
        if (isTyping(evt.target)) return;

        if (evt.key === '?') {
          evt.preventDefault();
          if (dlg) {
            if (dlg.open) {
              dlg.close();
            } else {
              dlg.showModal();
            }
          }
          return;
        }

        if (evt.key === '/') {
          var input = document.querySelector('input[type="search"], input[type="text"]');
          if (input) {
            evt.preventDefault();
            input.focus();
          }
          return;
        }

        if (evt.key === 'g') {
          pendingGoto = Date.now();
          return;
        }

        if (pendingGoto && Date.now() - pendingGoto < 1500) {
          var dest = nav[evt.key];
          if (dest) {
            evt.preventDefault();
            pendingGoto = 0;
            window.location.href = dest;
          }
        }
      });
    })();

    // Lily theme-picker wiring.
    //
    // The early-bootstrap script in <head> already applied the persisted
    // theme to avoid FOUC. This block syncs the visible <select> to the
    // current value, persists changes to localStorage, and spawns a
    // confirmation toast on each switch.
    (function () {
      'use strict';
      var picker = document.getElementById('theme-select');
      if (!picker) return;
      var current = document.documentElement.getAttribute('data-theme') || '';
      picker.value = current;
      picker.addEventListener('change', function () {
        var t = picker.value;
        if (t === 'dark' || t === 'high-contrast') {
          document.documentElement.setAttribute('data-theme', t);
          try { localStorage.setItem('lily-theme', t); } catch (e) { /* ignore */ }
        } else {
          document.documentElement.removeAttribute('data-theme');
          try { localStorage.removeItem('lily-theme'); } catch (e) { /* ignore */ }
        }
        if (window.lily && window.lily.toast) {
          var label = picker.options[picker.selectedIndex] && picker.options[picker.selectedIndex].text;
          window.lily.toast('Theme: ' + (label || 'default'), 'info');
        }
      });
    })();

    // Lily locale-picker wiring.
    //
    // Mirrors the theme-picker pattern: the early-bootstrap script in <head>
    // already applied the persisted `lang` + `dir` attributes to avoid FOUC.
    // This block syncs the visible <select> to the current value, persists
    // changes to localStorage, sets `dir="rtl"` for ar/fa/ur, and spawns a
    // confirmation toast on each switch.
    (function () {
      'use strict';
      var picker = document.getElementById('locale-select');
      if (!picker) return;
      var RTL = { ar: 1, fa: 1, ur: 1 };
      var current = document.documentElement.getAttribute('lang') || '';
      // Default <html lang="en"> means the picker's empty value covers English.
      picker.value = (current === 'en') ? '' : current;
      picker.addEventListener('change', function () {
        var loc = picker.value;
        if (loc && /^[a-z]{2}$/.test(loc)) {
          document.documentElement.setAttribute('lang', loc);
          document.documentElement.setAttribute('dir', RTL[loc] ? 'rtl' : 'ltr');
          try { localStorage.setItem('lily-locale', loc); } catch (e) { /* ignore */ }
        } else {
          document.documentElement.setAttribute('lang', 'en');
          document.documentElement.setAttribute('dir', 'ltr');
          try { localStorage.removeItem('lily-locale'); } catch (e) { /* ignore */ }
        }
        if (window.lily && window.lily.toast) {
          var label = picker.options[picker.selectedIndex] && picker.options[picker.selectedIndex].text;
          window.lily.toast('Language: ' + (label || 'default'), 'info');
        }
      });
    })();

    // Lily clipboard-copy-button bridge.
    //
    // Each `.clipboard-copy-button` reads `data-clipboard-text` (or its own
    // textContent), writes it via the async Clipboard API, sets
    // `data-copied="true"` on the button for ~2 s, and spawns a success toast.
    (function () {
      'use strict';
      document.addEventListener('click', function (evt) {
        var el = evt.target.closest('.clipboard-copy-button');
        if (!el) return;
        var text = el.getAttribute('data-clipboard-text') || el.textContent || '';
        if (!navigator.clipboard) {
          if (window.lily && window.lily.toast) {
            window.lily.toast('Clipboard not supported by this browser', 'error');
          }
          return;
        }
        navigator.clipboard.writeText(text).then(function () {
          el.setAttribute('data-copied', 'true');
          setTimeout(function () { el.removeAttribute('data-copied'); }, 2000);
          if (window.lily && window.lily.toast) {
            window.lily.toast(el.getAttribute('data-copied-message') || 'Copied to clipboard', 'success');
          }
        });
      });
    })();
  </script>
</body>
</html>