aboutsummaryrefslogtreecommitdiff
path: root/internal/server/server.go
blob: 92966471fb1d074af1f09c349f9340f21cd956b8 (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
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
package server

import (
	"bytes"
	"context"
	"embed"
	"encoding/json"
	"fmt"
	"html/template"
	"io/fs"
	"log/slog"
	"net/http"
	"net/url"
	"sort"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/Fuwn/kaze/internal/config"
	"github.com/Fuwn/kaze/internal/monitor"
	"github.com/Fuwn/kaze/internal/storage"
	"github.com/Fuwn/kaze/internal/theme"
)

//go:embed templates/*.html
var templatesFS embed.FS

//go:embed static/*
var staticFS embed.FS

// ReloadFunc is a callback function for reloading configuration
type ReloadFunc func() error

// VersionInfo contains build version information
type VersionInfo struct {
	Version string
	Commit  string
	Date    string
}

// Server handles HTTP requests for the status page
type Server struct {
	mu           sync.RWMutex
	config       *config.Config
	storage      *storage.Storage
	scheduler    *monitor.Scheduler
	logger       *slog.Logger
	server       *http.Server
	templates    *template.Template
	reloadConfig ReloadFunc
	version      VersionInfo
}

// New creates a new HTTP server
func New(cfg *config.Config, store *storage.Storage, sched *monitor.Scheduler, logger *slog.Logger) (*Server, error) {
	// Parse templates
	tmpl, err := template.New("").Funcs(templateFuncs()).ParseFS(templatesFS, "templates/*.html")
	if err != nil {
		return nil, fmt.Errorf("failed to parse templates: %w", err)
	}

	s := &Server{
		config:    cfg,
		storage:   store,
		scheduler: sched,
		logger:    logger,
		templates: tmpl,
	}

	// Setup routes
	mux := http.NewServeMux()

	// Static files
	staticContent, err := fs.Sub(staticFS, "static")
	if err != nil {
		return nil, fmt.Errorf("failed to get static fs: %w", err)
	}
	mux.Handle("GET /static/", http.StripPrefix("/static/", http.FileServer(http.FS(staticContent))))

	// Pages
	mux.HandleFunc("GET /", s.handleIndex)

	// API endpoints (protected by API access control)
	mux.HandleFunc("GET /api/status", s.withAPIAuth(s.handleAPIStatus))
	mux.HandleFunc("GET /api/monitor/{group}/{name}", s.withAPIAuth(s.handleAPIMonitor))
	mux.HandleFunc("GET /api/history/{group}/{name}", s.withAPIAuth(s.handleAPIHistory))
	mux.HandleFunc("GET /api/summary", s.withAPIAuth(s.handleAPISummary))
	mux.HandleFunc("GET /api/uptime/{group}/{name}", s.withAPIAuth(s.handleAPIUptime))
	mux.HandleFunc("GET /api/incidents", s.withAPIAuth(s.handleAPIIncidents))

	// Health check - always public (for load balancers, monitoring)
	mux.HandleFunc("GET /api/health", s.handleAPIHealth)

	// Badge endpoint - always public (for embedding in READMEs, docs)
	// Note: {path...} captures the rest of the path (group/name.svg)
	mux.HandleFunc("GET /api/badge/{path...}", s.handleAPIBadge)

	// Full page data endpoint - public if refresh_mode=api, otherwise follows api.access
	if cfg.Display.RefreshMode == "api" {
		mux.HandleFunc("GET /api/page", s.handleAPIPage)
	} else {
		mux.HandleFunc("GET /api/page", s.withAPIAuth(s.handleAPIPage))
	}

	// Config reload endpoint - always requires authentication
	mux.HandleFunc("POST /api/reload", s.withStrictAuth(s.handleAPIReload))

	// Create HTTP server
	s.server = &http.Server{
		Addr:         fmt.Sprintf("%s:%d", cfg.Server.Host, cfg.Server.Port),
		Handler:      s.withMiddleware(mux),
		ReadTimeout:  15 * time.Second,
		WriteTimeout: 30 * time.Second, // Increased for large page renders
		IdleTimeout:  60 * time.Second,
	}

	return s, nil
}

// Start begins serving HTTP requests
func (s *Server) Start() error {
	s.logger.Info("starting HTTP server", "addr", s.server.Addr)
	if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
		return fmt.Errorf("server error: %w", err)
	}
	return nil
}

// Stop gracefully shuts down the server
func (s *Server) Stop(ctx context.Context) error {
	s.logger.Info("stopping HTTP server")
	return s.server.Shutdown(ctx)
}

// withMiddleware adds common middleware to the handler
func (s *Server) withMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		start := time.Now()

		// Add security headers
		w.Header().Set("X-Content-Type-Options", "nosniff")
		w.Header().Set("X-Frame-Options", "DENY")
		w.Header().Set("X-XSS-Protection", "1; mode=block")

		next.ServeHTTP(w, r)

		s.logger.Debug("request",
			"method", r.Method,
			"path", r.URL.Path,
			"duration", time.Since(start))
	})
}

// withAPIAuth wraps an API handler with access control based on config.API.Access
func (s *Server) withAPIAuth(handler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cfg := s.getConfig()
		switch cfg.API.Access {
		case "private":
			s.jsonError(w, "API access is disabled", http.StatusForbidden)
			return

		case "authenticated":
			if !s.checkAPIKey(r, cfg) {
				w.Header().Set("WWW-Authenticate", "API-Key")
				s.jsonError(w, "API key required", http.StatusUnauthorized)
				return
			}
		}

		handler(w, r)
	}
}

func (s *Server) withStrictAuth(handler http.HandlerFunc) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		cfg := s.getConfig()
		if len(cfg.API.Keys) == 0 {
			s.jsonError(w, "No API keys configured. Add keys to api.keys in config to use this endpoint.", http.StatusForbidden)
			return
		}

		if !s.checkAPIKey(r, cfg) {
			w.Header().Set("WWW-Authenticate", "API-Key")
			s.jsonError(w, "API key required", http.StatusUnauthorized)
			return
		}

		handler(w, r)
	}
}

func (s *Server) checkAPIKey(r *http.Request, cfg *config.Config) bool {
	apiKey := r.Header.Get("X-API-Key")
	if apiKey == "" {
		apiKey = r.URL.Query().Get("api_key")
	}

	if apiKey == "" {
		return false
	}

	for _, key := range cfg.API.Keys {
		if key == apiKey {
			return true
		}
	}

	return false
}

// PageData contains data for rendering the status page
type PageData struct {
	Site               config.SiteConfig
	Groups             []GroupData
	Incidents          []IncidentData
	OverallStatus      string
	StatusCounts       StatusCounts // Counts for tab title
	LastUpdated        time.Time
	CurrentTime        string // Formatted date/time for display (without timezone)
	TimezoneTooltip    string // JSON data for timezone tooltip
	LastUpdatedTooltip string // JSON data for last updated tooltip
	TickMode           string // ping, minute, hour, day
	TickCount          int
	Timezone           string        // Timezone for display
	UseBrowserTimezone bool          // Use client-side timezone conversion
	ThemeCSS           template.CSS  // OpenCode theme CSS (safe CSS)
	CustomHead         template.HTML // Custom HTML for <head> (trusted)
	Scale              float64       // UI scale factor (0.5-2.0)
	RefreshMode        string        // page or api
	RefreshInterval    int           // seconds
	VersionTooltip     string        // JSON data for version tooltip
}

// StatusCounts holds monitor status counts for display
type StatusCounts struct {
	Up       int
	Down     int
	Degraded int
	Total    int
}

// GroupData contains data for a monitor group
type GroupData struct {
	Name             string
	Monitors         []MonitorData
	DefaultCollapsed bool
	ShowGroupUptime  bool
	GroupUptime      float64
}

// MonitorData contains data for a single monitor
type MonitorData struct {
	Name                 string
	Type                 string
	Link                 template.URL // Custom URL for clicking the monitor name (trusted)
	Status               string
	StatusClass          string
	ResponseTime         int64
	HidePing             bool // Hide response time from display
	UptimePercent        float64
	UptimeTooltip        string              // JSON data for uptime tooltip with last failure info
	Ticks                []*storage.TickData // Aggregated tick data for history bar
	SSLDaysLeft          int
	SSLExpiryDate        time.Time
	SSLTooltip           string // JSON data for SSL expiration tooltip
	LastCheck            time.Time
	LastError            string
	LastFailure          *time.Time // Time of last failure
	LastFailureError     string     // Error from last failure
	DisablePingTooltips  bool
	DisableUptimeTooltip bool
}

// IncidentData contains data for an incident
type IncidentData struct {
	Title          string
	Status         string
	StatusClass    string
	Message        string
	ScheduledStart *time.Time
	ScheduledEnd   *time.Time
	CreatedAt      *time.Time
	ResolvedAt     *time.Time
	Updates        []IncidentUpdateData
	IsScheduled    bool
	IsActive       bool
}

// IncidentUpdateData contains data for an incident update
type IncidentUpdateData struct {
	Time    time.Time
	Status  string
	Message string
}

// handleIndex renders the main status page
func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	cfg := s.getConfig()

	// Get all monitor stats
	stats, err := s.storage.GetAllMonitorStats(ctx)
	if err != nil {
		s.logger.Error("failed to get monitor stats", "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	// Load OpenCode theme if configured
	var themeCSS template.CSS
	if cfg.Site.ThemeURL != "" {
		resolvedTheme, err := theme.LoadTheme(cfg.Site.ThemeURL)
		if err != nil {
			s.logger.Warn("failed to load theme", "url", cfg.Site.ThemeURL, "error", err)
		} else if resolvedTheme != nil {
			cssString := resolvedTheme.GenerateCSS() + resolvedTheme.GenerateVariableOverrides()
			themeCSS = template.CSS(cssString)
		}
	}

	// Build page data
	data := PageData{
		Site:               cfg.Site,
		TickMode:           cfg.Display.TickMode,
		TickCount:          cfg.Display.TickCount,
		Timezone:           cfg.Display.Timezone,
		UseBrowserTimezone: cfg.Display.Timezone == "Browser",
		ThemeCSS:           themeCSS,
		CustomHead:         template.HTML(cfg.Site.CustomHead),
		Scale:              cfg.Display.Scale,
		RefreshMode:        cfg.Display.RefreshMode,
		RefreshInterval:    cfg.Display.RefreshInterval,
		VersionTooltip:     s.formatVersionTooltip(),
	}

	overallUp := true
	hasDegraded := false
	var mostRecentCheck time.Time
	var statusCounts StatusCounts

	// Build groups
	for _, group := range cfg.Groups {
		gd := GroupData{
			Name:             group.Name,
			DefaultCollapsed: group.DefaultCollapsed != nil && *group.DefaultCollapsed,
			ShowGroupUptime:  group.ShowGroupUptime == nil || *group.ShowGroupUptime,
		}

		var totalUptime float64
		var monitorsWithUptime int

		for _, monCfg := range group.Monitors {
			md := MonitorData{
				Name:                 monCfg.Name,
				Type:                 monCfg.Type,
				Link:                 template.URL(monCfg.Link),
				HidePing:             monCfg.HidePing,
				DisablePingTooltips:  monCfg.DisablePingTooltips,
				DisableUptimeTooltip: monCfg.DisableUptimeTooltip,
			}

			monitorID := monCfg.ID()
			if stat, ok := stats[monitorID]; ok {
				md.Status = stat.CurrentStatus
				md.ResponseTime = stat.LastResponseTime
				md.UptimePercent = stat.UptimePercent
				md.SSLDaysLeft = stat.SSLDaysLeft
				md.LastCheck = stat.LastCheck
				md.LastError = stat.LastError

				if stat.SSLExpiry != nil {
					md.SSLExpiryDate = *stat.SSLExpiry
					md.SSLTooltip = formatSSLTooltip(*stat.SSLExpiry, stat.SSLDaysLeft, cfg.Display.Timezone)
				}

				md.LastFailure = stat.LastFailure
				md.LastFailureError = stat.LastFailureError
				md.UptimeTooltip = formatUptimeTooltip(stat.UptimePercent, stat.TotalChecks, stat.LastFailure, stat.LastFailureError, cfg.Display.Timezone)

				if stat.LastCheck.After(mostRecentCheck) {
					mostRecentCheck = stat.LastCheck
				}

				ticks, err := s.storage.GetAggregatedHistory(
					ctx,
					monitorID,
					cfg.Display.TickCount,
					cfg.Display.TickMode,
					cfg.Display.PingFixedSlots,
				)
				if err != nil {
					s.logger.Error("failed to get tick history", "monitor", monitorID, "error", err)
				} else {
					md.Ticks = ticks
				}

				statusCounts.Total++
				switch stat.CurrentStatus {
				case "down":
					overallUp = false
					statusCounts.Down++
				case "degraded":
					hasDegraded = true
					statusCounts.Degraded++
				case "up":
					statusCounts.Up++
				}
			} else {
				md.Status = "unknown"
			}

			md.StatusClass = statusToClass(md.Status)
			gd.Monitors = append(gd.Monitors, md)

			if md.UptimePercent >= 0 {
				totalUptime += md.UptimePercent
				monitorsWithUptime++
			}
		}

		if monitorsWithUptime > 0 {
			gd.GroupUptime = totalUptime / float64(monitorsWithUptime)
		}

		data.Groups = append(data.Groups, gd)
	}

	now := time.Now()
	if !mostRecentCheck.IsZero() {
		data.LastUpdated = mostRecentCheck
	} else {
		data.LastUpdated = now
	}

	data.CurrentTime = formatCurrentTime(now, cfg.Display.Timezone)
	data.TimezoneTooltip = formatTimezoneTooltip(now, cfg.Display.Timezone)
	data.LastUpdatedTooltip = formatLastUpdatedTooltip(data.LastUpdated, cfg.Display.Timezone)

	if !overallUp {
		data.OverallStatus = "Major Outage"
	} else if hasDegraded {
		data.OverallStatus = "Partial Outage"
	} else {
		data.OverallStatus = "All Systems Operational"
	}
	data.StatusCounts = statusCounts

	for _, inc := range cfg.Incidents {
		id := IncidentData{
			Title:          inc.Title,
			Status:         inc.Status,
			StatusClass:    incidentStatusToClass(inc.Status),
			Message:        inc.Message,
			ScheduledStart: inc.ScheduledStart,
			ScheduledEnd:   inc.ScheduledEnd,
			CreatedAt:      inc.CreatedAt,
			ResolvedAt:     inc.ResolvedAt,
			IsScheduled:    inc.Status == "scheduled",
		}

		// Check if incident is active (not resolved and not future scheduled)
		if inc.Status != "resolved" {
			if inc.Status == "scheduled" {
				if inc.ScheduledStart != nil && inc.ScheduledStart.After(time.Now()) {
					id.IsActive = false
				} else {
					id.IsActive = true
				}
			} else {
				id.IsActive = true
			}
		}

		// Add updates
		for _, upd := range inc.Updates {
			id.Updates = append(id.Updates, IncidentUpdateData{
				Time:    upd.Time,
				Status:  upd.Status,
				Message: upd.Message,
			})
		}

		data.Incidents = append(data.Incidents, id)
	}

	// Sort incidents: active first, then by date
	sort.Slice(data.Incidents, func(i, j int) bool {
		if data.Incidents[i].IsActive != data.Incidents[j].IsActive {
			return data.Incidents[i].IsActive
		}
		return false
	})

	// Render template to buffer first to prevent broken pipe errors
	// This allows us to complete template execution even if client disconnects
	var buf bytes.Buffer
	if err := s.templates.ExecuteTemplate(&buf, "index.html", data); err != nil {
		s.logger.Error("failed to render template", "error", err)
		http.Error(w, "Internal Server Error", http.StatusInternalServerError)
		return
	}

	// Write buffered response atomically
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
	if _, err := w.Write(buf.Bytes()); err != nil {
		// Client likely disconnected, just log it
		s.logger.Debug("failed to write response", "error", err)
	}
}

// handleAPIStatus returns JSON status for all monitors
func (s *Server) handleAPIStatus(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	stats, err := s.storage.GetAllMonitorStats(ctx)
	if err != nil {
		s.jsonError(w, "Failed to get stats", http.StatusInternalServerError)
		return
	}

	s.jsonResponse(w, stats)
}

// handleAPIMonitor returns JSON status for a specific monitor
func (s *Server) handleAPIMonitor(w http.ResponseWriter, r *http.Request) {
	group := r.PathValue("group")
	name := r.PathValue("name")
	if group == "" || name == "" {
		s.jsonError(w, "Group and monitor name required", http.StatusBadRequest)
		return
	}

	// Construct composite ID (path values are already URL-decoded by net/http,
	// but we need to re-encode to match the internal ID format)
	monitorID := url.PathEscape(group) + "/" + url.PathEscape(name)

	stats, err := s.storage.GetMonitorStats(r.Context(), monitorID)
	if err != nil {
		s.jsonError(w, "Failed to get monitor stats", http.StatusInternalServerError)
		return
	}

	s.jsonResponse(w, stats)
}

func (s *Server) handleAPIHistory(w http.ResponseWriter, r *http.Request) {
	group := r.PathValue("group")
	name := r.PathValue("name")
	if group == "" || name == "" {
		s.jsonError(w, "Group and monitor name required", http.StatusBadRequest)
		return
	}

	cfg := s.getConfig()
	monitorID := url.PathEscape(group) + "/" + url.PathEscape(name)

	mode := cfg.Display.TickMode
	if modeParam := r.URL.Query().Get("mode"); modeParam != "" {
		switch modeParam {
		case "ping", "minute", "hour", "day":
			mode = modeParam
		}
	}

	count := cfg.Display.TickCount
	if countParam := r.URL.Query().Get("count"); countParam != "" {
		if c, err := strconv.Atoi(countParam); err == nil && c > 0 && c <= 200 {
			count = c
		}
	}

	ticks, err := s.storage.GetAggregatedHistory(r.Context(), monitorID, count, mode, cfg.Display.PingFixedSlots)
	if err != nil {
		s.jsonError(w, "Failed to get history", http.StatusInternalServerError)
		return
	}

	s.jsonResponse(w, map[string]interface{}{
		"monitor": monitorID,
		"mode":    mode,
		"count":   count,
		"ticks":   ticks,
	})
}

// APIPageResponse contains all data needed to render/update the status page
type APIPageResponse struct {
	Monitors      map[string]APIMonitorData `json:"monitors"`
	OverallStatus string                    `json:"overall_status"`
	Counts        StatusCounts              `json:"counts"`
	LastUpdated   time.Time                 `json:"last_updated"`
}

// APIMonitorData contains monitor data for the API page response
type APIMonitorData struct {
	Status       string              `json:"status"`
	ResponseTime int64               `json:"response_time"`
	Uptime       float64             `json:"uptime"`
	LastError    string              `json:"last_error,omitempty"`
	SSLDaysLeft  int                 `json:"ssl_days_left,omitempty"`
	Ticks        []*storage.TickData `json:"ticks"`
}

func (s *Server) handleAPIPage(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	cfg := s.getConfig()

	stats, err := s.storage.GetAllMonitorStats(ctx)
	if err != nil {
		s.jsonError(w, "Failed to get stats", http.StatusInternalServerError)
		return
	}

	response := APIPageResponse{
		Monitors:    make(map[string]APIMonitorData),
		LastUpdated: time.Now(),
	}

	overallUp := true
	hasDegraded := false

	for _, group := range cfg.Groups {
		for _, monCfg := range group.Monitors {
			monitorID := monCfg.ID()
			stat, ok := stats[monitorID]
			if !ok {
				continue
			}

			ticks, err := s.storage.GetAggregatedHistory(
				ctx,
				monitorID,
				cfg.Display.TickCount,
				cfg.Display.TickMode,
				cfg.Display.PingFixedSlots,
			)
			if err != nil {
				s.logger.Error("failed to get tick history", "monitor", monitorID, "error", err)
				ticks = nil
			}

			response.Monitors[monitorID] = APIMonitorData{
				Status:       stat.CurrentStatus,
				ResponseTime: stat.LastResponseTime,
				Uptime:       stat.UptimePercent,
				LastError:    stat.LastError,
				SSLDaysLeft:  stat.SSLDaysLeft,
				Ticks:        ticks,
			}

			response.Counts.Total++
			switch stat.CurrentStatus {
			case "down":
				overallUp = false
				response.Counts.Down++
			case "degraded":
				hasDegraded = true
				response.Counts.Degraded++
			case "up":
				response.Counts.Up++
			}
		}
	}

	if !overallUp {
		response.OverallStatus = "Major Outage"
	} else if hasDegraded {
		response.OverallStatus = "Partial Outage"
	} else {
		response.OverallStatus = "All Systems Operational"
	}

	s.jsonResponse(w, response)
}

// handleAPIHealth returns a simple health check response (always public)
func (s *Server) handleAPIHealth(w http.ResponseWriter, r *http.Request) {
	s.jsonResponse(w, map[string]string{"status": "ok"})
}

// handleAPIBadge returns an SVG status badge for a monitor (shields.io style)
func (s *Server) handleAPIBadge(w http.ResponseWriter, r *http.Request) {
	path := r.PathValue("path")
	if path == "" {
		http.Error(w, "Monitor path required (group/name.svg)", http.StatusBadRequest)
		return
	}

	// Strip .svg extension if present
	path = strings.TrimSuffix(path, ".svg")

	// The path should be in format "group/name" (URL-encoded components)
	// Split into group and name, then re-encode to match internal ID format
	idx := strings.Index(path, "/")
	var monitorID, displayName string
	if idx >= 0 {
		group := path[:idx]
		name := path[idx+1:]
		// Re-encode to ensure consistent internal format
		monitorID = url.PathEscape(group) + "/" + url.PathEscape(name)
		displayName = name
	} else {
		// No group, just name
		monitorID = url.PathEscape(path)
		displayName = path
	}

	// Get monitor stats
	stats, err := s.storage.GetMonitorStats(r.Context(), monitorID)
	if err != nil {
		s.logger.Error("failed to get monitor stats for badge", "monitor", monitorID, "error", err)
		// Return a gray "unknown" badge on error
		s.serveBadge(w, r, displayName, "unknown", "#9ca3af")
		return
	}

	// Determine status and color
	var status, color string
	switch stats.CurrentStatus {
	case "up":
		status = "up"
		color = "#22c55e" // green-500
	case "degraded":
		status = "degraded"
		color = "#eab308" // yellow-500
	case "down":
		status = "down"
		color = "#ef4444" // red-500
	default:
		status = "unknown"
		color = "#9ca3af" // gray-400
	}

	// Check for custom label
	label := r.URL.Query().Get("label")
	if label == "" {
		label = displayName
	}

	// Check for style (flat or plastic, default: flat)
	style := r.URL.Query().Get("style")
	if style != "plastic" {
		style = "flat"
	}

	// Check if uptime should be shown instead of status
	if r.URL.Query().Get("type") == "uptime" {
		status = fmt.Sprintf("%.1f%%", stats.UptimePercent)
		if stats.UptimePercent >= 99.0 {
			color = "#22c55e"
		} else if stats.UptimePercent >= 95.0 {
			color = "#eab308"
		} else {
			color = "#ef4444"
		}
	}

	s.serveBadge(w, r, label, status, color)
}

// serveBadge generates and serves an SVG badge
func (s *Server) serveBadge(w http.ResponseWriter, r *http.Request, label, status, color string) {
	style := r.URL.Query().Get("style")
	if style != "plastic" {
		style = "flat"
	}

	// Calculate widths (approximate, 6px per character + padding)
	labelWidth := len(label)*6 + 10
	statusWidth := len(status)*6 + 10
	totalWidth := labelWidth + statusWidth

	var svg string
	if style == "plastic" {
		// Plastic style with gradient
		svg = fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="20">
  <linearGradient id="b" x2="0" y2="100%%">
    <stop offset="0" stop-color="#fff" stop-opacity=".7"/>
    <stop offset=".1" stop-color="#aaa" stop-opacity=".1"/>
    <stop offset=".9" stop-color="#000" stop-opacity=".3"/>
    <stop offset="1" stop-color="#000" stop-opacity=".5"/>
  </linearGradient>
  <clipPath id="a">
    <rect width="%d" height="20" rx="3" fill="#fff"/>
  </clipPath>
  <g clip-path="url(#a)">
    <rect width="%d" height="20" fill="#555"/>
    <rect x="%d" width="%d" height="20" fill="%s"/>
    <rect width="%d" height="20" fill="url(#b)"/>
  </g>
  <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
    <text x="%d" y="15" fill="#010101" fill-opacity=".3">%s</text>
    <text x="%d" y="14">%s</text>
    <text x="%d" y="15" fill="#010101" fill-opacity=".3">%s</text>
    <text x="%d" y="14">%s</text>
  </g>
</svg>`,
			totalWidth, totalWidth, labelWidth, labelWidth, statusWidth, color, totalWidth,
			labelWidth/2, label, labelWidth/2, label,
			labelWidth+statusWidth/2, status, labelWidth+statusWidth/2, status)
	} else {
		// Flat style (default)
		svg = fmt.Sprintf(`<svg xmlns="http://www.w3.org/2000/svg" width="%d" height="20">
  <clipPath id="a">
    <rect width="%d" height="20" rx="3" fill="#fff"/>
  </clipPath>
  <g clip-path="url(#a)">
    <rect width="%d" height="20" fill="#555"/>
    <rect x="%d" width="%d" height="20" fill="%s"/>
  </g>
  <g fill="#fff" text-anchor="middle" font-family="DejaVu Sans,Verdana,Geneva,sans-serif" font-size="11">
    <text x="%d" y="15" fill="#010101" fill-opacity=".3">%s</text>
    <text x="%d" y="14">%s</text>
    <text x="%d" y="15" fill="#010101" fill-opacity=".3">%s</text>
    <text x="%d" y="14">%s</text>
  </g>
</svg>`,
			totalWidth, totalWidth, labelWidth, labelWidth, statusWidth, color,
			labelWidth/2, label, labelWidth/2, label,
			labelWidth+statusWidth/2, status, labelWidth+statusWidth/2, status)
	}

	w.Header().Set("Content-Type", "image/svg+xml")
	w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate")
	w.Write([]byte(svg))
}

// APISummaryResponse contains a lightweight status overview
type APISummaryResponse struct {
	OverallStatus string       `json:"overall_status"`
	Counts        StatusCounts `json:"counts"`
	LastUpdated   time.Time    `json:"last_updated"`
}

// handleAPISummary returns a lightweight status summary (no history data)
func (s *Server) handleAPISummary(w http.ResponseWriter, r *http.Request) {
	cfg := s.getConfig()
	ctx := r.Context()

	stats, err := s.storage.GetAllMonitorStats(ctx)
	if err != nil {
		s.jsonError(w, "Failed to get stats", http.StatusInternalServerError)
		return
	}

	response := APISummaryResponse{
		LastUpdated: time.Now(),
	}

	overallUp := true
	hasDegraded := false

	for _, group := range cfg.Groups {
		for _, monCfg := range group.Monitors {
			// Use composite ID (group/name) to look up stats
			monitorID := monCfg.ID()
			stat, ok := stats[monitorID]
			if !ok {
				continue
			}

			response.Counts.Total++
			switch stat.CurrentStatus {
			case "down":
				overallUp = false
				response.Counts.Down++
			case "degraded":
				hasDegraded = true
				response.Counts.Degraded++
			case "up":
				response.Counts.Up++
			}
		}
	}

	if !overallUp {
		response.OverallStatus = "Major Outage"
	} else if hasDegraded {
		response.OverallStatus = "Partial Outage"
	} else {
		response.OverallStatus = "All Systems Operational"
	}

	s.jsonResponse(w, response)
}

// APIUptimeResponse contains historical uptime statistics
type APIUptimeResponse struct {
	Monitor       string  `json:"monitor"`
	Period        string  `json:"period"`
	UptimePercent float64 `json:"uptime_percent"`
	TotalChecks   int64   `json:"total_checks"`
	SuccessChecks int64   `json:"success_checks"`
	FailedChecks  int64   `json:"failed_checks"`
}

// handleAPIUptime returns historical uptime for a specific period
func (s *Server) handleAPIUptime(w http.ResponseWriter, r *http.Request) {
	group := r.PathValue("group")
	name := r.PathValue("name")
	if group == "" || name == "" {
		s.jsonError(w, "Group and monitor name required", http.StatusBadRequest)
		return
	}

	// Construct composite ID (re-encode to match internal format)
	monitorID := url.PathEscape(group) + "/" + url.PathEscape(name)

	// Parse period (default: 24h, options: 1h, 24h, 7d, 30d, 90d)
	period := r.URL.Query().Get("period")
	if period == "" {
		period = "24h"
	}

	var duration time.Duration
	switch period {
	case "1h":
		duration = time.Hour
	case "24h":
		duration = 24 * time.Hour
	case "7d":
		duration = 7 * 24 * time.Hour
	case "30d":
		duration = 30 * 24 * time.Hour
	case "90d":
		duration = 90 * 24 * time.Hour
	default:
		s.jsonError(w, "Invalid period (use: 1h, 24h, 7d, 30d, 90d)", http.StatusBadRequest)
		return
	}

	stats, err := s.storage.GetUptimeStats(r.Context(), monitorID, duration)
	if err != nil {
		s.jsonError(w, "Failed to get uptime stats", http.StatusInternalServerError)
		return
	}

	s.jsonResponse(w, APIUptimeResponse{
		Monitor:       monitorID,
		Period:        period,
		UptimePercent: stats.UptimePercent,
		TotalChecks:   stats.TotalChecks,
		SuccessChecks: stats.SuccessChecks,
		FailedChecks:  stats.FailedChecks,
	})
}

// APIIncidentResponse contains incident data for the API
type APIIncidentResponse struct {
	Title          string     `json:"title"`
	Status         string     `json:"status"`
	Message        string     `json:"message"`
	IsActive       bool       `json:"is_active"`
	CreatedAt      *time.Time `json:"created_at,omitempty"`
	ResolvedAt     *time.Time `json:"resolved_at,omitempty"`
	ScheduledStart *time.Time `json:"scheduled_start,omitempty"`
	ScheduledEnd   *time.Time `json:"scheduled_end,omitempty"`
	Affected       []string   `json:"affected_monitors,omitempty"`
}

// handleAPIIncidents returns active and recent incidents
func (s *Server) handleAPIIncidents(w http.ResponseWriter, r *http.Request) {
	cfg := s.getConfig()
	// Filter: all, active, resolved, scheduled (default: all)
	filter := r.URL.Query().Get("filter")

	var incidents []APIIncidentResponse

	for _, inc := range cfg.Incidents {
		isActive := inc.Status != "resolved"
		isScheduled := inc.Status == "scheduled"

		// Apply filter
		switch filter {
		case "active":
			if !isActive || isScheduled {
				continue
			}
		case "resolved":
			if isActive {
				continue
			}
		case "scheduled":
			if !isScheduled {
				continue
			}
		}

		incidents = append(incidents, APIIncidentResponse{
			Title:          inc.Title,
			Status:         inc.Status,
			Message:        inc.Message,
			IsActive:       isActive,
			CreatedAt:      inc.CreatedAt,
			ResolvedAt:     inc.ResolvedAt,
			ScheduledStart: inc.ScheduledStart,
			ScheduledEnd:   inc.ScheduledEnd,
			Affected:       inc.AffectedMonitors,
		})
	}

	s.jsonResponse(w, map[string]interface{}{
		"incidents": incidents,
		"count":     len(incidents),
	})
}

// SetReloadFunc sets the callback function for reloading configuration
func (s *Server) SetReloadFunc(fn ReloadFunc) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.reloadConfig = fn
}

// SetVersion sets the version information for display
func (s *Server) SetVersion(version, commit, date string) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.version = VersionInfo{
		Version: version,
		Commit:  commit,
		Date:    date,
	}
}

// UpdateConfig atomically updates the server's config and scheduler for zero-downtime reload
func (s *Server) UpdateConfig(cfg *config.Config, sched *monitor.Scheduler) {
	s.mu.Lock()
	defer s.mu.Unlock()
	s.config = cfg
	s.scheduler = sched
}

// getConfig returns the current config (thread-safe)
func (s *Server) getConfig() *config.Config {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.config
}

// getScheduler returns the current scheduler (thread-safe)
func (s *Server) getScheduler() *monitor.Scheduler {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.scheduler
}

// getVersion returns the current version info (thread-safe)
func (s *Server) getVersion() VersionInfo {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.version
}

// getReloadFunc returns the reload function (thread-safe)
func (s *Server) getReloadFunc() ReloadFunc {
	s.mu.RLock()
	defer s.mu.RUnlock()
	return s.reloadConfig
}

// handleAPIReload triggers a configuration reload (always requires authentication)
func (s *Server) handleAPIReload(w http.ResponseWriter, r *http.Request) {
	if s.reloadConfig == nil {
		s.jsonError(w, "Reload function not configured", http.StatusServiceUnavailable)
		return
	}

	s.logger.Info("config reload triggered via API", "remote_addr", r.RemoteAddr)

	if err := s.reloadConfig(); err != nil {
		s.logger.Error("config reload failed", "error", err)
		s.jsonError(w, fmt.Sprintf("Reload failed: %v", err), http.StatusInternalServerError)
		return
	}

	s.jsonResponse(w, map[string]string{
		"status":  "ok",
		"message": "Configuration reloaded successfully",
	})
}

// jsonResponse writes a JSON response
func (s *Server) jsonResponse(w http.ResponseWriter, data interface{}) {
	w.Header().Set("Content-Type", "application/json")
	if err := json.NewEncoder(w).Encode(data); err != nil {
		s.logger.Error("failed to encode JSON response", "error", err)
	}
}

// jsonError writes a JSON error response
func (s *Server) jsonError(w http.ResponseWriter, message string, status int) {
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(status)
	json.NewEncoder(w).Encode(map[string]string{"error": message})
}

// templateFuncs returns custom template functions
func templateFuncs() template.FuncMap {
	return template.FuncMap{
		"formatTime": func(t time.Time) string {
			if t.IsZero() {
				return "-"
			}
			return t.Format("Jan 2, 15:04 UTC")
		},
		"formatDate": func(t time.Time) string {
			if t.IsZero() {
				return "-"
			}
			return t.Format("Jan 2, 2006")
		},
		"formatDuration": func(ms int64) string {
			if ms < 1000 {
				return fmt.Sprintf("%dms", ms)
			}
			return fmt.Sprintf("%.2fs", float64(ms)/1000)
		},
		"formatUptime": func(pct float64) string {
			if pct < 0 {
				return "-"
			}
			return fmt.Sprintf("%.2f%%", pct)
		},
		"timeAgo": func(t time.Time) string {
			if t.IsZero() {
				return "never"
			}
			d := time.Since(t)
			if d < time.Minute {
				return fmt.Sprintf("%d seconds ago", int(d.Seconds()))
			}
			if d < time.Hour {
				return fmt.Sprintf("%d minutes ago", int(d.Minutes()))
			}
			if d < 24*time.Hour {
				return fmt.Sprintf("%d hours ago", int(d.Hours()))
			}
			return fmt.Sprintf("%d days ago", int(d.Hours()/24))
		},
		"tickColor": func(tick *storage.TickData) string {
			if tick == nil {
				return "bg-neutral-200 dark:bg-neutral-800" // No data
			}
			if tick.UptimePercent >= 99 {
				return "bg-emerald-500"
			}
			if tick.UptimePercent >= 95 {
				return "bg-yellow-500"
			}
			if tick.UptimePercent > 0 {
				return "bg-red-500"
			}
			// For ping mode with status
			switch tick.Status {
			case "up":
				return "bg-emerald-500"
			case "degraded":
				return "bg-yellow-500"
			case "down":
				return "bg-red-500"
			}
			return "bg-neutral-200 dark:bg-neutral-800"
		},
		"simplifyError": simplifyErrorMessage,
		"tickTooltipData": func(tick *storage.TickData, mode, timezone string, hidePing bool) string {
			if tick == nil {
				data := map[string]interface{}{"header": "No data"}
				b, _ := json.Marshal(data)
				return string(b)
			}

			// If using browser timezone, include raw timestamp for client-side conversion
			useBrowserTz := timezone == "Browser"

			// Convert timestamp to configured timezone (fallback for non-JS users)
			loc := time.Local
			if timezone != "" && timezone != "Local" && timezone != "Browser" {
				if l, err := time.LoadLocation(timezone); err == nil {
					loc = l
				}
			}
			t := tick.Timestamp.In(loc)

			// Get timezone info
			tzAbbr := t.Format("MST")
			_, offset := t.Zone()
			hours := offset / 3600
			minutes := (offset % 3600) / 60
			var utcOffset string
			if minutes != 0 {
				utcOffset = fmt.Sprintf("UTC%+d:%02d", hours, abs(minutes))
			} else {
				utcOffset = fmt.Sprintf("UTC%+d", hours)
			}

			var header, statusClass string
			data := make(map[string]interface{})
			rows := []map[string]string{}

			// Include raw timestamp for browser timezone conversion
			if useBrowserTz {
				data["timestamp"] = tick.Timestamp.Format(time.RFC3339)
				data["mode"] = mode
			}

			switch mode {
			case "ping":
				header = t.Format("Jan 2, 15:04:05")
				statusClass = tickStatusClass(tick.Status)
				rows = append(rows,
					map[string]string{"label": "Status", "value": tick.Status, "class": statusClass},
				)
				if !hidePing {
					rows = append(rows,
						map[string]string{"label": "Response", "value": fmt.Sprintf("%dms", tick.ResponseTime), "class": ""},
					)
				}
				rows = append(rows,
					map[string]string{"label": "Timezone", "value": fmt.Sprintf("%s (%s)", tzAbbr, utcOffset), "class": ""},
				)
			case "minute":
				header = t.Format("Jan 2, 15:04")
				statusClass = uptimeStatusClass(tick.UptimePercent)
				rows = append(rows,
					map[string]string{"label": "Checks", "value": fmt.Sprintf("%d", tick.TotalChecks), "class": ""},
					map[string]string{"label": "Uptime", "value": fmt.Sprintf("%.1f%%", tick.UptimePercent), "class": statusClass},
				)
				if !hidePing {
					rows = append(rows,
						map[string]string{"label": "Avg Response", "value": fmt.Sprintf("%dms", int(tick.AvgResponse)), "class": ""},
					)
				}
				rows = append(rows,
					map[string]string{"label": "Timezone", "value": fmt.Sprintf("%s (%s)", tzAbbr, utcOffset), "class": ""},
				)
			case "hour":
				header = t.Format("Jan 2, 15:00")
				statusClass = uptimeStatusClass(tick.UptimePercent)
				rows = append(rows,
					map[string]string{"label": "Checks", "value": fmt.Sprintf("%d", tick.TotalChecks), "class": ""},
					map[string]string{"label": "Uptime", "value": fmt.Sprintf("%.1f%%", tick.UptimePercent), "class": statusClass},
				)
				if !hidePing {
					rows = append(rows,
						map[string]string{"label": "Avg Response", "value": fmt.Sprintf("%dms", int(tick.AvgResponse)), "class": ""},
					)
				}
				rows = append(rows,
					map[string]string{"label": "Timezone", "value": fmt.Sprintf("%s (%s)", tzAbbr, utcOffset), "class": ""},
				)
			case "day":
				header = t.Format("Jan 2, 2006")
				statusClass = uptimeStatusClass(tick.UptimePercent)
				rows = append(rows,
					map[string]string{"label": "Checks", "value": fmt.Sprintf("%d", tick.TotalChecks), "class": ""},
					map[string]string{"label": "Uptime", "value": fmt.Sprintf("%.1f%%", tick.UptimePercent), "class": statusClass},
				)
				if !hidePing {
					rows = append(rows,
						map[string]string{"label": "Avg Response", "value": fmt.Sprintf("%dms", int(tick.AvgResponse)), "class": ""},
					)
				}
				rows = append(rows,
					map[string]string{"label": "Timezone", "value": fmt.Sprintf("%s (%s)", tzAbbr, utcOffset), "class": ""},
				)
			default:
				header = t.Format("Jan 2, 15:04")
			}

			data["header"] = header
			data["rows"] = rows

			b, _ := json.Marshal(data)
			return string(b)
		},
		"seq": func(n int) []int {
			result := make([]int, n)
			for i := range result {
				result[i] = i
			}
			return result
		},
	}
}

// formatCurrentTime formats the current time for display without timezone
func formatCurrentTime(t time.Time, timezone string) string {
	loc := time.Local

	if timezone != "" && timezone != "Local" {
		if l, err := time.LoadLocation(timezone); err == nil {
			loc = l
		}
	}

	t = t.In(loc)
	return t.Format("Jan 2, 2006 15:04")
}

// formatTimezoneTooltip creates JSON data for timezone tooltip
func formatTimezoneTooltip(t time.Time, timezone string) string {
	loc := time.Local

	if timezone != "" && timezone != "Local" {
		if l, err := time.LoadLocation(timezone); err == nil {
			loc = l
		}
	}

	t = t.In(loc)

	// Get timezone abbreviation (like PST, EST, etc.)
	tzAbbr := t.Format("MST")

	// Get UTC offset in format like "UTC-8" or "UTC+5:30"
	_, offset := t.Zone()
	hours := offset / 3600
	minutes := (offset % 3600) / 60
	var utcOffset string
	if minutes != 0 {
		utcOffset = fmt.Sprintf("UTC%+d:%02d", hours, abs(minutes))
	} else {
		utcOffset = fmt.Sprintf("UTC%+d", hours)
	}

	// Get GMT offset in same format
	var gmtOffset string
	if minutes != 0 {
		gmtOffset = fmt.Sprintf("GMT%+d:%02d", hours, abs(minutes))
	} else {
		gmtOffset = fmt.Sprintf("GMT%+d", hours)
	}

	data := map[string]interface{}{
		"header": "Timezone",
		"rows": []map[string]string{
			{"label": "Abbreviation", "value": tzAbbr, "class": ""},
			{"label": "UTC Offset", "value": utcOffset, "class": ""},
			{"label": "GMT Offset", "value": gmtOffset, "class": ""},
		},
	}

	b, _ := json.Marshal(data)
	return string(b)
}

// abs returns the absolute value of an integer
func abs(n int) int {
	if n < 0 {
		return -n
	}
	return n
}

// formatSSLTooltip creates JSON data for SSL expiration tooltip
func formatSSLTooltip(expiryDate time.Time, daysLeft int, timezone string) string {
	loc := time.Local

	if timezone != "" && timezone != "Local" {
		if l, err := time.LoadLocation(timezone); err == nil {
			loc = l
		}
	}

	t := expiryDate.In(loc)

	// Get timezone abbreviation
	tzAbbr := t.Format("MST")

	// Get UTC offset
	_, offset := t.Zone()
	hours := offset / 3600
	minutes := (offset % 3600) / 60
	var utcOffset string
	if minutes != 0 {
		utcOffset = fmt.Sprintf("UTC%+d:%02d", hours, abs(minutes))
	} else {
		utcOffset = fmt.Sprintf("UTC%+d", hours)
	}

	// Get GMT offset
	var gmtOffset string
	if minutes != 0 {
		gmtOffset = fmt.Sprintf("GMT%+d:%02d", hours, abs(minutes))
	} else {
		gmtOffset = fmt.Sprintf("GMT%+d", hours)
	}

	// Format the expiry date
	expiryStr := t.Format("Jan 2, 2006 15:04:05")

	// Determine status message
	var statusMsg, statusClass string
	if daysLeft < 0 {
		statusMsg = "Expired"
		statusClass = "error"
	} else if daysLeft < 7 {
		statusMsg = fmt.Sprintf("%d days (Critical)", daysLeft)
		statusClass = "error"
	} else if daysLeft < 14 {
		statusMsg = fmt.Sprintf("%d days (Warning)", daysLeft)
		statusClass = "warning"
	} else {
		statusMsg = fmt.Sprintf("%d days", daysLeft)
		statusClass = "success"
	}

	data := map[string]interface{}{
		"header": "SSL Certificate",
		"rows": []map[string]string{
			{"label": "Expires", "value": expiryStr, "class": ""},
			{"label": "Days Left", "value": statusMsg, "class": statusClass},
			{"label": "Timezone", "value": tzAbbr, "class": ""},
			{"label": "UTC Offset", "value": utcOffset, "class": ""},
			{"label": "GMT Offset", "value": gmtOffset, "class": ""},
		},
	}

	b, _ := json.Marshal(data)
	return string(b)
}

// formatLastUpdatedTooltip creates JSON data for last updated tooltip
func formatLastUpdatedTooltip(t time.Time, timezone string) string {
	loc := time.Local

	if timezone != "" && timezone != "Local" {
		if l, err := time.LoadLocation(timezone); err == nil {
			loc = l
		}
	}

	t = t.In(loc)

	// Get timezone abbreviation
	tzAbbr := t.Format("MST")

	// Get UTC offset
	_, offset := t.Zone()
	hours := offset / 3600
	minutes := (offset % 3600) / 60
	var utcOffset string
	if minutes != 0 {
		utcOffset = fmt.Sprintf("UTC%+d:%02d", hours, abs(minutes))
	} else {
		utcOffset = fmt.Sprintf("UTC%+d", hours)
	}

	// Get GMT offset
	var gmtOffset string
	if minutes != 0 {
		gmtOffset = fmt.Sprintf("GMT%+d:%02d", hours, abs(minutes))
	} else {
		gmtOffset = fmt.Sprintf("GMT%+d", hours)
	}

	// Format the datetime
	datetime := t.Format("Jan 2, 2006 15:04:05")

	data := map[string]interface{}{
		"header": "Last Check",
		"rows": []map[string]string{
			{"label": "Date & Time", "value": datetime, "class": ""},
			{"label": "Timezone", "value": tzAbbr, "class": ""},
			{"label": "UTC Offset", "value": utcOffset, "class": ""},
			{"label": "GMT Offset", "value": gmtOffset, "class": ""},
		},
	}

	b, _ := json.Marshal(data)
	return string(b)
}

// formatUptimeTooltip creates JSON data for uptime percentage tooltip
func formatUptimeTooltip(uptimePercent float64, totalChecks int64, lastFailure *time.Time, lastFailureError string, timezone string) string {
	loc := time.Local

	if timezone != "" && timezone != "Local" && timezone != "Browser" {
		if l, err := time.LoadLocation(timezone); err == nil {
			loc = l
		}
	}

	rows := []map[string]string{
		{"label": "Uptime", "value": fmt.Sprintf("%.2f%%", uptimePercent), "class": ""},
		{"label": "Total Checks", "value": fmt.Sprintf("%d", totalChecks), "class": ""},
	}

	if lastFailure != nil {
		t := lastFailure.In(loc)
		failureTime := t.Format("Jan 2, 2006 15:04:05")
		rows = append(rows, map[string]string{"label": "Last Failure", "value": failureTime, "class": "error"})

		if lastFailureError != "" {
			// Simplify the error for display
			simplifiedError := simplifyErrorMessage(lastFailureError)
			rows = append(rows, map[string]string{"label": "Failure Reason", "value": simplifiedError, "class": ""})
		}
	} else {
		rows = append(rows, map[string]string{"label": "Last Failure", "value": "Never", "class": "success"})
	}

	data := map[string]interface{}{
		"header": "Uptime Statistics",
		"rows":   rows,
	}

	b, _ := json.Marshal(data)
	return string(b)
}

// formatVersionTooltip creates JSON data for version tooltip
func (s *Server) formatVersionTooltip() string {
	cfg := s.getConfig()
	timezone := cfg.Display.Timezone
	useBrowserTz := timezone == "Browser"

	rows := []map[string]string{
		{"label": "Version", "value": s.version.Version, "class": ""},
		{"label": "Commit", "value": s.version.Commit, "class": ""},
	}

	data := map[string]interface{}{
		"header": "Kaze",
	}

	// Parse and format build date if available
	if s.version.Date != "" && s.version.Date != "unknown" {
		if t, err := time.Parse(time.RFC3339, s.version.Date); err == nil {
			// Include raw timestamp for browser timezone conversion
			if useBrowserTz {
				data["timestamp"] = t.Format(time.RFC3339)
				data["timestampLabel"] = "Built"
			}

			// Convert to configured timezone for server-side rendering
			loc := time.Local
			if timezone != "" && timezone != "Local" && timezone != "Browser" {
				if l, err := time.LoadLocation(timezone); err == nil {
					loc = l
				}
			}
			t = t.In(loc)
			rows = append(rows, map[string]string{"label": "Built", "value": t.Format("Jan 2, 2006 15:04"), "class": ""})
		} else {
			rows = append(rows, map[string]string{"label": "Built", "value": s.version.Date, "class": ""})
		}
	}

	data["rows"] = rows

	b, _ := json.Marshal(data)
	return string(b)
}

// simplifyErrorMessage simplifies error messages for display
func simplifyErrorMessage(err string) string {
	if err == "" {
		return ""
	}
	switch {
	case strings.Contains(err, "no such host"):
		return "DNS lookup failed"
	case strings.Contains(err, "connection refused"):
		return "Connection refused"
	case strings.Contains(err, "connection reset"):
		return "Connection reset"
	case strings.Contains(err, "timeout"):
		return "Timeout"
	case strings.Contains(err, "certificate"):
		return "SSL/TLS error"
	case strings.Contains(err, "EOF"):
		return "Connection closed"
	case strings.Contains(err, "status code"):
		return "Unexpected status"
	case strings.Contains(err, "expected content"):
		return "Content mismatch"
	case strings.Contains(err, "i/o timeout"):
		return "I/O timeout"
	case strings.Contains(err, "network is unreachable"):
		return "Network unreachable"
	default:
		return "Error"
	}
}

// statusToClass converts a status to a CSS class
func statusToClass(status string) string {
	switch status {
	case "up":
		return "status-up"
	case "down":
		return "status-down"
	case "degraded":
		return "status-degraded"
	default:
		return "status-unknown"
	}
}

// tickStatusClass returns CSS class for tooltip status text
func tickStatusClass(status string) string {
	switch status {
	case "up":
		return "success"
	case "degraded":
		return "warning"
	case "down":
		return "error"
	default:
		return ""
	}
}

// uptimeStatusClass returns CSS class based on uptime percentage
func uptimeStatusClass(pct float64) string {
	if pct >= 99 {
		return "success"
	}
	if pct >= 95 {
		return "warning"
	}
	return "error"
}

// incidentStatusToClass converts an incident status to a CSS class
func incidentStatusToClass(status string) string {
	switch status {
	case "scheduled":
		return "incident-scheduled"
	case "investigating":
		return "incident-investigating"
	case "identified":
		return "incident-identified"
	case "monitoring":
		return "incident-monitoring"
	case "resolved":
		return "incident-resolved"
	default:
		return "incident-unknown"
	}
}