aboutsummaryrefslogtreecommitdiff
path: root/internal/server/templates/index.html
blob: 684819dbef19dfa4d3640a9d1f7fa8f6365f9133 (plain) (blame)
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
<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        :root { --scale: {{.Scale}}; }
    </style>
    {{if .ThemeCSS}}
    <style>
        /* OpenCode Theme - Loaded before external CSS to prevent flash */
{{.ThemeCSS}}
    </style>
    {{end}}
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{.Site.Name}} [↑{{.StatusCounts.Up}}{{if gt .StatusCounts.Down 0}}/{{.StatusCounts.Down}}↓{{end}}]</title>
    <meta name="description" content="{{.Site.Description}}">
    {{if .Site.Favicon}}
    <link rel="icon" href="{{.Site.Favicon}}">
    {{else}}
    <link rel="icon" href="data:image/svg+xml,<svg xmlns=%22http://www.w3.org/2000/svg%22 viewBox=%220 0 100 100%22><text y=%22.9em%22 font-size=%2290%22>🎐</text></svg>">
    {{end}}
    <link rel="stylesheet" href="/static/style.css">
    {{if .CustomHead}}{{.CustomHead}}{{end}}
</head>
<body class="bg-neutral-50 dark:bg-neutral-950 text-neutral-900 dark:text-neutral-100 min-h-screen font-mono">
    <div class="max-w-4xl mx-auto px-4 py-8 sm:py-12">
        <!-- Header -->
        <header class="mb-8 sm:mb-12">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    {{if .Site.Logo}}
                    <img src="{{.Site.Logo}}" alt="Logo" class="h-8 w-8">
                    {{end}}
                    <div>
                        <h1 class="text-xl sm:text-2xl font-bold tracking-tight">{{.Site.Name}}</h1>
                        <p class="text-sm text-neutral-500 dark:text-neutral-400">{{.Site.Description}}</p>
                    </div>
                </div>

            </div>
        </header>

        <!-- Overall Status Banner -->
        <div class="mb-8 p-4 rounded-lg border {{if eq .OverallStatus "All Systems Operational"}}bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-900{{else if eq .OverallStatus "Partial Outage"}}bg-yellow-50 dark:bg-yellow-950/30 border-yellow-200 dark:border-yellow-900{{else}}bg-red-50 dark:bg-red-950/30 border-red-200 dark:border-red-900{{end}}">
            <div class="flex items-center justify-between">
                <div class="flex items-center gap-3">
                    <div class="flex-shrink-0">
                        {{if eq .OverallStatus "All Systems Operational"}}
                        <div class="w-3 h-3 rounded-full bg-emerald-500 animate-pulse"></div>
                        {{else if eq .OverallStatus "Partial Outage"}}
                        <div class="w-3 h-3 rounded-full bg-yellow-500 animate-pulse"></div>
                        {{else}}
                        <div class="w-3 h-3 rounded-full bg-red-500 animate-pulse"></div>
                        {{end}}
                    </div>
                    <span class="font-medium">{{.OverallStatus}}</span>
                </div>
                <span class="text-sm text-neutral-500 dark:text-neutral-400" data-tooltip='{{.TimezoneTooltip}}'{{if .UseBrowserTimezone}} data-timestamp="{{.LastUpdated.Format "2006-01-02T15:04:05Z07:00"}}" data-format="datetime"{{end}}>{{.CurrentTime}}</span>
            </div>
        </div>

        <!-- Monitor Groups -->
        <div class="space-y-6">
            {{range $groupIndex, $group := .Groups}}
            <section class="border border-neutral-200 dark:border-neutral-800 rounded-lg overflow-hidden" data-group="{{$group.Name}}">
                <div class="px-4 py-3 bg-neutral-100 dark:bg-neutral-900 border-b border-neutral-200 dark:border-neutral-800 cursor-pointer hover:bg-neutral-200 dark:hover:bg-neutral-800 transition-colors" onclick="toggleGroup('{{$group.Name}}')">
                    <div class="flex items-center justify-between">
                        <div class="flex items-center gap-3">
                            <svg class="w-4 h-4 text-neutral-600 dark:text-neutral-400 transition-transform" data-group-icon="{{$group.Name}}" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/>
                            </svg>
                            <h2 class="font-semibold text-sm uppercase tracking-wider text-neutral-600 dark:text-neutral-400">{{$group.Name}}</h2>
                        </div>
                        {{if $group.ShowGroupUptime}}
                        <span class="text-sm font-medium {{if ge $group.GroupUptime 99.0}}text-emerald-600 dark:text-emerald-400{{else if ge $group.GroupUptime 95.0}}text-yellow-600 dark:text-yellow-400{{else}}text-red-600 dark:text-red-400{{end}}">{{formatUptime $group.GroupUptime}}</span>
                        {{end}}
                    </div>
                </div>
                <div class="divide-y divide-neutral-200 dark:divide-neutral-800 group-content" data-group-content="{{$group.Name}}" data-default-collapsed="{{$group.DefaultCollapsed}}">
                    {{range .Monitors}}
                    {{$monitor := .}}
                    <div class="p-4 hover:bg-neutral-100/50 dark:hover:bg-neutral-900/50 transition-colors" data-monitor="{{.Name}}" data-group="{{$group.Name}}"{{if .HidePing}} data-hide-ping{{end}}{{if .DisablePingTooltips}} data-disable-tooltips{{end}}>
                        <div class="flex items-start justify-between gap-4">
                            <div class="flex-1 min-w-0">
                                <div class="flex items-center gap-2 mb-2">
                                    {{if eq .Status "up"}}
                                    <div class="w-2 h-2 rounded-full bg-emerald-500 flex-shrink-0"></div>
                                    {{else if eq .Status "degraded"}}
                                    <div class="w-2 h-2 rounded-full bg-yellow-500 flex-shrink-0"></div>
                                    {{else if eq .Status "down"}}
                                    <div class="w-2 h-2 rounded-full bg-red-500 flex-shrink-0"></div>
                                    {{else}}
                                    <div class="w-2 h-2 rounded-full bg-neutral-400 flex-shrink-0"></div>
                                    {{end}}
                                    {{if .Link}}<a href="{{.Link}}" target="_blank" rel="noopener noreferrer" class="font-medium truncate">{{.Name}}</a>{{else}}<span class="font-medium truncate">{{.Name}}</span>{{end}}
                                    <span class="text-xs px-1.5 py-0.5 rounded bg-neutral-200 dark:bg-neutral-800 text-neutral-600 dark:text-neutral-400 uppercase">{{.Type}}</span>
                                </div>
                                <div class="flex items-center gap-4 text-xs text-neutral-500 dark:text-neutral-400">
                                    {{if not .HidePing}}<span>{{formatDuration .ResponseTime}}</span>{{end}}
                                    {{if gt .SSLDaysLeft 0}}
                                    <span class="{{if lt .SSLDaysLeft 14}}text-yellow-600 dark:text-yellow-400{{else if lt .SSLDaysLeft 7}}text-red-600 dark:text-red-400{{end}}" data-tooltip='{{.SSLTooltip}}'>SSL: {{.SSLDaysLeft}}d</span>
                                    {{end}}
                                    {{if .LastError}}<span class="text-red-600 dark:text-red-400">{{simplifyError .LastError}}</span>{{end}}
                                </div>
                            </div>
                            <div class="flex items-center gap-2 flex-shrink-0">
                                <span class="text-sm font-medium {{if ge .UptimePercent 99.0}}text-emerald-600 dark:text-emerald-400{{else if ge .UptimePercent 95.0}}text-yellow-600 dark:text-yellow-400{{else}}text-red-600 dark:text-red-400{{end}}"{{if not $monitor.DisableUptimeTooltip}} data-tooltip='{{.UptimeTooltip}}'{{end}}>{{formatUptime .UptimePercent}}</span>
                            </div>
                        </div>
                        <!-- History Bar -->
                        <div class="mt-3 flex gap-px">
                            {{range $monitor.Ticks}}
                            <div class="flex-1 h-6 rounded-sm {{tickColor .}}"{{if not $monitor.DisablePingTooltips}} data-tooltip='{{tickTooltipData . $.TickMode $.Timezone $monitor.HidePing}}'{{end}}></div>
                            {{else}}
                            {{range seq $.TickCount}}
                            <div class="flex-1 h-6 rounded-sm bg-neutral-200 dark:bg-neutral-800"{{if not $monitor.DisablePingTooltips}} data-tooltip='{"header":"No data"}'{{end}}></div>
                            {{end}}
                            {{end}}
                        </div>
                    </div>
                    {{end}}
                </div>
            </section>
            {{end}}
        </div>

        <!-- Incidents -->
        {{if .Incidents}}
        <section class="mt-8">
            <h2 class="text-lg font-semibold mb-4">Incidents</h2>
            <div class="space-y-4">
                {{range .Incidents}}
                <div class="border border-neutral-200 dark:border-neutral-800 rounded-lg overflow-hidden">
                    <div class="p-4 {{if .IsActive}}bg-yellow-50 dark:bg-yellow-950/20{{else}}bg-neutral-50 dark:bg-neutral-900/50{{end}}">
                        <div class="flex items-start justify-between gap-4">
                            <div>
                                <div class="flex items-center gap-2 mb-1">
                                    {{if eq .Status "resolved"}}
                                    <svg class="w-4 h-4 text-emerald-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
                                    </svg>
                                    {{else if eq .Status "scheduled"}}
                                    <svg class="w-4 h-4 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                                    </svg>
                                    {{else}}
                                    <svg class="w-4 h-4 text-yellow-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"/>
                                    </svg>
                                    {{end}}
                                    <span class="font-medium">{{.Title}}</span>
                                </div>
                                <p class="text-sm text-neutral-600 dark:text-neutral-400">{{.Message}}</p>
                                 {{if .IsScheduled}}
                                 <p class="text-xs text-neutral-500 dark:text-neutral-500 mt-2"{{if $.UseBrowserTimezone}}{{if .ScheduledStart}} data-timestamp-start="{{.ScheduledStart.Format "2006-01-02T15:04:05Z07:00"}}"{{end}}{{if .ScheduledEnd}} data-timestamp-end="{{.ScheduledEnd.Format "2006-01-02T15:04:05Z07:00"}}"{{end}} data-format="scheduled"{{end}}>
                                     Scheduled: {{if .ScheduledStart}}{{formatTime .ScheduledStart}}{{end}} - {{if .ScheduledEnd}}{{formatTime .ScheduledEnd}}{{end}}
                                 </p>
                                 {{end}}
                            </div>
                            <div class="flex-shrink-0">
                                <span class="text-xs px-2 py-1 rounded-full {{if eq .Status "resolved"}}bg-emerald-100 dark:bg-emerald-900/50 text-emerald-700 dark:text-emerald-300{{else if eq .Status "scheduled"}}bg-blue-100 dark:bg-blue-900/50 text-blue-700 dark:text-blue-300{{else if eq .Status "investigating"}}bg-yellow-100 dark:bg-yellow-900/50 text-yellow-700 dark:text-yellow-300{{else if eq .Status "identified"}}bg-orange-100 dark:bg-orange-900/50 text-orange-700 dark:text-orange-300{{else}}bg-neutral-100 dark:bg-neutral-800 text-neutral-700 dark:text-neutral-300{{end}} capitalize">
                                    {{.Status}}
                                </span>
                            </div>
                        </div>
                    </div>
                    {{if .Updates}}
                    <div class="border-t border-neutral-200 dark:border-neutral-800 p-4 space-y-3 bg-white dark:bg-neutral-950">
                        {{range .Updates}}
                         <div class="text-sm">
                             <div class="flex items-center gap-2 text-neutral-500 dark:text-neutral-400 mb-1">
                                 <span class="capitalize font-medium">{{.Status}}</span>
                                 <span class="text-xs"{{if $.UseBrowserTimezone}} data-timestamp="{{.Time.Format "2006-01-02T15:04:05Z07:00"}}" data-format="datetime-short"{{end}}>{{formatTime .Time}}</span>
                             </div>
                             <p class="text-neutral-700 dark:text-neutral-300">{{.Message}}</p>
                         </div>
                        {{end}}
                    </div>
                    {{end}}
                </div>
                {{end}}
            </div>
        </section>
        {{end}}

        <!-- Footer -->
        <footer class="mt-12 pt-6 border-t border-neutral-200 dark:border-neutral-800">
            <div class="flex items-center justify-between text-xs text-neutral-500 dark:text-neutral-400">
                <span data-tooltip='{{.LastUpdatedTooltip}}'{{if $.UseBrowserTimezone}} data-timestamp="{{$.LastUpdated.Format "2006-01-02T15:04:05Z07:00"}}" data-format="timeago"{{end}}>Updated {{timeAgo $.LastUpdated}}</span>
                <span data-tooltip='{{.VersionTooltip}}'>Powered by <a href="https://github.com/Fuwn/kaze" class="hover:text-neutral-900 dark:hover:text-neutral-100">Kaze</a></span>
            </div>
        </footer>
    </div>

    <!-- Tooltip container -->
    <div id="tooltip" class="tooltip"></div>

    <!-- Command Palette -->
    <div id="command-palette" class="command-palette">
        <div class="command-palette-backdrop"></div>
        <div class="command-palette-container">
            <input type="text" id="command-input" class="command-input" placeholder="Search groups and monitors..." autocomplete="off" />
            <div id="command-results" class="command-results"></div>
            <div class="command-hint">
                <span><kbd>↑↓</kbd> navigate</span>
                <span><kbd></kbd> select</span>
                <span><kbd>esc</kbd> close</span>
            </div>
        </div>
    </div>

    <script>
        // Group collapse/expand functionality
        function toggleGroup(groupName) {
            const content = document.querySelector('[data-group-content="' + groupName + '"]');
            const icon = document.querySelector('[data-group-icon="' + groupName + '"]');

            if (!content || !icon) return;

            const isCollapsed = content.classList.contains('collapsed');

            if (isCollapsed) {
                content.classList.remove('collapsed');
                icon.classList.remove('rotated');
                localStorage.setItem('group-' + groupName, 'expanded');
            } else {
                content.classList.add('collapsed');
                icon.classList.add('rotated');
                localStorage.setItem('group-' + groupName, 'collapsed');
            }
        }

        // Initialize group states on page load
        (function initGroupStates() {
            document.querySelectorAll('[data-group-content]').forEach(function(content) {
                const groupName = content.getAttribute('data-group-content');
                const defaultCollapsed = content.getAttribute('data-default-collapsed') === 'true';
                const savedState = localStorage.getItem('group-' + groupName);
                const icon = document.querySelector('[data-group-icon="' + groupName + '"]');

                // Determine initial state: localStorage > config default > expanded
                let shouldCollapse = false;
                if (savedState !== null) {
                    shouldCollapse = savedState === 'collapsed';
                } else {
                    shouldCollapse = defaultCollapsed;
                }

                if (shouldCollapse) {
                    content.classList.add('collapsed');
                    if (icon) icon.classList.add('rotated');
                }
            });
        })();

        // Custom tooltip handling
        (function() {
            const tooltip = document.getElementById('tooltip');
            let currentTarget = null;
            let hideTimeout = null;

            function renderTooltip(data) {
                {{if .UseBrowserTimezone}}
                // Convert tick tooltip timestamps to browser timezone
                if (data.timestamp && data.mode) {
                    const date = new Date(data.timestamp);
                    const tzInfo = {
                        tzName: Intl.DateTimeFormat().resolvedOptions().timeZone || 'Local',
                        offset: -date.getTimezoneOffset()
                    };
                    const hours = Math.floor(tzInfo.offset / 60);
                    const minutes = Math.abs(tzInfo.offset % 60);
                    const utcOffset = 'UTC' + (hours >= 0 ? '+' : '') + hours + (minutes ? ':' + String(minutes).padStart(2, '0') : '');

                    // Update header based on mode
                    if (data.mode === 'ping') {
                        data.header = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + ', ' + 
                                      date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
                    } else if (data.mode === 'minute') {
                        data.header = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + ', ' + 
                                      date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });
                    } else if (data.mode === 'hour') {
                        const hourStr = String(date.getHours()).padStart(2, '0') + ':00';
                        data.header = date.toLocaleDateString('en-US', { month: 'short', day: 'numeric' }) + ', ' + hourStr;
                    } else if (data.mode === 'day') {
                        data.header = date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' });
                    }

                    // Update timezone info in rows
                    if (data.rows) {
                        data.rows.forEach(function(row) {
                            if (row.label === 'Timezone') {
                                row.value = tzInfo.tzName + ' (' + utcOffset + ')';
                            }
                        });
                    }
                }
                // Convert version tooltip build date to browser timezone
                if (data.timestamp && data.timestampLabel) {
                    const date = new Date(data.timestamp);
                    const formatted = date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric' }) + ' ' +
                                      date.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: false });
                    if (data.rows) {
                        data.rows.forEach(function(row) {
                            if (row.label === data.timestampLabel) {
                                row.value = formatted;
                            }
                        });
                    }
                }
                {{end}}

                let html = '<span class="tooltip-header">' + data.header + '</span>';
                if (data.error) {
                    html += '<div style="white-space:normal;max-width:260px;margin-top:0.25rem">' + data.error + '</div>';
                } else if (data.rows) {
                    data.rows.forEach(function(row) {
                        html += '<div class="tooltip-row">';
                        html += '<span class="tooltip-label">' + row.label + '</span>';
                        html += '<span class="tooltip-value ' + (row.class || '') + '">' + row.value + '</span>';
                        html += '</div>';
                    });
                }
                return html;
            }

            function showTooltip(e) {
                const target = e.target.closest('[data-tooltip]');
                if (!target) return;

                clearTimeout(hideTimeout);
                currentTarget = target;

                // Parse and render tooltip content
                try {
                    const data = JSON.parse(target.getAttribute('data-tooltip'));
                    tooltip.innerHTML = renderTooltip(data);
                } catch (err) {
                    tooltip.innerHTML = target.getAttribute('data-tooltip');
                }

                // Make visible to calculate dimensions
                tooltip.classList.add('visible');

                // Position tooltip
                const rect = target.getBoundingClientRect();
                const tooltipRect = tooltip.getBoundingClientRect();

                // Calculate horizontal position (center above the element)
                let left = rect.left + (rect.width / 2) - (tooltipRect.width / 2);

                // Keep tooltip within viewport horizontally
                const padding = 8;
                if (left < padding) {
                    left = padding;
                } else if (left + tooltipRect.width > window.innerWidth - padding) {
                    left = window.innerWidth - tooltipRect.width - padding;
                }

                // Calculate vertical position (above element by default)
                let top = rect.top - tooltipRect.height - 8;

                // If not enough space above, show below
                if (top < padding) {
                    top = rect.bottom + 8;
                    tooltip.classList.add('tooltip-top');
                } else {
                    tooltip.classList.remove('tooltip-top');
                }

                tooltip.style.left = left + 'px';
                tooltip.style.top = top + 'px';
            }

            function hideTooltip() {
                hideTimeout = setTimeout(() => {
                    tooltip.classList.remove('visible');
                    currentTarget = null;
                }, 100);
            }

            // Event delegation for tooltip triggers
            document.addEventListener('mouseenter', showTooltip, true);
            document.addEventListener('mouseleave', function(e) {
                if (e.target.closest('[data-tooltip]')) {
                    hideTooltip();
                }
            }, true);

            // Handle touch devices
            document.addEventListener('touchstart', function(e) {
                const target = e.target.closest('[data-tooltip]');
                if (target) {
                    if (currentTarget === target) {
                        hideTooltip();
                    } else {
                        showTooltip(e);
                    }
                } else {
                    hideTooltip();
                }
            }, { passive: true });
        })();

        // Auto-refresh
        {{if eq .RefreshMode "api"}}
        // API-based refresh (no page reload)
        (function() {
            const refreshInterval = {{.RefreshInterval}} * 1000;
            const tickMode = '{{.TickMode}}';
            const tickCount = {{.TickCount}};
            const useBrowserTimezone = {{.UseBrowserTimezone}};
            
            function getStatusColor(status) {
                switch(status) {
                    case 'up': return 'bg-emerald-500';
                    case 'degraded': return 'bg-yellow-500';
                    case 'down': return 'bg-red-500';
                    default: return 'bg-neutral-400';
                }
            }
            
            function getTickColor(tick) {
                if (!tick || tick.TotalChecks === 0) return 'bg-neutral-200 dark:bg-neutral-800';
                if (tick.Status) {
                    // Ping mode
                    switch(tick.Status) {
                        case 'up': return 'bg-emerald-500';
                        case 'degraded': return 'bg-yellow-500';
                        case 'down': return 'bg-red-500';
                        default: return 'bg-neutral-200 dark:bg-neutral-800';
                    }
                }
                // Aggregated mode
                if (tick.FailureCount > 0 && tick.SuccessCount === 0) return 'bg-red-500';
                if (tick.FailureCount > 0) return 'bg-yellow-500';
                return 'bg-emerald-500';
            }
            
            function getUptimeColor(uptime) {
                if (uptime >= 99.0) return 'text-emerald-600 dark:text-emerald-400';
                if (uptime >= 95.0) return 'text-yellow-600 dark:text-yellow-400';
                return 'text-red-600 dark:text-red-400';
            }
            
            function formatDuration(ms) {
                if (ms < 1000) return ms + 'ms';
                return (ms / 1000).toFixed(2) + 's';
            }
            
            function formatUptime(pct) {
                if (pct >= 99.99) return pct.toFixed(2) + '%';
                if (pct >= 99.9) return pct.toFixed(2) + '%';
                return pct.toFixed(1) + '%';
            }
            
            function simplifyError(err) {
                if (!err) return '';
                const lower = err.toLowerCase();
                if (lower.includes('timeout') || lower.includes('deadline')) return 'Timeout';
                if (lower.includes('connection refused')) return 'Connection refused';
                if (lower.includes('no such host') || lower.includes('dns')) return 'DNS error';
                if (lower.includes('certificate') || lower.includes('x509') || lower.includes('tls')) return 'SSL/TLS error';
                if (lower.includes('eof') || lower.includes('reset by peer')) return 'Connection reset';
                return 'Error';
            }
            
            function formatTickHeader(timestamp, mode) {
                const date = new Date(timestamp);
                const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                if (mode === 'ping') {
                    return months[date.getMonth()] + ' ' + date.getDate() + ', ' + 
                        String(date.getHours()).padStart(2, '0') + ':' + 
                        String(date.getMinutes()).padStart(2, '0') + ':' + 
                        String(date.getSeconds()).padStart(2, '0');
                } else if (mode === 'minute') {
                    return months[date.getMonth()] + ' ' + date.getDate() + ', ' + 
                        String(date.getHours()).padStart(2, '0') + ':' + 
                        String(date.getMinutes()).padStart(2, '0');
                } else if (mode === 'hour') {
                    return months[date.getMonth()] + ' ' + date.getDate() + ', ' + 
                        String(date.getHours()).padStart(2, '0') + ':00';
                } else if (mode === 'day') {
                    return months[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear();
                }
                return timestamp;
            }
            
            function buildTickTooltip(tick, mode, hidePing) {
                if (!tick || tick.TotalChecks === 0) {
                    return JSON.stringify({header: 'No data'});
                }
                
                const data = {
                    header: formatTickHeader(tick.Timestamp, mode),
                    timestamp: tick.Timestamp,
                    mode: mode,
                    rows: []
                };
                
                if (mode === 'ping') {
                    if (!hidePing) {
                        data.rows.push({label: 'Response', value: formatDuration(tick.ResponseTime)});
                    }
                    data.rows.push({label: 'Status', value: tick.Status || 'unknown'});
                } else {
                    data.rows.push({label: 'Checks', value: tick.TotalChecks.toString()});
                    data.rows.push({label: 'Success', value: tick.SuccessCount.toString()});
                    if (tick.FailureCount > 0) {
                        data.rows.push({label: 'Failed', value: tick.FailureCount.toString()});
                    }
                    if (!hidePing && tick.AvgResponse > 0) {
                        data.rows.push({label: 'Avg Response', value: formatDuration(tick.AvgResponse)});
                    }
                    data.rows.push({label: 'Uptime', value: formatUptime(tick.UptimePercent)});
                }
                
                return JSON.stringify(data);
            }
            
            function updateHistoryBar(monitorEl, ticks, hidePing, disableTooltips) {
                const historyBar = monitorEl.querySelector('.mt-3.flex.gap-px');
                if (!historyBar) return;
                
                // Build new tick elements
                let html = '';
                if (ticks && ticks.length > 0) {
                    for (const tick of ticks) {
                        const color = getTickColor(tick);
                        const tooltip = disableTooltips ? '' : ` data-tooltip='${buildTickTooltip(tick, tickMode, hidePing)}'`;
                        html += `<div class="flex-1 h-6 rounded-sm ${color}"${tooltip}></div>`;
                    }
                } else {
                    // Empty ticks
                    for (let i = 0; i < tickCount; i++) {
                        const tooltip = disableTooltips ? '' : ` data-tooltip='{"header":"No data"}'`;
                        html += `<div class="flex-1 h-6 rounded-sm bg-neutral-200 dark:bg-neutral-800"${tooltip}></div>`;
                    }
                }
                historyBar.innerHTML = html;
            }
            
            async function refresh() {
                try {
                    // Fetch all page data in a single request
                    const response = await fetch('/api/page');
                    if (!response.ok) return;
                    const data = await response.json();
                    
                    // Update each monitor
                    document.querySelectorAll('[data-monitor]').forEach(el => {
                        const name = el.getAttribute('data-monitor');
                        const monitor = data.monitors[name];
                        if (!monitor) return;
                        
                        // Update status indicator
                        const statusDot = el.querySelector('.rounded-full');
                        if (statusDot) {
                            statusDot.className = 'w-2 h-2 rounded-full flex-shrink-0 ' + getStatusColor(monitor.status);
                        }
                        
                        // Update response time
                        const infoDiv = el.querySelector('.flex.items-center.gap-4.text-xs');
                        if (infoDiv) {
                            const spans = infoDiv.querySelectorAll(':scope > span');
                            const hidePing = el.hasAttribute('data-hide-ping');
                            if (spans.length > 0 && !hidePing) {
                                spans[0].textContent = formatDuration(monitor.response_time);
                            }
                            
                            // Update error
                            let errorSpan = infoDiv.querySelector('.text-red-600');
                            if (monitor.last_error) {
                                if (!errorSpan) {
                                    errorSpan = document.createElement('span');
                                    errorSpan.className = 'text-red-600 dark:text-red-400';
                                    infoDiv.appendChild(errorSpan);
                                }
                                errorSpan.textContent = simplifyError(monitor.last_error);
                            } else if (errorSpan) {
                                errorSpan.remove();
                            }
                        }
                        
                        // Update uptime
                        const uptimeEl = el.querySelector('.text-sm.font-medium');
                        if (uptimeEl) {
                            uptimeEl.textContent = formatUptime(monitor.uptime);
                            uptimeEl.className = 'text-sm font-medium ' + getUptimeColor(monitor.uptime);
                        }
                        
                        // Update history bar
                        if (monitor.ticks) {
                            const hidePing = el.hasAttribute('data-hide-ping');
                            const disableTooltips = el.hasAttribute('data-disable-tooltips');
                            updateHistoryBar(el, monitor.ticks, hidePing, disableTooltips);
                        }
                    });
                    
                    // Update overall status banner
                    const banner = document.querySelector('.mb-8.p-4.rounded-lg.border');
                    if (banner) {
                        const statusText = banner.querySelector('.font-medium');
                        if (statusText) statusText.textContent = data.overall_status;
                        
                        const dot = banner.querySelector('.rounded-full');
                        if (dot) {
                            if (data.overall_status === 'All Systems Operational') {
                                dot.className = 'w-3 h-3 rounded-full bg-emerald-500 animate-pulse';
                                banner.className = 'mb-8 p-4 rounded-lg border bg-emerald-50 dark:bg-emerald-950/30 border-emerald-200 dark:border-emerald-900';
                            } else if (data.overall_status === 'Partial Outage') {
                                dot.className = 'w-3 h-3 rounded-full bg-yellow-500 animate-pulse';
                                banner.className = 'mb-8 p-4 rounded-lg border bg-yellow-50 dark:bg-yellow-950/30 border-yellow-200 dark:border-yellow-900';
                            } else {
                                dot.className = 'w-3 h-3 rounded-full bg-red-500 animate-pulse';
                                banner.className = 'mb-8 p-4 rounded-lg border bg-red-50 dark:bg-red-950/30 border-red-200 dark:border-red-900';
                            }
                        }
                    }
                    
                    // Update status counts in title
                    let title = '{{.Site.Name}} [↑' + data.counts.Up;
                    if (data.counts.Down > 0) title += '/' + data.counts.Down + '↓';
                    title += ']';
                    document.title = title;
                    
                    // Update last updated time
                    const timeEl = document.querySelector('[data-timestamp][data-format="datetime"]');
                    if (timeEl) {
                        const now = new Date(data.last_updated);
                        {{if .UseBrowserTimezone}}
                        const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                        timeEl.textContent = months[now.getMonth()] + ' ' + now.getDate() + ', ' + now.getFullYear() + ' ' + 
                            String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0');
                        {{else}}
                        timeEl.textContent = timeEl.textContent.replace(/\d{2}:\d{2}$/, 
                            String(now.getHours()).padStart(2, '0') + ':' + String(now.getMinutes()).padStart(2, '0'));
                        {{end}}
                    }
                    
                } catch (e) {
                    console.error('Failed to refresh status:', e);
                }
            }
            
            setInterval(refresh, refreshInterval);
        })();
        {{else}}
        // Page-based refresh (full reload)
        setTimeout(() => location.reload(), {{.RefreshInterval}} * 1000);
        {{end}}

        // Client-side timezone conversion
        {{if .UseBrowserTimezone}}
        (function() {
            function formatDateTime(date) {
                const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                const month = months[date.getMonth()];
                const day = date.getDate();
                const year = date.getFullYear();
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return month + ' ' + day + ', ' + year + ' ' + hours + ':' + minutes;
            }

            function formatDateTimeShort(date) {
                const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
                const month = months[date.getMonth()];
                const day = date.getDate();
                const hours = String(date.getHours()).padStart(2, '0');
                const minutes = String(date.getMinutes()).padStart(2, '0');
                return month + ' ' + day + ', ' + hours + ':' + minutes;
            }

            function timeAgo(date) {
                const seconds = Math.floor((new Date() - date) / 1000);
                if (seconds < 60) return seconds + ' seconds ago';
                const minutes = Math.floor(seconds / 60);
                if (minutes < 60) return minutes + ' minute' + (minutes === 1 ? '' : 's') + ' ago';
                const hours = Math.floor(minutes / 60);
                if (hours < 24) return hours + ' hour' + (hours === 1 ? '' : 's') + ' ago';
                const days = Math.floor(hours / 24);
                return days + ' day' + (days === 1 ? '' : 's') + ' ago';
            }

            function getTimezoneInfo() {
                const date = new Date();
                const tzName = Intl.DateTimeFormat().resolvedOptions().timeZone || 'Local';
                const offset = -date.getTimezoneOffset();
                const hours = Math.floor(offset / 60);
                const minutes = Math.abs(offset % 60);
                const utcOffset = 'UTC' + (hours >= 0 ? '+' : '') + hours + (minutes ? ':' + String(minutes).padStart(2, '0') : '');
                const gmtOffset = 'GMT' + (hours >= 0 ? '+' : '') + hours + (minutes ? ':' + String(minutes).padStart(2, '0') : '');
                return { tzName: tzName, utcOffset: utcOffset, gmtOffset: gmtOffset };
            }

            // Convert all timestamps
            document.querySelectorAll('[data-timestamp]').forEach(function(el) {
                const timestamp = el.getAttribute('data-timestamp');
                const format = el.getAttribute('data-format');
                const date = new Date(timestamp);

                if (format === 'datetime') {
                    el.textContent = formatDateTime(date);
                } else if (format === 'datetime-short') {
                    el.textContent = formatDateTimeShort(date);
                } else if (format === 'timeago') {
                    el.textContent = 'Updated ' + timeAgo(date);
                } else if (format === 'scheduled') {
                    const startTimestamp = el.getAttribute('data-timestamp-start');
                    const endTimestamp = el.getAttribute('data-timestamp-end');
                    let text = 'Scheduled: ';
                    if (startTimestamp) {
                        text += formatDateTimeShort(new Date(startTimestamp));
                    }
                    text += ' - ';
                    if (endTimestamp) {
                        text += formatDateTimeShort(new Date(endTimestamp));
                    }
                    el.textContent = text;
                }

                // Update tooltips to show browser timezone
                const tooltipData = el.getAttribute('data-tooltip');
                if (tooltipData) {
                    try {
                        const data = JSON.parse(tooltipData);
                        if (data.rows) {
                            const tzInfo = getTimezoneInfo();
                            data.rows.forEach(function(row) {
                                if (row.label === 'Timezone') {
                                    row.value = tzInfo.tzName;
                                } else if (row.label === 'UTC Offset') {
                                    row.value = tzInfo.utcOffset;
                                } else if (row.label === 'GMT Offset') {
                                    row.value = tzInfo.gmtOffset;
                                } else if (row.label === 'Date & Time' && format === 'timeago') {
                                    // Update "Last Check" tooltip with browser timezone
                                    const dtFormat = new Intl.DateTimeFormat('en-US', {
                                        year: 'numeric',
                                        month: 'short',
                                        day: 'numeric',
                                        hour: '2-digit',
                                        minute: '2-digit',
                                        second: '2-digit',
                                        hour12: false
                                    });
                                    row.value = dtFormat.format(date);
                                }
                            });
                            el.setAttribute('data-tooltip', JSON.stringify(data));
                        }
                    } catch (e) {
                        // Ignore JSON parse errors
                    }
                }
            });
        })();
        {{end}}

        // Command Palette
        (function() {
            const palette = document.getElementById('command-palette');
            const input = document.getElementById('command-input');
            const results = document.getElementById('command-results');
            let selectedIndex = -1;
            let items = [];

            // Build search index
            function buildIndex() {
                const index = [];
                
                // Add groups
                document.querySelectorAll('[data-group-content]').forEach(function(el) {
                    const name = el.getAttribute('data-group-content');
                    index.push({
                        type: 'group',
                        name: name,
                        element: el.closest('section'),
                        searchText: name.toLowerCase()
                    });
                });

                // Add monitors
                document.querySelectorAll('[data-monitor]').forEach(function(el) {
                    const name = el.getAttribute('data-monitor');
                    const group = el.getAttribute('data-group');
                    index.push({
                        type: 'monitor',
                        name: name,
                        group: group,
                        element: el,
                        searchText: (name + ' ' + group).toLowerCase()
                    });
                });

                return index;
            }

            const searchIndex = buildIndex();

            function openPalette() {
                palette.classList.add('visible');
                input.value = '';
                input.focus();
                search('');
            }

            function closePalette() {
                palette.classList.remove('visible');
                selectedIndex = -1;
            }

            function search(query) {
                const q = query.toLowerCase().trim();
                
                if (q === '') {
                    items = searchIndex.slice(0, 10);
                } else {
                    items = searchIndex.filter(function(item) {
                        return item.searchText.includes(q);
                    }).slice(0, 10);
                }

                // Always select first item if there are results
                selectedIndex = items.length > 0 ? 0 : -1;
                renderResults();
            }

            function renderResults() {
                if (items.length === 0) {
                    results.innerHTML = '<div class="command-empty">No results found</div>';
                    return;
                }

                results.innerHTML = items.map(function(item, i) {
                    const isSelected = i === selectedIndex ? ' selected' : '';
                    const icon = item.type === 'group' 
                        ? '<svg class="command-item-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10"/></svg>'
                        : '<svg class="command-item-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24"><circle cx="12" cy="12" r="3" stroke-width="2"/></svg>';
                    
                    const meta = item.type === 'group'
                        ? '<span class="command-item-type">Group</span>'
                        : '<span class="command-item-path">' + item.group + '</span>';

                    return '<div class="command-item' + isSelected + '" data-index="' + i + '">' +
                        icon +
                        '<div class="command-item-content">' +
                        '<div class="command-item-name">' + item.name + '</div>' +
                        meta +
                        '</div></div>';
                }).join('');

                // Scroll selected item into view
                if (selectedIndex >= 0) {
                    const selectedEl = results.querySelector('.command-item.selected');
                    if (selectedEl) {
                        selectedEl.scrollIntoView({ block: 'nearest' });
                    }
                }
            }

            function selectItem(index) {
                if (index < 0 || index >= items.length) return;
                
                const item = items[index];
                closePalette();

                // Expand group if collapsed
                if (item.type === 'group') {
                    const groupName = item.name;
                    const content = document.querySelector('[data-group-content="' + groupName + '"]');
                    const icon = document.querySelector('[data-group-icon="' + groupName + '"]');
                    
                    if (content && content.classList.contains('collapsed')) {
                        content.classList.remove('collapsed');
                        if (icon) icon.classList.remove('rotated');
                        localStorage.setItem('group-' + groupName, 'expanded');
                    }
                } else if (item.type === 'monitor') {
                    // Expand parent group if collapsed
                    const groupName = item.group;
                    const content = document.querySelector('[data-group-content="' + groupName + '"]');
                    const icon = document.querySelector('[data-group-icon="' + groupName + '"]');
                    
                    if (content && content.classList.contains('collapsed')) {
                        content.classList.remove('collapsed');
                        if (icon) icon.classList.remove('rotated');
                        localStorage.setItem('group-' + groupName, 'expanded');
                    }
                }

                // Scroll to element and highlight
                setTimeout(function() {
                    item.element.scrollIntoView({ behavior: 'smooth', block: 'center' });
                    item.element.classList.add('highlight-jump');
                    setTimeout(function() {
                        item.element.classList.remove('highlight-jump');
                    }, 1000);
                }, 50);
            }

            // Event listeners
            document.addEventListener('keydown', function(e) {
                // Open with Cmd/Ctrl+K or /
                if ((e.key === 'k' && (e.metaKey || e.ctrlKey)) || (e.key === '/' && !palette.classList.contains('visible') && document.activeElement.tagName !== 'INPUT')) {
                    e.preventDefault();
                    openPalette();
                    return;
                }

                if (!palette.classList.contains('visible')) return;

                if (e.key === 'Escape') {
                    e.preventDefault();
                    closePalette();
                } else if (e.key === 'ArrowDown') {
                    e.preventDefault();
                    selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
                    renderResults();
                } else if (e.key === 'ArrowUp') {
                    e.preventDefault();
                    selectedIndex = Math.max(selectedIndex - 1, 0);
                    renderResults();
                } else if (e.key === 'Enter') {
                    e.preventDefault();
                    if (selectedIndex >= 0) {
                        selectItem(selectedIndex);
                    }
                }
            });

            input.addEventListener('input', function() {
                search(input.value);
            });

            results.addEventListener('click', function(e) {
                const item = e.target.closest('.command-item');
                if (item) {
                    selectItem(parseInt(item.getAttribute('data-index'), 10));
                }
            });

            // Close on backdrop click
            palette.querySelector('.command-palette-backdrop').addEventListener('click', closePalette);
        })();
    </script>
</body>
</html>