Spaces:
Running

File size: 75,324 Bytes
c062f7a
 
 
 
 
 
 
 
456988d
 
 
 
 
c062f7a
 
 
 
 
 
 
 
 
 
 
456988d
 
c062f7a
456988d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c062f7a
 
 
 
 
 
 
 
 
 
 
456988d
 
c062f7a
456988d
 
 
 
 
 
 
 
3f0bda9
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
fee94c0
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
456988d
c062f7a
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
456988d
 
 
 
 
 
 
 
 
 
 
c062f7a
3f0bda9
c062f7a
3f0bda9
 
 
 
 
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0bda9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c062f7a
 
 
 
e0cbfb9
456988d
c062f7a
 
456988d
 
 
 
 
 
 
 
 
 
 
 
e0cbfb9
456988d
 
 
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
 
 
c062f7a
 
 
 
fee94c0
c062f7a
 
 
 
 
 
 
 
 
456988d
 
 
 
 
 
 
 
 
 
 
 
c062f7a
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
fee94c0
 
 
 
3f0bda9
fee94c0
3f0bda9
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
fee94c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c062f7a
 
 
fee94c0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c062f7a
fee94c0
 
 
c062f7a
 
 
 
fee94c0
c062f7a
 
 
fee94c0
 
c062f7a
fee94c0
 
c062f7a
fee94c0
c062f7a
 
 
fee94c0
 
c062f7a
fee94c0
c062f7a
 
 
 
fee94c0
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3f0bda9
c062f7a
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456988d
c062f7a
456988d
c062f7a
 
 
3f0bda9
 
 
456988d
 
c062f7a
456988d
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
 
3f0bda9
 
fee94c0
 
 
c062f7a
fee94c0
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
c062f7a
 
 
 
 
fee94c0
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
 
 
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
 
 
 
 
 
 
c062f7a
 
 
 
fee94c0
c062f7a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fee94c0
 
 
c062f7a
 
3f0bda9
456988d
c062f7a
 
 
 
 
 
 
fee94c0
c062f7a
 
 
 
 
 
 
 
 
 
456988d
c062f7a
 
 
 
 
 
699f3d6
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
<meta name="theme-color" content="#08090e">
<title>Football Live</title>
<link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Inter:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap" rel="stylesheet">
<script>
(function(){ var t = 'auto'; try { t = JSON.parse(localStorage.getItem('fl3_theme')) || 'auto'; } catch (e) {}
  var light = t === 'light' || (t === 'auto' && window.matchMedia && matchMedia('(prefers-color-scheme: light)').matches);
  document.documentElement.setAttribute('data-theme', light ? 'light' : 'dark'); })();
</script>
<style>
:root{
  --bg:#08090e;--s1:#10131c;--s2:#171b27;--s3:#1f2433;
  --bdr:rgba(255,255,255,.07);--bdr2:rgba(255,255,255,.14);
  --gold:#f4c430;--gold2:#ffd84d;--gbg:rgba(244,196,48,.10);--gbdr:rgba(244,196,48,.32);
  --w:#edf0f8;--gr:#9aa3bd;--dim:#5d6684;
  --green:#2ed172;--grbg:rgba(46,209,114,.13);
  --red:#ff5050;--rdbg:rgba(255,80,80,.13);
  --blue:#5b9cff;--blbg:rgba(91,156,255,.14);
  --orange:#ff9f43;--orbg:rgba(255,159,67,.14);
  --live:#ff3b3b;
  --hdr:#0e1122;--bar:rgba(11,13,23,.97);--chip:rgba(255,255,255,.06);--notec:#a9c8ff;
  --livesc:#ffffff;--glow:rgba(244,196,48,.3);--goldbtn:#f4c430;
  --nav-h:62px;
  color-scheme:dark;
}
:root[data-theme="light"]{
  --bg:#f3f5fa;--s1:#ffffff;--s2:#eceff6;--s3:#dfe3ec;
  --bdr:rgba(16,19,28,.09);--bdr2:rgba(16,19,28,.17);
  --gold:#a97700;--gold2:#8a6000;--gbg:rgba(169,119,0,.10);--gbdr:rgba(169,119,0,.38);
  --w:#141824;--gr:#4f586d;--dim:#737b8f;
  --green:#14894a;--grbg:rgba(20,137,74,.11);
  --red:#d42e2e;--rdbg:rgba(212,46,46,.10);
  --blue:#2563d6;--blbg:rgba(37,99,214,.09);
  --orange:#c56a0c;--orbg:rgba(197,106,12,.11);
  --live:#e02424;
  --hdr:#ffffff;--bar:rgba(255,255,255,.97);--chip:rgba(16,19,28,.06);--notec:#1d4fae;
  --livesc:#141824;--glow:transparent;--goldbtn:#f2bf26;
  color-scheme:light;
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{background:var(--bg);color:var(--w);font-family:'Inter',system-ui,sans-serif;font-size:14px;line-height:1.5;min-height:100vh;padding-bottom:calc(var(--nav-h) + env(safe-area-inset-bottom));overflow-x:hidden}
body.today{padding-bottom:calc(20px + env(safe-area-inset-bottom))}
body.noscroll{overflow:hidden}
button{font-family:inherit;cursor:pointer}
input{font-family:inherit}
.wrap{max-width:860px;margin:0 auto}

/* header */
.hdr{background:linear-gradient(180deg,var(--hdr) 0%,var(--bg) 100%);padding:calc(10px + env(safe-area-inset-top)) 12px 8px;text-align:center}
.hdr h1{font-family:'Bebas Neue';font-size:clamp(28px,7vw,42px);letter-spacing:4px;color:var(--gold);line-height:1;text-shadow:0 0 28px var(--glow)}
.hdr-sub{font-size:10px;font-weight:600;letter-spacing:2.5px;color:var(--gr);text-transform:uppercase;margin-top:4px}
.top{display:flex;justify-content:space-between;align-items:flex-start;gap:10px;margin-bottom:6px}
.theme{display:inline-flex;background:var(--s2);border:1px solid var(--bdr2);border-radius:10px;padding:2px;gap:2px}
.theme button{border:0;background:none;width:36px;height:32px;border-radius:8px;font-size:15px;line-height:1;opacity:.55}
.theme button.on{background:var(--s1);opacity:1;box-shadow:0 1px 3px rgba(0,0,0,.18)}
.who-r{display:flex;flex-direction:column;align-items:flex-end;gap:3px;min-width:0}
.setbtn{display:inline-flex;align-items:center;gap:6px;height:36px;padding:0 12px;border-radius:10px;border:1px solid var(--gbdr);background:var(--gbg);color:var(--gold2);font-weight:700;font-size:12.5px;white-space:nowrap}
.setbtn svg{width:16px;height:16px;flex-shrink:0}
.sig{font-size:9.5px;color:var(--dim);font-weight:600;letter-spacing:.2px;white-space:nowrap}
/* tabs + signature: phones stack the signature on its own line; wide screens put it at the right of the tabs */
.navgrid{display:grid;grid-template-columns:minmax(0,1fr);grid-template-areas:"secs" "chips" "sig"}
.navgrid .secs{grid-area:secs;min-width:0}.navgrid .chips{grid-area:chips;min-width:0}
.navgrid .sig{grid-area:sig;justify-self:end;padding:0 14px 5px}
@media(min-width:1080px){
  .navgrid{grid-template-columns:1fr auto 1fr;grid-template-areas:". secs sig" ". chips ."}
  .navgrid .sig{align-self:center;padding:0 16px 2px 8px}
}
.sig b{color:var(--gr);font-weight:700}

/* sections + competition chips */
.secs{display:flex;gap:6px;overflow-x:auto;padding:6px 12px 8px;scrollbar-width:none;justify-content:safe center}
.secs::-webkit-scrollbar,.chips::-webkit-scrollbar{display:none}
.secs button{flex-shrink:0;border:1px solid var(--bdr2);background:var(--s2);color:var(--gr);font-weight:700;font-size:12.5px;padding:8px 13px;border-radius:999px;display:flex;align-items:center;gap:6px;min-height:38px}
.secs button.on{background:var(--goldbtn);color:#16130a;border-color:var(--gold)}
.chips{display:flex;gap:6px;overflow-x:auto;padding:0 12px 10px;scrollbar-width:none;justify-content:safe center}
.chips button{flex-shrink:0;border:1px solid var(--bdr);background:transparent;color:var(--gr);font-weight:600;font-size:12px;padding:6px 12px;border-radius:8px;min-height:34px}
.chips button.on{background:var(--gbg);color:var(--gold2);border-color:var(--gbdr)}
.chips:empty{display:none}
.hline{height:2px;background:linear-gradient(90deg,transparent,var(--gold),transparent)}
.cal{width:18px;height:18px;border-radius:3px;overflow:hidden;background:#fff;display:inline-flex;flex-direction:column;flex-shrink:0}
.cal b{background:var(--red);color:#fff;font-size:5px;line-height:6px;text-align:center}
.cal i{font-style:normal;font-weight:800;font-size:9.5px;line-height:12px;color:#111;text-align:center}

/* sticky bar */
.sbar{position:sticky;top:0;z-index:30;background:var(--bar);backdrop-filter:blur(6px);border-bottom:1px solid var(--bdr);padding:8px 14px;display:flex;align-items:center;gap:10px}
.rf{display:flex;align-items:center;gap:6px;background:var(--green);color:#04150b;border:0;border-radius:8px;padding:8px 13px;font-size:11px;font-weight:800;letter-spacing:.6px;text-transform:uppercase;min-height:36px;flex-shrink:0}
.rf:disabled{opacity:.55}
.rf.busy .ic{display:inline-block;animation:spin .7s linear infinite}
@keyframes spin{to{transform:rotate(360deg)}}
.stxt{font-size:11px;color:var(--gr);flex:1;min-width:0;line-height:1.35}
.stxt b{color:var(--green)}
.stxt.err b{color:var(--orange)}
.clk{font-family:'JetBrains Mono';font-size:11px;color:var(--gr);flex-shrink:0}

/* panels */
.panel{display:none;padding:14px}
.panel.on{display:block}
.sec{font-family:'Bebas Neue';font-size:19px;letter-spacing:2px;color:var(--gold);margin:18px 0 8px;display:flex;align-items:baseline;gap:8px;flex-wrap:wrap}
.sec:first-child{margin-top:2px}
.sec small{font-family:'Inter';font-size:11px;letter-spacing:0;color:var(--gr);font-weight:600}
.sub{font-size:11px;font-weight:800;letter-spacing:1.2px;text-transform:uppercase;color:var(--gr);margin:12px 0 6px;display:flex;align-items:center;gap:6px}
.day{font-size:11px;font-weight:700;letter-spacing:1.2px;text-transform:uppercase;color:var(--gr);margin:14px 0 6px}
.note{background:var(--blbg);border:1px solid rgba(91,156,255,.28);color:var(--notec);border-radius:9px;padding:9px 12px;font-size:12px;font-weight:600;margin-bottom:10px;line-height:1.5}
.empty{color:var(--gr);font-size:13px;padding:12px 4px}
.msg{background:var(--s1);border:1px solid var(--bdr2);border-radius:12px;padding:18px;line-height:1.7;color:var(--gr)}
.msg h3{color:var(--gold);font-family:'Bebas Neue';letter-spacing:1.5px;font-size:20px;margin-bottom:6px}
.msg.err{border-color:rgba(255,159,67,.45)}
.mode{display:flex;gap:6px;align-items:center;margin-bottom:6px;flex-wrap:wrap}
.mode button{border:1px solid var(--bdr2);background:var(--s2);color:var(--gr);border-radius:8px;padding:6px 12px;font-size:12px;font-weight:700;min-height:34px}
.mode button.on{background:var(--gbg);border-color:var(--gbdr);color:var(--gold2)}
.mode .sp{flex:1}
.dbar{display:flex;gap:6px;align-items:center;margin-bottom:8px}
.dbar button{background:var(--s2);color:var(--w);border:1px solid var(--bdr2);border-radius:8px;min-width:42px;height:42px;font-size:18px;flex-shrink:0}
.dbar button.tdy{font-size:12px;font-weight:700;padding:0 12px;color:var(--gold2);background:var(--gbg);border-color:var(--gbdr)}
.dbar input{flex:1;min-width:0;height:42px;background:var(--s2);border:1px solid var(--bdr2);border-radius:8px;color:var(--w);padding:0 10px;font-size:16px;font-weight:600;text-align:center}
.favs{display:flex;gap:6px;flex-wrap:wrap;margin:4px 0 2px}
.fv{display:inline-flex;align-items:center;gap:5px;background:var(--s2);border:1px solid var(--bdr);border-radius:999px;padding:3px 9px 3px 4px;font-size:11px;font-weight:600;color:var(--w)}
.fv img{width:16px;height:16px;object-fit:contain}
.fv i{width:16px;height:16px;border-radius:50%;background:var(--s3);font-style:normal;font-size:9px;display:inline-flex;align-items:center;justify-content:center;color:var(--gold)}

/* match card */
.m{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:8px 10px;background:var(--s1);border:1px solid var(--bdr);border-radius:12px;padding:12px 14px;margin-bottom:8px;cursor:pointer}
.m.live{border-color:rgba(255,59,59,.45);background:linear-gradient(135deg,rgba(255,59,59,.10),rgba(255,59,59,.03))}
.m.tracked{box-shadow:inset 3px 0 0 var(--gold)}
.m.flash{animation:flash 2.4s ease-out}
@keyframes flash{0%{background:rgba(244,196,48,.35)}100%{}}
.tm{display:flex;align-items:center;gap:8px;min-width:0}
.tm.away{flex-direction:row-reverse;text-align:right}
.tm img{width:26px;height:26px;object-fit:contain;flex-shrink:0}
.tm .nm{min-width:0}
.tm .nm span{font-weight:700;font-size:14px;line-height:1.25;overflow:hidden;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow-wrap:anywhere}
.tm .nm small{display:block;font-size:10.5px;color:var(--dim);font-family:'JetBrains Mono'}
.tm .star{color:var(--gold);font-size:11px;margin-left:3px}
.m.done .tm:not(.win) .nm span{color:var(--gr)}
.mid{text-align:center;min-width:78px}
.sc{font-family:'Bebas Neue';font-size:30px;letter-spacing:3px;line-height:1;color:var(--gold2)}
.m.live .sc{color:var(--livesc)}
.ko{font-family:'JetBrains Mono';font-size:17px;font-weight:600;color:var(--gold)}
.st{display:inline-flex;align-items:center;gap:5px;margin-top:4px;font-size:10px;font-weight:800;letter-spacing:.8px;text-transform:uppercase;padding:2px 8px;border-radius:5px;white-space:nowrap}
.st.lv{background:var(--live);color:#fff}
.st.lv i{width:6px;height:6px;border-radius:50%;background:#fff;animation:blink 1s infinite}
@keyframes blink{50%{opacity:.25}}
.st.ft{background:var(--grbg);color:var(--green)}
.st.ns{background:var(--chip);color:var(--gr)}
.st.pp{background:var(--rdbg);color:var(--red)}
.acts{grid-column:1/-1;display:flex;gap:8px;border-top:1px solid var(--bdr);padding-top:9px;margin-top:2px;align-items:center}
.acts .info{flex:1;min-width:0;font-size:11px;color:var(--dim);line-height:1.35}
.acts .info b{color:var(--gr);font-weight:700}
.btn{border:1px solid var(--bdr2);background:var(--s2);color:var(--w);border-radius:8px;padding:6px 11px;font-size:12px;font-weight:700;white-space:nowrap;min-height:32px}
.btn.trk.on{background:var(--gbg);border-color:var(--gbdr);color:var(--gold2)}
.btn.x{padding:6px 9px;color:var(--gr)}
.btn.wide{width:100%;margin-top:8px;min-height:40px}
.cd{font-family:'JetBrains Mono';color:var(--gold)}

/* round picker */
.mw{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:6px}
.mw button{background:var(--s2);color:var(--w);border:1px solid var(--bdr2);border-radius:8px;width:42px;height:40px;font-size:18px;flex-shrink:0}
.mw button:disabled{opacity:.3}
.mw div{text-align:center;min-width:0}
.mw b{font-family:'Bebas Neue';font-size:22px;letter-spacing:2px;color:var(--gold);display:block;line-height:1.1}
.mw small{font-size:11px;color:var(--gr)}

/* tables */
.tw{overflow-x:auto;border-radius:12px;border:1px solid var(--bdr);margin-bottom:6px}
.tbl{width:100%;border-collapse:collapse;background:var(--s1)}
.tbl th{font-size:10px;font-weight:700;letter-spacing:1px;color:var(--gr);text-transform:uppercase;padding:8px 6px;text-align:center;background:var(--s2);white-space:nowrap}
.tbl th.l,.tbl td.l{text-align:left}
.tbl td{padding:7px 6px;border-top:1px solid var(--bdr);text-align:center;font-size:13px;color:var(--gr);white-space:nowrap}
.tbl td.pos{font-family:'JetBrains Mono';color:var(--w);width:34px;border-left:4px solid transparent}
.tbl td.l{color:var(--w);font-weight:600;white-space:normal}
.tbl td.l .c{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
.tbl td.l img{width:20px;height:20px;object-fit:contain}
.tbl td.pts{font-family:'JetBrains Mono';font-weight:700;color:var(--w)}
.tbl tr.me td.l{color:var(--gold2)}
.bdg{display:inline-block;font-size:9px;font-weight:800;letter-spacing:.6px;text-transform:uppercase;padding:2px 6px;border-radius:4px;white-space:nowrap;color:#08090e}
.form{display:flex;gap:3px;justify-content:center}
.form i{width:16px;height:16px;border-radius:3px;font-size:9px;font-weight:800;font-style:normal;display:flex;align-items:center;justify-content:center;color:#08090e}
.form .W{background:var(--green)}.form .D{background:#8a93ad}.form .L{background:var(--red)}
.legend{display:flex;flex-wrap:wrap;gap:8px 14px;font-size:11px;color:var(--gr);margin:8px 0 4px}
.legend span::before{content:'';display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:5px;vertical-align:-1px;background:var(--c)}
.gname{font-family:'Bebas Neue';letter-spacing:1.5px;font-size:17px;color:var(--w);margin:14px 0 6px}

/* stats */
.who{display:flex;align-items:center;gap:9px}
.who img.ph{width:30px;height:30px;border-radius:50%;object-fit:cover;background:var(--s3);flex-shrink:0}
.who small{display:flex;align-items:center;gap:5px;color:var(--gr);font-weight:500;font-size:11px}
.who small img{width:14px;height:14px;object-fit:contain}
.big{font-family:'JetBrains Mono';font-weight:700;color:var(--gold2)!important;font-size:15px!important}
@media(max-width:560px){.hide-sm{display:none}.tm .nm span{font-size:13px}.tm img{width:22px;height:22px}}

/* sheets (match details + settings) */
.sheet-bg{position:fixed;inset:0;z-index:60;background:rgba(0,0,0,.6);display:none}
.sheet-bg.on{display:block}
.sheet{position:fixed;left:0;right:0;bottom:0;z-index:61;max-height:85vh;max-height:calc(100svh - 24px - env(safe-area-inset-top));overflow:auto;background:var(--bg);border-top:1px solid var(--bdr2);border-radius:18px 18px 0 0;transform:translateY(100%);transition:transform .25s ease;padding:0 0 calc(20px + env(safe-area-inset-bottom));visibility:hidden}
.sheet.on{transform:none;visibility:visible}
@media(min-width:700px){.sheet{left:50%;width:680px;margin-left:-340px}}
.sh-top{position:sticky;top:0;background:var(--bg);z-index:2;padding:12px 14px 0;border-bottom:1px solid var(--bdr)}
.sh-bar{display:flex;justify-content:space-between;align-items:center;gap:8px;margin-bottom:6px}
.sh-bar .ttl{font-size:11px;color:var(--gr);font-weight:600;flex:1;min-width:0}
.sh-bar h2{font-family:'Bebas Neue';letter-spacing:2px;color:var(--gold);font-size:22px;flex:1}
.sh-head{display:grid;grid-template-columns:1fr auto 1fr;align-items:center;gap:10px;padding:6px 0 10px}
.sh-head .t{display:flex;flex-direction:column;align-items:center;gap:5px;text-align:center;font-weight:700;font-size:13px}
.sh-head .t img{width:40px;height:40px;object-fit:contain}
.sh-tabs{display:flex;gap:6px;padding-bottom:10px}
.sh-tabs button{flex:1;border:1px solid var(--bdr2);background:var(--s2);color:var(--gr);border-radius:8px;padding:8px;font-weight:700;font-size:12px}
.sh-tabs button.on{background:var(--goldbtn);color:#16130a;border-color:var(--gold)}
.sh-body{padding:12px 14px}
.ev{display:grid;grid-template-columns:1fr 46px 1fr;align-items:center;gap:6px;padding:7px 0;border-bottom:1px solid var(--bdr);font-size:13px}
.ev .min{text-align:center;font-family:'JetBrains Mono';font-size:12px;color:var(--gold);background:var(--s2);border-radius:6px;padding:2px 0}
.ev .h{text-align:right}
.ev small{display:block;color:var(--gr);font-size:11px}
.ev.subst{opacity:.75;font-size:12px}
.ev-sum{display:flex;justify-content:space-around;font-size:12px;color:var(--gr);margin-bottom:8px}
.tst{display:grid;grid-template-columns:60px 1fr 60px;gap:8px;align-items:center;padding:6px 0;border-bottom:1px solid var(--bdr);font-size:13px}
.tst span{text-align:center;color:var(--gr);font-size:12px}
.tst b{font-family:'JetBrains Mono';text-align:center}
.lsc{width:100%;border-collapse:collapse;margin-bottom:12px}
.lsc th,.lsc td{padding:6px 4px;text-align:center;border-bottom:1px solid var(--bdr);font-family:'JetBrains Mono';font-size:12px}
.lsc th{color:var(--gr);font-size:10px}
.lsc td.l{text-align:left;font-family:'Inter';font-weight:700}
.lsc td.tot{color:var(--gold2);font-weight:700}
.ldr{display:grid;grid-template-columns:1fr 1fr;gap:10px}
.ldr h4,.sbox h4{font-size:11px;letter-spacing:1px;text-transform:uppercase;color:var(--gr);margin-bottom:5px}
.ldr div div{font-size:12px;padding:4px 0;border-bottom:1px solid var(--bdr)}
.ldr small{color:var(--gr);display:block;font-size:10px}
.ply{padding:7px 0;border-bottom:1px solid var(--bdr);font-size:12.5px}
.ply small{color:var(--gold);font-family:'JetBrains Mono';margin-right:6px}

/* pitch */
.form-head{display:flex;justify-content:space-between;font-size:12px;color:var(--gr);margin:4px 2px 8px;gap:10px}
.form-head b{color:var(--w);font-family:'JetBrains Mono'}
.pitch{position:relative;background:repeating-linear-gradient(180deg,#145a32 0 44px,#176638 44px 88px);border-radius:12px;padding:8px 4px;border:2px solid rgba(255,255,255,.35);overflow:hidden}
.pitch::before{content:'';position:absolute;left:0;right:0;top:50%;border-top:2px solid rgba(255,255,255,.35)}
.pitch::after{content:'';position:absolute;left:50%;top:50%;width:80px;height:80px;margin:-40px 0 0 -40px;border:2px solid rgba(255,255,255,.35);border-radius:50%}
.half{display:flex;flex-direction:column;gap:6px;padding:6px 0;position:relative;z-index:1}
.half.away{padding-top:12px}
.prow{display:flex;justify-content:space-around;align-items:flex-start}
.pl{display:flex;flex-direction:column;align-items:center;width:64px;text-align:center}
.pl .n{width:30px;height:30px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-weight:800;font-size:12px;border:2px solid #fff}
.half.home .pl .n{background:#e8ecf5;color:#111}
.half.away .pl .n{background:#1b1f2c;color:#fff}
.pl .nm{font-size:10px;font-weight:700;color:#fff;margin-top:2px;text-shadow:0 1px 2px #000;line-height:1.15;max-width:64px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.pl .tags{font-size:10px;line-height:1;margin-top:1px;min-height:10px}
.subs{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:12px}
.subs h4{font-size:11px;letter-spacing:1px;text-transform:uppercase;color:var(--gr);margin-bottom:5px}
.subs div div{font-size:12px;padding:3px 0;border-bottom:1px solid var(--bdr)}
.subs .num{display:inline-block;width:22px;font-family:'JetBrains Mono';color:var(--gr)}

/* settings */
.set-h{font-size:11px;font-weight:800;letter-spacing:1.2px;text-transform:uppercase;color:var(--gr);margin:16px 0 8px}
.set-h:first-child{margin-top:4px}
.myteams{display:flex;flex-wrap:wrap;gap:6px}
.myteams .fv{padding-right:4px}
.myteams .fv button{border:0;background:var(--s3);color:var(--gr);width:22px;height:22px;border-radius:50%;font-size:11px;margin-left:2px}
.srch{width:100%;background:var(--s2);border:1px solid var(--bdr2);border-radius:10px;color:var(--w);padding:10px 12px;font-size:16px;margin:8px 0}
.trow{display:flex;align-items:center;gap:10px;padding:8px 2px;border-bottom:1px solid var(--bdr)}
.trow img{width:24px;height:24px;object-fit:contain}
.trow span{flex:1;font-weight:600;font-size:13px}
.trow small{color:var(--dim);font-size:11px;font-weight:500}
.trow button{border:1px solid var(--bdr2);background:var(--s2);color:var(--gr);border-radius:8px;min-width:44px;min-height:34px;font-size:16px}
.trow button.on{background:var(--gbg);color:var(--gold2);border-color:var(--gbdr)}
.setchips{display:flex;flex-wrap:wrap;gap:6px}
.setchips button{border:1px solid var(--bdr);background:transparent;color:var(--gr);font-weight:600;font-size:11.5px;padding:5px 10px;border-radius:8px}
.setchips button.on{background:var(--gbg);color:var(--gold2);border-color:var(--gbdr)}

/* bottom nav */
.nav{position:fixed;left:0;right:0;bottom:0;z-index:40;height:calc(var(--nav-h) + env(safe-area-inset-bottom));padding-bottom:env(safe-area-inset-bottom);background:var(--bar);border-top:1px solid var(--bdr2);display:flex}
body.today .nav{display:none}
.nav button{flex:1;background:none;border:0;color:var(--dim);display:flex;flex-direction:column;align-items:center;justify-content:center;gap:3px;font-size:10px;font-weight:700;letter-spacing:.5px;text-transform:uppercase}
.nav button.on{color:var(--gold)}
.nav .ico{font-size:20px;line-height:1}
</style>
</head>
<body class="today">

<header class="hdr">
  <div class="top">
    <div class="theme" role="group" aria-label="Colour theme">
      <button data-act="theme" data-v="light" aria-label="Light mode" title="Light mode">☀️</button>
      <button data-act="theme" data-v="dark" aria-label="Dark mode" title="Dark mode">🌙</button>
    </div>
    <div class="who-r">
      <button class="setbtn" data-act="settings" aria-label="Settings: my teams and display">
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><line x1="4" y1="6" x2="20" y2="6"/><line x1="4" y1="12" x2="20" y2="12"/><line x1="4" y1="18" x2="20" y2="18"/><circle cx="9" cy="6" r="2.2" fill="currentColor"/><circle cx="15" cy="12" r="2.2" fill="currentColor"/><circle cx="7" cy="18" r="2.2" fill="currentColor"/></svg>
        Settings</button>
    </div>
  </div>
  <h1>Football Live</h1>
  <div class="hdr-sub" id="hdrSub">All times Dubai (GMT+4)</div>
</header>
<div class="navgrid">
  <nav class="secs" id="secs"></nav>
  <nav class="chips" id="chips"></nav>
  <span class="sig">Developed by: <b>Eng. Mickey</b></span>
</div>
<div class="hline"></div>

<div class="sbar">
  <button class="rf" id="rf"><span class="ic">↻</span> Refresh</button>
  <span class="stxt" id="stxt">Loading…</span>
  <span class="clk" id="clk"></span>
</div>

<main class="wrap">
  <section class="panel on" id="p-today"></section>
  <section class="panel" id="p-matches"></section>
  <section class="panel" id="p-table"></section>
  <section class="panel" id="p-stats"></section>
</main>

<div class="sheet-bg" id="sheetBg"></div>
<div class="sheet" id="sheet" role="dialog" aria-modal="true"></div>
<div class="sheet" id="settings" role="dialog" aria-modal="true"></div>

<nav class="nav" id="nav">
  <button class="on" data-p="matches"><span class="ico">📅</span><span>Matches</span></button>
  <button data-p="table"><span class="ico">🏆</span><span id="navTable">Table</span></button>
  <button data-p="stats"><span class="ico">📊</span><span id="navStats">Stats</span></button>
</nav>

<script>
/* ── SETTINGS ──────────────────────────────────────────────
   Paste your Cloudflare Worker address here (see SETUP.md). */
const WORKER_URL = 'https://fl-hub.footballive.workers.dev';
const TRACK_EVERY = 5 * 60;   // seconds between updates of tracked matches
const DEFAULT_TEAMS = [       // used until each person picks their own teams in ⚙︎
  { name: 'Egypt', sport: 'soccer' }, { name: 'Al Ahly', sport: 'soccer' }, { name: 'Zamalek', sport: 'soccer' },
  { name: 'Liverpool', sport: 'soccer' }, { name: 'Manchester City', sport: 'soccer' }, { name: 'Real Madrid', sport: 'soccer' },
  { name: 'Barcelona', sport: 'soccer' }, { name: 'Trabzonspor', sport: 'soccer' },
];
/* ────────────────────────────────────────────────────────── */

const ZONES = [
  { tz: 'Asia/Dubai', label: 'Dubai', flag: '🇦🇪' },
  { tz: 'Africa/Cairo', label: 'Cairo', flag: '🇪🇬' },
  { tz: 'America/New_York', label: 'New York (US Eastern)', short: 'New York', flag: '🇺🇸' },
];
/* first visit: use the phone's own zone if it is one of these, otherwise Dubai */
const deviceTz = (() => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone; } catch { return ''; } })();
let TZ = (() => { let t = null; try { t = JSON.parse(localStorage.getItem('fl3_tz')); } catch {} return ZONES.some(z => z.tz === t) ? t : ZONES.some(z => z.tz === deviceTz) ? deviceTz : 'Asia/Dubai'; })();
/* current offset and abbreviation, with daylight saving taken from the official zone rules */
function zoneInfo(tz, at = new Date()){
  const part = (opts) => { try { return new Intl.DateTimeFormat('en-US', { timeZone: tz, ...opts }).formatToParts(at).find(p => p.type === 'timeZoneName')?.value || ''; } catch { return ''; } };
  const off = part({ timeZoneName: 'shortOffset' }) || 'GMT';
  const abbr = tz === 'America/New_York' ? part({ timeZoneName: 'short' }) : '';
  return { off, abbr: /^[A-Z]{3,4}$/.test(abbr) ? abbr : '' };
}
function zoneText(tz){ const z = ZONES.find(x => x.tz === tz), i = zoneInfo(tz); return `${z.short || z.label} (${i.abbr ? i.abbr + ', ' : ''}${i.off})`; }
const SECTIONS = [
  { id: 'today',  name: 'Today' },
  { id: 'leagues', name: '🏟️ Leagues', comps: ['pl', 'laliga', 'tsl'] },
  { id: 'cups',   name: '🏆 Club Cups', comps: ['ucl', 'cafcl', 'cafcc'] },
  { id: 'intl',   name: '🌐 National Teams', comps: ['wc', 'wcq', 'afcon', 'afconq', 'euro', 'euroq', 'unl', 'intl'] },
  { id: 'us',     name: '🇺🇸 US Sports', comps: ['nfl', 'nba'] },
];
const C = {
  pl:     { icon: '🏴󠁧󠁢󠁥󠁮󠁧󠁿', name: 'Premier League', sport: 'soccer', kind: 'league', clinch: true },
  laliga: { icon: '🇪🇸', name: 'LaLiga', sport: 'soccer', kind: 'league', clinch: true },
  tsl:    { icon: '🇹🇷', name: 'Trendyol Süper Lig', sport: 'soccer', kind: 'league', clinch: true },
  ucl:    { icon: '⭐', name: 'Champions League', sport: 'soccer', kind: 'cup' },
  cafcl:  { icon: '🥇', name: 'CAF Champions League', sport: 'soccer', kind: 'cup' },
  cafcc:  { icon: '🥈', name: 'CAF Confederation Cup', sport: 'soccer', kind: 'cup' },
  wc:     { icon: '🏆', name: 'World Cup', sport: 'soccer', kind: 'intl' },
  wcq:    { icon: '🎟️', name: 'WC Qualifiers · Africa', sport: 'soccer', kind: 'intl' },
  afcon:  { icon: '🌍', name: 'AFCON', sport: 'soccer', kind: 'intl' },
  afconq: { icon: '🎟️', name: 'AFCON Qualifiers', sport: 'soccer', kind: 'intl' },
  euro:   { icon: '🇪🇺', name: 'EURO', sport: 'soccer', kind: 'intl' },
  euroq:  { icon: '🎟️', name: 'EURO Qualifiers', sport: 'soccer', kind: 'intl' },
  unl:    { icon: '🛡️', name: 'UEFA Nations League', short: 'Nations League', sport: 'soccer', kind: 'intl' },
  intl:   { icon: '🤝', name: 'Friendlies', sport: 'soccer', kind: 'intl' },
  nfl:    { icon: '🏈', name: 'NFL', sport: 'nfl', kind: 'us' },
  nba:    { icon: '🏀', name: 'NBA', sport: 'nba', kind: 'us' },
};
const ORDER = SECTIONS.flatMap(s => s.comps || []);
const LIVE = new Set(['1H','HT','2H','ET','BT','P','SUSP','LIVE']);
const DONE = new Set(['FT','AET','PEN']);
const OFF  = new Set(['PST','CANC','ABD']);

/* saved settings (wrapped: storage can be blocked in private windows) */
const store = {
  get(k, d){ try { const v = localStorage.getItem(k); return v ? JSON.parse(v) : d; } catch { return d; } },
  set(k, v){ try { localStorage.setItem(k, JSON.stringify(v)); } catch {} },
};

/* state */
let section = store.get('fl3_section', 'today');
if (!SECTIONS.some(s => s.id === section)) section = 'today';
const lastComp = store.get('fl3_comp', {});            // last competition chosen in each section
let panel = 'matches';
let favs = store.get('fl3_favs', null);
if (!Array.isArray(favs)) favs = DEFAULT_TEAMS.map(t => ({ ...t, id: null, logo: '' }));
let homeMode = store.get('fl3_mode', 'mine');          // 'mine' | 'all'
let homeSport = store.get('fl3_sport', 'all');         // 'all' | 'soccer' | 'nfl' | 'nba'
if (!['all', 'soccer', 'nfl', 'nba'].includes(homeSport)) homeSport = 'all';
let homeDate = null;                                   // 'YYYY-MM-DD' (Dubai); null = today
let tracked = store.get('fl3_tracked', []);            // [{ key: 'pl:123', comp, id }]
if (!Array.isArray(tracked)) tracked = [];

const WIN = {};     // WIN[comp]   = { list, at, error }      (Today window)
const DAY = {};     // DAY['comp|YYYY-MM-DD'] = { list, at, error }   (a chosen date)
const FIX = {};     // FIX[comp]   = { list, at, warning, error }
const TAB = {};     // TAB[comp]   = { groups, error }
const STA = {};     // STA[comp]   = { cats, error }
const MATCH = {};   // MATCH[key]  = { m, at, next, error }
const TEAMS = {};   // TEAMS[comp] = { list, error }
const roundSel = {};
let sheetKey = null, sheetTab = null, setOpen = false, setComp = 'pl', setQuery = '';
let trackTimer = null, nextTrackAt = null, busy = false;

/* ── theme ── */
let themePref = store.get('fl3_theme', 'auto');
if (!['auto', 'light', 'dark'].includes(themePref)) themePref = 'auto';
const mq = window.matchMedia ? matchMedia('(prefers-color-scheme: light)') : null;
function applyTheme(){
  const light = themePref === 'light' || (themePref === 'auto' && mq && mq.matches);
  document.documentElement.setAttribute('data-theme', light ? 'light' : 'dark');
  document.querySelector('meta[name=theme-color]').setAttribute('content', light ? '#ffffff' : '#08090e');
  document.querySelectorAll('.theme button').forEach(b => b.classList.toggle('on', b.dataset.v === (light ? 'light' : 'dark')));
}
if (mq) (mq.addEventListener ? mq.addEventListener('change', applyTheme) : mq.addListener(applyTheme));

/* ── helpers ── */
const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
const tTime = d => d.toLocaleTimeString('en-GB', {timeZone:TZ, hour:'2-digit', minute:'2-digit'});
const tDay  = d => d.toLocaleDateString('en-GB', {timeZone:TZ, weekday:'long', day:'numeric', month:'long'});
const tShort= d => d.toLocaleDateString('en-GB', {timeZone:TZ, weekday:'short', day:'numeric', month:'short'});
const dKey  = d => d.toLocaleDateString('en-CA', {timeZone:TZ});
const when  = m => new Date(m.ts * 1000);
const keyOf = m => `${m.comp}:${m.id}`;
const sport = comp => C[comp]?.sport || 'soccer';
const isUS  = comp => C[comp]?.kind === 'us';
const cname = comp => C[comp]?.short || C[comp]?.name || comp;
const cfull = comp => `${C[comp]?.icon ? C[comp].icon + ' ' : ''}${C[comp]?.name || comp}`;
const lastName = n => { const p = String(n || '').trim().split(/\s+/); return p.length > 1 ? p.slice(1).join(' ') : p[0] || ''; };
const mmss = s => `${Math.floor(s / 60)}:${String(Math.max(0, s % 60)).padStart(2, '0')}`;
const isTracked = k => tracked.some(t => t.key === k);
const trackable = m => !DONE.has(m.st.s) && !OFF.has(m.st.s);
const secOf = comp => SECTIONS.find(s => (s.comps || []).includes(comp));
const todayKey = () => dKey(new Date());
const viewDate = () => homeDate || todayKey();
const isToday = () => viewDate() === todayKey();
function shiftDate(s, n){ const d = new Date(s + 'T12:00:00Z'); d.setUTCDate(d.getUTCDate() + n); return d.toISOString().slice(0, 10); }
const dateLabel = s => tDay(new Date(s + 'T12:00:00Z'));   // noon UTC is the same calendar day in all three zones
const homeComps = () => ORDER.filter(c => homeSport === 'all' || sport(c) === homeSport);
const dayData = (c, d) => DAY[c + '|' + d + '|' + TZ];
function currentComp(){ const s = SECTIONS.find(x => x.id === section); if (!s || !s.comps) return null; const c = lastComp[section]; return s.comps.includes(c) ? c : s.comps[0]; }

/* favourite teams: matched by id when chosen in ⚙︎, otherwise by name */
const STOP = new Set(['fc','sc','cf','afc','club','al','el','the','sk','as','ac','cd','sad']);
function norm(n){
  return String(n || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase()
    .replace(/[^a-z0-9 ]+/g, ' ').split(/\s+/).filter(w => w && !STOP.has(w)).join(' ');
}
function isFavTeam(t, sp){
  if (!t) return false;
  const n = norm(t.name);
  return favs.some(f => f.sport === sp && ((f.id != null && f.id === t.id) || norm(f.name) === n));
}
const isFavMatch = m => isFavTeam(m.h, sport(m.comp)) || isFavTeam(m.a, sport(m.comp));
function saveFavs(){ store.set('fl3_favs', favs); }

/* freshest copy of a match: the detailed /match answer if it is newer than the list */
function fresh(m){
  const d = MATCH[keyOf(m)];
  const listAt = Math.max(FIX[m.comp]?.at || 0, WIN[m.comp]?.at || 0);
  return d && d.m && d.at >= listAt ? { ...m, ...d.m, comp: m.comp } : m;
}
function allKnown(){
  const map = new Map();
  ORDER.forEach(c => { (FIX[c]?.list || []).forEach(m => map.set(keyOf(m), m)); (WIN[c]?.list || []).forEach(m => map.set(keyOf(m), m)); });
  Object.values(DAY).forEach(d => (d.list || []).forEach(m => { if (!map.has(keyOf(m))) map.set(keyOf(m), m); }));
  return map;
}
function findMatch(key){ return MATCH[key]?.m || allKnown().get(key) || null; }

function liveLabel(m){
  const s = m.st.s;
  if (isUS(m.comp)) return s === 'HT' ? 'Halftime' : (m.st.detail || 'Live');
  return s === 'HT' ? 'Half time' : s === 'BT' ? 'Break' : s === 'P' ? 'Penalties' : s === 'SUSP' ? 'Suspended' : (m.st.clock || 'Live');
}
function finalLabel(m){
  if (isUS(m.comp)) return m.st.detail || 'Final';
  return m.st.s === 'PEN' ? 'After pens' : m.st.s === 'AET' ? 'After ET' : 'Full time';
}

/* ── match card ── */
function card(raw, o = {}){
  const m = fresh(raw), s = m.st.s, live = LIVE.has(s), done = DONE.has(s), off = OFF.has(s);
  const k = keyOf(m), on = isTracked(k), us = isUS(m.comp), sp = sport(m.comp);
  let mid, pill;
  if (live){ mid = `<div class="sc">${m.h.score ?? 0} – ${m.a.score ?? 0}</div>`; pill = `<span class="st lv"><i></i>${esc(liveLabel(m))}</span>`; }
  else if (done){ mid = `<div class="sc">${m.h.score ?? 0} – ${m.a.score ?? 0}</div>`; pill = `<span class="st ft">${esc(finalLabel(m))}</span>`; }
  else if (off){ mid = `<div class="ko">${tTime(when(m))}</div>`; pill = `<span class="st pp">${s === 'PST' ? 'Postponed' : s === 'CANC' ? 'Cancelled' : 'Abandoned'}</span>`; }
  else { mid = `<div class="ko">${s === 'TBD' ? 'TBD' : tTime(when(m))}</div>`; pill = `<span class="st ns">${us ? 'Tip-off' : 'Kick-off'}</span>`; if (m.comp === 'nfl') pill = `<span class="st ns">Kick-off</span>`; }
  const team = (t, side) => `<div class="tm ${side} ${t.winner ? 'win' : ''}"><img src="${esc(t.logo)}" alt="" loading="lazy" onerror="this.style.visibility='hidden'">
    <div class="nm"><span>${esc(us ? (t.short || t.name) : t.name)}${isFavTeam(t, sp) ? '<em class="star">★</em>' : ''}</span>${t.rec ? `<small>${esc(t.rec)}</small>` : ''}</div></div>`;
  let info = `${o.comp ? `<b>${esc((C[m.comp]?.icon || '') + ' ' + cname(m.comp))}</b> · ` : ''}${tShort(when(m))} · ${tTime(when(m))}${m.note && !o.comp ? ' · ' + esc(m.note) : ''}${m.venue && !o.comp ? ' · ' + esc(m.venue) : ''}`;
  if (o.tracking) info = `<b>${esc(cname(m.comp))}</b> · ${done ? 'Final score, tracking stopped' : `updates every 5 min · next in <span class="cd" data-cd>–</span>`}`;
  const trackBtn = (trackable(m) || on) && !o.tracking ? `<button class="btn trk ${on ? 'on' : ''}" data-act="track">${on ? '★ Tracking' : '☆ Track'}</button>` : '';
  const removeBtn = o.tracking ? `<button class="btn x" data-act="untrack" aria-label="Stop tracking">✕</button>` : '';
  return `<div class="m ${live ? 'live' : done ? 'done' : ''} ${on ? 'tracked' : ''}" data-key="${esc(k)}">
    ${team(m.h, 'home')}<div class="mid">${mid}${pill}</div>${team(m.a, 'away')}
    <div class="acts"><span class="info">${info}</span>${trackBtn}<button class="btn" data-act="details">Details ›</button>${removeBtn}</div></div>`;
}
function byDay(list, o){
  let out = '', last = '';
  list.forEach(m => { const k = dKey(when(m)); if (k !== last){ out += `<div class="day">${tDay(when(m))}</div>`; last = k; } out += card(m, o); });
  return out;
}
function byComp(list){
  let out = '';
  ORDER.forEach(c => { const l = list.filter(m => m.comp === c); if (l.length) out += `<div class="sub">${esc(cfull(c))}</div>` + l.map(m => card(m)).join(''); });
  return out;
}

/* ── TODAY ── */
const SPORTS = [['all', 'All'], ['soccer', '⚽ Football'], ['nfl', '🏈 NFL'], ['nba', '🏀 NBA']];
function homeControls(mine){
  const d = viewDate();
  return `<div class="dbar">
      <button data-act="day" data-step="-1" aria-label="Previous day">‹</button>
      <input type="date" id="dpick" value="${d}" aria-label="Choose a date">
      <button data-act="day" data-step="1" aria-label="Next day">›</button>
      ${isToday() ? '' : '<button class="tdy" data-act="dtoday">Today</button>'}</div>
    <div class="mode">${SPORTS.map(([v, l]) => `<button data-act="sport" data-v="${v}" class="${homeSport === v ? 'on' : ''}">${l}</button>`).join('')}</div>
    <div class="mode">
      <button data-act="mode" data-v="mine" class="${mine ? 'on' : ''}">★ My teams</button>
      <button data-act="mode" data-v="all" class="${!mine ? 'on' : ''}">All matches</button></div>`;
}
const flat = l => l.map(m => card(m, { comp: true })).join('');
function failedNote(comps){
  return comps.length ? `<div class="empty" style="font-size:11px">Couldn't load: ${comps.map(c => esc(C[c].name)).join(', ')}. Try Refresh.</div>` : '';
}
function renderToday(){
  const mine = homeMode === 'mine' && favs.length > 0;
  const comps = homeComps();
  let h = homeControls(mine);
  const filterMine = m => !mine || isFavMatch(m);

  if (!isToday()){
    const d = viewDate(), loaded = comps.filter(c => dayData(c, d));
    h += `<div class="sec">${esc(dateLabel(d))}</div>`;
    if (!loaded.length){ $('p-today').innerHTML = h + `<div class="empty">Loading matches…</div>`; return; }
    const list = [...new Map(loaded.flatMap(c => dayData(c, d).list || []).map(m => [keyOf(m), m])).values()].map(fresh)
      .filter(filterMine).sort((a, b) => a.ts - b.ts);
    const live = list.filter(m => LIVE.has(m.st.s));
    if (live.length) h += `<div class="sub">🔴 Live now</div>` + (mine ? flat(live) : byComp(live));
    const rest = list.filter(m => !LIVE.has(m.st.s));
    h += rest.length ? (mine ? flat(rest) : byComp(rest))
      : live.length ? '' : `<div class="empty">${mine ? 'None of your teams play on this day.' : 'No matches on this day in these competitions.'}</div>`;
    if (loaded.length < comps.length) h += `<div class="empty" style="font-size:11px">Still loading some competitions…</div>`;
    h += failedNote(loaded.filter(c => dayData(c, d).error));
    $('p-today').innerHTML = h;
    return;
  }

  const trk = tracked.filter(t => homeSport === 'all' || sport(t.comp) === homeSport);
  if (trk.length){
    h += `<div class="sec">★ Tracking <small>updates every 5 minutes while this page is open</small></div>` + trk.map(t => {
      const m = findMatch(t.key);
      return m ? card({ ...m, comp: t.comp }, { tracking: true }) : `<div class="m" data-key="${esc(t.key)}"><div class="acts" style="border:0;padding:0;margin:0"><span class="info">Loading tracked match…</span><button class="btn x" data-act="untrack">✕</button></div></div>`;
    }).join('');
  }
  const loaded = comps.filter(c => WIN[c]);
  if (!loaded.length){ $('p-today').innerHTML = h + `<div class="empty">Loading today's matches…</div>`; return; }

  const all = [...new Map(loaded.flatMap(c => WIN[c].list || []).map(m => [keyOf(m), m])).values()].map(fresh)
    .filter(m => !isTracked(keyOf(m)) && filterMine(m));
  const tk = todayKey(), yKey = shiftDate(tk, -1);
  const live = all.filter(m => LIVE.has(m.st.s));
  const today = all.filter(m => !LIVE.has(m.st.s) && dKey(when(m)) === tk).sort((a, b) => a.ts - b.ts);
  if (live.length) h += `<div class="sec">🔴 Live now <small>score as of your last refresh · ☆ Track for 5-minute updates</small></div>` + (mine ? flat(live) : byComp(live));
  h += `<div class="sec">Today <small>${tDay(new Date())}</small></div>`;
  h += today.length ? (mine ? flat(today) : byComp(today))
    : `<div class="empty">${mine ? 'None of your teams play today.' : 'No matches today in these competitions.'}</div>`;

  if (mine){
    const up = all.filter(m => trackable(m) && !LIVE.has(m.st.s) && dKey(when(m)) > tk).sort((a, b) => a.ts - b.ts);
    const recent = all.filter(m => DONE.has(m.st.s) && dKey(when(m)) < tk).sort((a, b) => b.ts - a.ts);
    h += `<div class="sec">Coming up <small>next 6 days</small></div>` + (up.length ? byDay(up, { comp: true }) : `<div class="empty">No matches for your teams in the next 6 days.</div>`);
    if (recent.length) h += `<div class="sec">Latest results <small>last 2 days</small></div>` + flat(recent);
  } else {
    const yday = all.filter(m => DONE.has(m.st.s) && dKey(when(m)) === yKey).sort((a, b) => a.ts - b.ts);
    if (yday.length) h += `<div class="sec">Yesterday's results</div>` + byComp(yday);
  }
  h += failedNote(loaded.filter(c => WIN[c].error));
  $('p-today').innerHTML = h;
}

/* ── MATCHES (by round) ── */
function rounds(list){
  const first = {};
  list.forEach(m => { if (OFF.has(m.st.s)) return; if (!(m.round in first) || m.ts < first[m.round]) first[m.round] = m.ts; });
  list.forEach(m => { if (!(m.round in first)) first[m.round] = m.ts; });
  return Object.keys(first).sort((a, b) => first[a] - first[b]);
}
function currentRound(list){
  const cut = Date.now() / 1000 - 3 * 3600;
  const next = list.filter(m => trackable(m) && m.ts >= cut).sort((a, b) => a.ts - b.ts)[0];
  const rs = rounds(list);
  return next ? next.round : rs[rs.length - 1];
}
function renderMatches(){
  const comp = currentComp(), d = FIX[comp];
  if (!d){ $('p-matches').innerHTML = `<div class="empty">Loading ${esc(C[comp].name)}…</div>`; return; }
  if (!d.list.length){
    $('p-matches').innerHTML = d.error ? errorBox(d.error)
      : `<div class="msg"><h3>No matches right now</h3>${C[comp].kind === 'intl' ? 'Nothing scheduled from five months ago to six months ahead. National-team competitions are played in windows; this tab fills up when the next one starts.' : 'No fixtures published yet for this season.'}</div>`;
    return;
  }
  const list = d.list.map(fresh), rs = rounds(list), cur = currentRound(list);
  if (!rs.includes(roundSel[comp])) roundSel[comp] = cur;
  const r = roundSel[comp], i = rs.indexOf(r);
  const items = list.filter(m => m.round === r).sort((a, b) => a.ts - b.ts);
  $('p-matches').innerHTML = `
    <div class="mw">
      <button data-act="round" data-step="-1" ${i <= 0 ? 'disabled' : ''} aria-label="Previous">‹</button>
      <div><b>${esc(r)}</b><small>${r === cur ? 'Current' : i < rs.indexOf(cur) ? 'Played' : 'Upcoming'} · ${i + 1} of ${rs.length}</small></div>
      <button data-act="round" data-step="1" ${i >= rs.length - 1 ? 'disabled' : ''} aria-label="Next">›</button>
    </div>` + byDay(items) + (d.warning ? `<div class="empty" style="font-size:11px">Showing saved data: ${esc(d.warning)}</div>` : '');
}

/* ── TABLES ── */
function formOf(comp, teamId){
  return (FIX[comp]?.list || []).filter(m => DONE.has(m.st.s) && (m.h.id === teamId || m.a.id === teamId)).sort((a, b) => a.ts - b.ts).slice(-5)
    .map(m => { const home = m.h.id === teamId, us = home ? m.h.score : m.a.score, th = home ? m.a.score : m.h.score; return us > th ? 'W' : us < th ? 'L' : 'D'; }).join('');
}
/* Which places are mathematically certain (single-table leagues).
   A team has secured a top-k place when fewer than k other teams can still reach its points.
   A team is relegated when enough teams already have more points than its maximum. Ties count as "not yet". */
function clinch(rows){
  const n = rows.length, games = (n - 1) * 2;
  const R = rows.map(r => ({ r, pts: r.v.points ?? 0, max: (r.v.points ?? 0) + 3 * Math.max(0, games - (r.v.gamesPlayed ?? 0)) }));
  const zones = []; let pos = 0;
  rows.forEach((r, i) => { const d = r.note?.desc || ''; if (!d) return; const z = zones[zones.length - 1]; if (z && z.desc === d && z.end === i) z.end = i + 1; else zones.push({ desc: d, color: r.note.color, start: i + 1, end: i + 1 }); });
  const out = new Map();
  R.forEach(t => {
    for (const z of zones){
      const releg = /releg|descen|playoff.*down/i.test(z.desc);
      if (!releg && z.start <= n / 2 && R.filter(o => o !== t && o.max >= t.pts).length <= z.end - 1){ out.set(t.r.team.id, [z.desc + ' ✓', z.color]); break; }
      if (releg && R.filter(o => o !== t && o.pts > t.max).length >= z.start - 1){ out.set(t.r.team.id, ['Relegated', z.color]); break; }
    }
  });
  return out;
}
const col = c => c ? (String(c).startsWith('#') ? c : '#' + c) : '';
function renderTable(){
  const comp = currentComp(), d = TAB[comp], us = isUS(comp), sp = sport(comp);
  if (!d){ $('p-table').innerHTML = `<div class="empty">Loading…</div>`; return; }
  if (!d.groups.length){ $('p-table').innerHTML = d.error ? errorBox(d.error) : `<div class="msg"><h3>No table right now</h3>The table appears once this competition's current edition has started.</div>`; return; }
  const playing = new Set((FIX[comp]?.list || []).map(fresh).filter(m => LIVE.has(m.st.s)).flatMap(m => [m.h.id, m.a.id]));
  const single = d.groups.length === 1;
  let h = playing.size ? `<div class="note">🔴 Matches are in progress. Tap Refresh for the latest table.</div>` : '';
  const notes = new Map();
  d.groups.forEach(g => {
    const status = (!us && single && C[comp].clinch && g.rows.length >= 10) ? clinch(g.rows) : new Map();
    if (!single || g.name) h += single ? '' : `<div class="gname">${esc(g.name)}</div>`;
    const hasT = us && g.rows.some(r => (r.v.ties ?? 0) > 0);
    const head = us
      ? `<tr><th>#</th><th class="l">Team</th><th>W</th><th>L</th>${hasT ? '<th>T</th>' : ''}<th>Pct</th><th>GB</th><th class="hide-sm">Strk</th></tr>`
      : `<tr><th>#</th><th class="l">Club</th><th>P</th><th class="hide-sm">W</th><th class="hide-sm">D</th><th class="hide-sm">L</th><th>GD</th><th>Pts</th>${C[comp].kind === 'league' ? '<th class="hide-sm">Form</th>' : ''}</tr>`;
    const rows = g.rows.map(r => {
      if (r.note?.desc) notes.set(r.note.desc, col(r.note.color));
      const s = status.get(r.team.id), me = isFavTeam(r.team, sp);
      const badge = s ? ` <span class="bdg" style="background:${esc(col(s[1]) || 'var(--gold)')}">${esc(s[0])}</span>` : '';
      const cls = `${me ? 'me' : ''} ${playing.has(r.team.id) ? 'playing' : ''}`;
      const pos = `<td class="pos" style="${r.note?.color ? `border-left-color:${esc(col(r.note.color))}` : ''}">${r.rank}</td>`;
      const name = `<td class="l"><div class="c"><img src="${esc(r.team.logo)}" alt="" loading="lazy">${esc(us ? (r.team.short || r.team.name) : r.team.name)}${me ? ' ★' : ''}${playing.has(r.team.id) ? ' 🔴' : ''}${badge}</div></td>`;
      if (us) return `<tr class="${cls}">${pos}${name}<td>${esc(r.d.wins ?? '')}</td><td>${esc(r.d.losses ?? '')}</td>${hasT ? `<td>${esc(r.d.ties ?? '0')}</td>` : ''}<td class="pts">${esc(r.d.winPercent ?? '')}</td><td>${esc(r.d.gamesBehind ?? '')}</td><td class="hide-sm">${esc(r.d.streak ?? '')}</td></tr>`;
      const gd = r.v.pointDifferential ?? ((r.v.pointsFor ?? 0) - (r.v.pointsAgainst ?? 0));
      const form = C[comp].kind === 'league' ? `<td class="hide-sm"><div class="form">${[...formOf(comp, r.team.id)].map(c => `<i class="${c}">${c}</i>`).join('')}</div></td>` : '';
      return `<tr class="${cls}">${pos}${name}<td>${r.v.gamesPlayed ?? 0}</td><td class="hide-sm">${r.v.wins ?? 0}</td><td class="hide-sm">${r.v.ties ?? r.v.draws ?? 0}</td><td class="hide-sm">${r.v.losses ?? 0}</td><td>${gd > 0 ? '+' : ''}${gd}</td><td class="pts">${r.v.points ?? 0}</td>${form}</tr>`;
    }).join('');
    h += `<div class="tw"><table class="tbl"><thead>${head}</thead><tbody>${rows}</tbody></table></div>`;
  });
  if (notes.size) h += `<div class="legend">${[...notes].map(([d, c]) => `<span style="--c:${esc(c || 'var(--gr)')}">${esc(d)}</span>`).join('')}</div>`;
  if (!us && single && C[comp].clinch) h += `<div class="empty" style="font-size:11px">Badges (✓ / Relegated) appear once a place is mathematically certain, usually late in the season. ★ marks your teams.</div>`;
  $('p-table').innerHTML = h;
}

/* ── STATS ── */
function renderStats(){
  const comp = currentComp(), d = STA[comp], us = isUS(comp);
  if (!d){ $('p-stats').innerHTML = `<div class="empty">Loading…</div>`; return; }
  if (!d.cats.length){ $('p-stats').innerHTML = d.error ? errorBox(d.error) : `<div class="empty">No statistics yet for this competition.</div>`; return; }
  $('p-stats').innerHTML = d.cats.map(cat => {
    const rows = cat.leaders.slice(0, 15).map((l, i) => {
      const apps = /(?:Matches|Games|Apps|GP)\D*(\d+)/i.exec(l.display || '');
      const main = us ? (l.display || l.value) : (l.value ?? l.display);
      const extra = us ? '' : (apps ? `${apps[1]} apps` : /pen/.test(l.display || '') ? l.display : '');
      return `<tr><td class="pos">${i + 1}</td><td class="l"><div class="who">${l.player.photo ? `<img class="ph" src="${esc(l.player.photo)}" alt="" loading="lazy">` : ''}<div>${esc(l.player.name)}<small>${l.team.logo ? `<img src="${esc(l.team.logo)}" alt="">` : ''}${esc(l.team.name)}</small></div></div></td><td class="big">${esc(main)}</td><td class="hide-sm">${esc(extra)}</td></tr>`;
    }).join('');
    return `<div class="sec">${esc(cat.label)} <small>${esc(C[comp].name)}</small></div><div class="tw"><table class="tbl"><tbody>${rows}</tbody></table></div>`;
  }).join('');
}

function errorBox(e){
  return `<div class="msg err"><h3>No data from the score service</h3>${esc(e)}<br><br>Scores come from ESPN's public feed through the Cloudflare Worker. Try Refresh in a minute.</div>`;
}

/* ── layout ── */
function renderShell(){
  $('hdrSub').textContent = `All times ${zoneText(TZ)}`;
  const s = SECTIONS.find(x => x.id === section);
  const now = new Date();
  $('secs').innerHTML = SECTIONS.map(x => `<button data-act="section" data-v="${x.id}" class="${x.id === section ? 'on' : ''}">${x.id === 'today'
    ? `<span class="cal"><b>${now.toLocaleDateString('en-GB', {timeZone:TZ, month:'short'}).toUpperCase()}</b><i>${now.toLocaleDateString('en-GB', {timeZone:TZ, day:'numeric'})}</i></span>Today` : esc(x.name)}</button>`).join('');
  const comp = currentComp();
  $('chips').innerHTML = s.comps ? s.comps.map(c => `<button data-act="comp" data-v="${c}" class="${c === comp ? 'on' : ''}">${esc(cfull(c))}</button>`).join('') : '';
  document.body.classList.toggle('today', section === 'today');
  const vis = section === 'today' ? 'today' : panel;
  document.querySelectorAll('.panel').forEach(p => p.classList.toggle('on', p.id === 'p-' + vis));
  document.querySelectorAll('.nav button').forEach(b => b.classList.toggle('on', b.dataset.p === panel));
  if (comp){
    const k = C[comp].kind;
    $('navTable').textContent = k === 'us' ? 'Standings' : k === 'league' ? 'Table' : 'Groups';
    $('navStats').textContent = k === 'us' ? 'Leaders' : 'Scorers';
  }
  // keep the selected tab visible on narrow screens
  ['secs', 'chips'].forEach(id => { const on = $(id).querySelector('.on'); if (on) on.scrollIntoView({ block: 'nearest', inline: 'center' }); });
}
function renderAll(){
  renderShell();
  if (section === 'today') renderToday();
  else { renderMatches(); renderTable(); renderStats(); }
  if (sheetKey) renderSheet();
  tickCountdowns();
}

/* ── MATCH DETAILS ── */
function openSheet(key){
  sheetKey = key; sheetTab = null;
  $('sheet').classList.add('on'); $('sheetBg').classList.add('on'); document.body.classList.add('noscroll');
  $('sheet').scrollTop = 0;
  renderSheet();
  loadMatch(key).then(renderAll);
}
function closeSheets(){
  sheetKey = null; setOpen = false;
  $('sheet').classList.remove('on'); $('settings').classList.remove('on'); $('sheetBg').classList.remove('on'); document.body.classList.remove('noscroll');
}
function renderSheet(){
  const d = MATCH[sheetKey], [comp] = sheetKey.split(':');
  const m0 = d?.m || allKnown().get(sheetKey);
  if (!m0){ $('sheet').innerHTML = `<div class="sh-body">${d?.error ? esc(d.error) : 'Loading…'} <button class="btn x" data-act="close">✕</button></div>`; return; }
  const m = { ...m0, comp }, s = m.st.s, live = LIVE.has(s), done = DONE.has(s), on = isTracked(sheetKey), us = isUS(comp);
  const tabs = us ? [['box', 'Box score'], ...(comp === 'nfl' ? [['plays', 'Scoring']] : []), ['tstats', 'Team stats']]
                  : [['events', 'Goals & cards'], ['lineups', 'Line-ups'], ['tstats', 'Stats']];
  if (!tabs.some(t => t[0] === sheetTab)) sheetTab = tabs[0][0];
  const score = (live || done) ? `${m.h.score ?? 0} – ${m.a.score ?? 0}` : tTime(when(m));
  const status = live ? liveLabel(m) : done ? finalLabel(m) : OFF.has(s) ? 'Postponed' : (us ? 'Tip-off' : 'Kick-off');
  const updated = d?.m ? `Updated ${tTime(new Date(d.at))}` : 'Loading details…';
  const body = !d ? `<div class="empty">Loading details…</div>`
    : !d.m ? `<div class="msg err">${esc(d.error || 'No details')}</div>`
    : sheetTab === 'events' ? eventsHtml(m) : sheetTab === 'lineups' ? lineupsHtml(m) : sheetTab === 'box' ? boxHtml(m) : sheetTab === 'plays' ? playsHtml(m) : teamStatsHtml(m);
  $('sheet').innerHTML = `
    <div class="sh-top">
      <div class="sh-bar"><span class="ttl">${esc(cfull(comp))}${m.round ? ' · ' + esc(m.round) : ''}${m.note ? ' · ' + esc(m.note) : ''} · ${tShort(when(m))} · ${updated}</span>
        ${(trackable(m) || on) ? `<button class="btn trk ${on ? 'on' : ''}" data-act="track">${on ? '★ Tracking' : '☆ Track'}</button>` : ''}
        <button class="btn" data-act="refresh-match" aria-label="Update this match">↻</button>
        <button class="btn x" data-act="close" aria-label="Close">✕</button></div>
      <div class="sh-head">
        <div class="t"><img src="${esc(m.h.logo)}" alt="">${esc(m.h.name)}${m.h.rec ? `<small style="color:var(--dim)">${esc(m.h.rec)}</small>` : ''}</div>
        <div class="mid"><div class="${live || done ? 'sc' : 'ko'}">${score}</div><span class="st ${live ? 'lv' : done ? 'ft' : 'ns'}">${live ? '<i></i>' : ''}${esc(status)}</span></div>
        <div class="t"><img src="${esc(m.a.logo)}" alt="">${esc(m.a.name)}${m.a.rec ? `<small style="color:var(--dim)">${esc(m.a.rec)}</small>` : ''}</div>
      </div>
      <div class="sh-tabs">${tabs.map(([k, l]) => `<button data-act="stab" data-t="${k}" class="${sheetTab === k ? 'on' : ''}">${l}</button>`).join('')}</div>
    </div>
    <div class="sh-body">${body}${m.venue ? `<div class="empty" style="font-size:11px">📍 ${esc(m.venue)}</div>` : ''}</div>`;
}

const ICON = { goal: '⚽', pen: '⚽', og: '⚽', misspen: '❌', yc: '🟨', rc: '🟥', y2: '🟨🟥', sub: '⇄' };
const WHAT = { goal: 'Goal', pen: 'Penalty', og: 'Own goal', misspen: 'Missed penalty', yc: 'Yellow card', rc: 'Red card', y2: 'Second yellow → red', sub: 'Substitution' };
function eventsHtml(m){
  const ev = (m.events || []).slice().sort((a, b) => (a.min - b.min) || (a.extra - b.extra));
  if (!ev.length) return `<div class="empty">${LIVE.has(m.st.s) || DONE.has(m.st.s) ? 'No goals or cards yet.' : 'Goals and cards appear here once the match starts.'}</div>`;
  const cards = side => { const e = ev.filter(x => x.side === side); return `🟨 ${e.filter(x => x.type === 'yc').length} · 🟥 ${e.filter(x => x.type === 'rc' || x.type === 'y2').length}`; };
  return `<div class="ev-sum"><span>${cards('h')}</span><span>Cards</span><span>${cards('a')}</span></div>` + ev.map(e => {
    const sub = e.type === 'sub' ? (e.assist ? `on · ${esc(e.assist)} off` : 'Substitution') : e.type === 'goal' && e.assist ? `Goal · assist ${esc(e.assist)}` : WHAT[e.type];
    const txt = `${ICON[e.type]} <b>${esc(e.player)}</b><small>${sub}</small>`;
    const min = `${e.min}${e.extra ? '+' + e.extra : ''}'`;
    const cls = `ev ${e.type === 'sub' ? 'subst' : ''}`;
    return e.side === 'h' ? `<div class="${cls}"><div class="h">${txt}</div><div class="min">${min}</div><div></div></div>`
                          : `<div class="${cls}"><div></div><div class="min">${min}</div><div>${txt}</div></div>`;
  }).join('');
}
function lineupsHtml(m){
  const L = m.lineups || [];
  if (L.length < 2) return `<div class="empty">Line-ups aren't announced yet. Teams usually publish them about an hour before kick-off.</div>`;
  const home = L.find(l => l.side === 'h') || L[0], away = L.find(l => l.side === 'a') || L[1];
  const ev = m.events || [];
  const tags = name => ev.filter(e => e.player === name).map(e => e.type === 'og' ? '⚽<sup>OG</sup>' : e.type === 'sub' ? '🔼' : e.type === 'misspen' ? '' : ICON[e.type]).join('')
    + (ev.some(e => e.type === 'sub' && e.assist === name) ? '🔽' : '');
  const rowsOf = (lu, flip) => {
    const byRow = {};
    lu.xi.forEach(p => (byRow[p.row] = byRow[p.row] || []).push(p));
    let keys = Object.keys(byRow).map(Number).sort((a, b) => a - b);
    if (flip) keys = keys.reverse();
    return keys.map(k => {
      let ps = byRow[k].slice().sort((a, b) => a.col - b.col);
      if (flip) ps = ps.reverse();
      return `<div class="prow">${ps.map(p => `<div class="pl"><div class="n">${esc(p.num)}</div><div class="nm">${esc(lastName(p.name))}</div><div class="tags">${tags(p.name)}</div></div>`).join('')}</div>`;
    }).join('');
  };
  const subs = lu => lu.subs.map(p => `<div><span class="num">${esc(p.num)}</span>${esc(p.name)} ${tags(p.name)}</div>`).join('') || '<div>–</div>';
  return `
    <div class="form-head"><span>${esc(m.h.name)} · <b>${esc(home.formation || '–')}</b></span><span><b>${esc(away.formation || '–')}</b> · ${esc(m.a.name)}</span></div>
    <div class="pitch"><div class="half home">${rowsOf(home, false)}</div><div class="half away">${rowsOf(away, true)}</div></div>
    <div class="subs"><div><h4>${esc(m.h.name)} subs</h4>${subs(home)}</div><div><h4>${esc(m.a.name)} subs</h4>${subs(away)}</div></div>`;
}
function teamStatsHtml(m){
  const s = m.teamStats || [];
  if (!s.length) return `<div class="empty">Team statistics appear once the match starts.</div>`;
  return `<div class="tst"><span>${esc(m.h.abbr || m.h.short || 'Home')}</span><span></span><span>${esc(m.a.abbr || m.a.short || 'Away')}</span></div>`
    + s.map(x => `<div class="tst"><b>${esc(x.h)}</b><span>${esc(x.label)}</span><b>${esc(x.a)}</b></div>`).join('');
}
function boxHtml(m){
  let h = '';
  const n = Math.max(m.h.ls?.length || 0, m.a.ls?.length || 0);
  if (n){
    const per = i => m.comp === 'nba' || m.comp === 'nfl' ? (i < 4 ? 'Q' + (i + 1) : 'OT' + (i > 4 ? i - 3 : '')) : i + 1;
    const row = t => `<tr><td class="l">${esc(t.abbr || t.short || t.name)}</td>${Array.from({ length: n }, (_, i) => `<td>${esc(t.ls?.[i] ?? '')}</td>`).join('')}<td class="tot">${t.score ?? ''}</td></tr>`;
    h += `<table class="lsc"><thead><tr><th></th>${Array.from({ length: n }, (_, i) => `<th>${per(i)}</th>`).join('')}<th>T</th></tr></thead><tbody>${row(m.h)}${row(m.a)}</tbody></table>`;
  }
  const L = m.leaders || [];
  if (L.length){
    const col = side => { const t = L.find(x => x.side === side); return `<div><h4>${esc(side === 'h' ? m.h.short || m.h.name : m.a.short || m.a.name)}</h4>${t ? t.cats.map(c => `<div>${esc(c.name)} <b>${esc(c.value)}</b><small>${esc(c.label)}</small></div>`).join('') : '–'}</div>`; };
    h += `<div class="sbox"><h4>Top performers</h4></div><div class="ldr">${col('h')}${col('a')}</div>`;
  }
  return h || `<div class="empty">The box score appears once the game starts.</div>`;
}
function playsHtml(m){
  const p = m.plays || [];
  if (!p.length) return `<div class="empty">No scoring plays yet.</div>`;
  return p.map(x => `<div class="ply"><small>Q${esc(x.q)} ${esc(x.clock)}</small><b>${esc(x.side === 'h' ? m.h.abbr || m.h.short : m.a.abbr || m.a.short)}</b> ${esc(x.text)}${x.score ? ` <small>(${esc(x.score)})</small>` : ''}</div>`).join('');
}

/* ── SETTINGS: my teams ── */
function openSettings(){
  setOpen = true; setQuery = '';
  $('settings').classList.add('on'); $('sheetBg').classList.add('on'); document.body.classList.add('noscroll');
  renderSettings();
  if (!TEAMS[setComp]) loadTeams(setComp);
}
function renderSettings(){
  const s = $('settings');
  s.innerHTML = `
    <div class="sh-top"><div class="sh-bar"><h2>Settings</h2><button class="btn x" data-act="close" aria-label="Close">✕</button></div></div>
    <div class="sh-body">
      <div class="set-h">My teams · following ${favs.length}</div>
      <div class="myteams">${favs.length ? favs.map((f, i) => `<span class="fv">${f.logo ? `<img src="${esc(f.logo)}" alt="">` : '<i>★</i>'}${esc(f.name)}${f.sport !== 'soccer' ? ` <small style="color:var(--dim)">${f.sport.toUpperCase()}</small>` : ''}<button data-act="unfav" data-i="${i}" aria-label="Remove ${esc(f.name)}">✕</button></span>`).join('') : '<span class="empty" style="padding:0">No teams yet. Add some below.</span>'}</div>
      <div class="set-h">Home screen shows</div>
      <div class="mode"><button data-act="mode" data-v="mine" class="${homeMode === 'mine' ? 'on' : ''}">★ My teams</button><button data-act="mode" data-v="all" class="${homeMode === 'all' ? 'on' : ''}">All matches</button></div>
      <div class="set-h">Time zone</div>
      <div class="mode">${ZONES.map(z => `<button data-act="tz" data-v="${z.tz}" class="${TZ === z.tz ? 'on' : ''}">${z.flag} ${esc(z.short || z.label)} <small style="opacity:.75">${esc(zoneInfo(z.tz).abbr || zoneInfo(z.tz).off)}</small></button>`).join('')}</div>
      <div class="empty" style="font-size:11px;padding:2px 2px 6px">All kick-off times and dates follow this zone. Summer time changes are applied automatically.</div>
      <div class="set-h">Appearance</div>
      <div class="mode">${[['auto', '📱 Match my phone'], ['light', '☀️ Light'], ['dark', '🌙 Dark']].map(([v, l]) => `<button data-act="theme" data-v="${v}" class="${themePref === v ? 'on' : ''}">${l}</button>`).join('')}</div>
      <div class="set-h">Add teams</div>
      <div class="setchips">${ORDER.map(c => `<button data-act="setcomp" data-v="${c}" class="${c === setComp ? 'on' : ''}">${esc(cfull(c))}</button>`).join('')}</div>
      <input class="srch" id="tsearch" type="search" placeholder="Search teams in ${esc(C[setComp].name)}…" value="${esc(setQuery)}" autocomplete="off">
      <div id="tlist"></div>
      <button class="btn wide" data-act="resetfavs">Restore the default teams</button>
      <div class="empty" style="font-size:11px">Your teams are saved on this device only. Each friend chooses their own.</div>
    </div>`;
  renderTeamList();
}
function renderTeamList(){
  const el = $('tlist'); if (!el) return;
  const t = TEAMS[setComp];
  if (!t){ el.innerHTML = `<div class="empty">Loading teams…</div>`; return; }
  if (!t.list.length){ el.innerHTML = `<div class="empty">${t.error ? esc(t.error) : 'No teams listed for this competition right now.'}</div>`; return; }
  const q = norm(setQuery), sp = sport(setComp);
  const list = t.list.filter(x => !q || norm(x.name).includes(q) || norm(x.short).includes(q));
  el.innerHTML = list.map(x => { const on = isFavTeam(x, sp); return `<div class="trow"><img src="${esc(x.logo)}" alt="" loading="lazy"><span>${esc(x.name)}</span><button data-act="favtoggle" data-id="${x.id}" class="${on ? 'on' : ''}" aria-label="${on ? 'Unfollow' : 'Follow'} ${esc(x.name)}">${on ? '★' : '☆'}</button></div>`; }).join('')
    || `<div class="empty">No team matches "${esc(setQuery)}".</div>`;
}
function toggleFav(id){
  const t = TEAMS[setComp]?.list.find(x => x.id === id); if (!t) return;
  const sp = sport(setComp);
  if (isFavTeam(t, sp)) favs = favs.filter(f => !(f.sport === sp && ((f.id != null && f.id === t.id) || norm(f.name) === norm(t.name))));
  else favs.push({ name: t.name, id: t.id, sport: sp, logo: t.logo });
  saveFavs(); renderSettings(); renderAll();
}

/* ── NETWORK ── */
async function getJson(path){
  const r = await fetch(WORKER_URL.replace(/\/$/, '') + path, { cache: 'no-store' });
  const j = await r.json().catch(() => ({}));
  if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);
  return j;
}
async function loadDay(d){
  await Promise.all(homeComps().map(async c => {
    try { const j = await getJson(`/day?comp=${c}&date=${d.replace(/-/g, '')}&tz=${encodeURIComponent(TZ)}`); DAY[c + '|' + d + '|' + TZ] = { list: (j.response || []).map(m => ({ ...m, comp: c })), at: Date.parse(j.updatedAt), warning: j.warning }; }
    catch (e) { DAY[c + '|' + d + '|' + TZ] = { list: dayData(c, d)?.list || [], at: dayData(c, d)?.at || 0, error: e.message }; }
    if (section === 'today' && viewDate() === d) renderToday();
  }));
}
async function loadToday(){
  await Promise.all(homeComps().map(async c => {
    try { const j = await getJson('/window?comp=' + c); WIN[c] = { list: (j.response || []).map(m => ({ ...m, comp: c })), at: Date.parse(j.updatedAt), warning: j.warning }; }
    catch (e) { WIN[c] = { list: WIN[c]?.list || [], at: WIN[c]?.at || 0, error: e.message }; }
    if (section === 'today') renderToday();
  }));
}
async function loadComp(c){
  const [fx, tb, st] = await Promise.allSettled([getJson('/fixtures?comp=' + c), getJson('/standings?comp=' + c), getJson('/stats?comp=' + c)]);
  if (fx.status === 'fulfilled') FIX[c] = { list: (fx.value.response || []).map(m => ({ ...m, comp: c })), at: Date.parse(fx.value.updatedAt), warning: fx.value.warning };
  else FIX[c] = { list: FIX[c]?.list || [], at: FIX[c]?.at || 0, error: fx.reason.message };
  TAB[c] = tb.status === 'fulfilled' ? { groups: tb.value.response || [] } : { groups: TAB[c]?.groups || [], error: tb.reason.message };
  STA[c] = st.status === 'fulfilled' ? { cats: st.value.response || [] } : { cats: STA[c]?.cats || [], error: st.reason.message };
}
async function loadTeams(c){
  try { const j = await getJson('/teams?comp=' + c); TEAMS[c] = { list: j.response || [] }; }
  catch (e) { TEAMS[c] = { list: [], error: e.message }; }
  // fill in logos for default teams once a list includes them
  let changed = false;
  favs.forEach(f => { if (!f.logo && f.sport === sport(c)){ const t = TEAMS[c].list.find(x => norm(x.name) === norm(f.name)); if (t){ f.logo = t.logo; changed = true; } } });
  if (changed) saveFavs();
  if (setOpen && c === setComp) renderTeamList();
}
async function loadMatch(key){
  const [comp, id] = key.split(':');
  try {
    const j = await getJson(`/match?comp=${comp}&id=${id}`);
    const m = j.response?.[0], old = MATCH[key]?.m;
    if (m){
      MATCH[key] = { m: { ...m, comp }, at: Date.parse(j.updatedAt), next: j.nextRefreshIn };
      if (old && (old.h.score !== m.h.score || old.a.score !== m.a.score)) flash(key);
    } else if (!old) MATCH[key] = { at: Date.now(), error: j.warning || 'Match not found' };
  } catch (e) { if (!MATCH[key]?.m) MATCH[key] = { at: Date.now(), error: e.message }; }
}

async function refresh(){
  if (busy) return;
  if (WORKER_URL.includes('YOUR-WORKER')){ setupNeeded(); return; }
  busy = true; $('rf').disabled = true; $('rf').classList.add('busy'); statusLine();
  try {
    if (section === 'today') await (isToday() ? loadToday() : loadDay(viewDate()));
    else await loadComp(currentComp());
    await refreshTracked(true);
  } finally {
    busy = false; $('rf').disabled = false; $('rf').classList.remove('busy'); renderAll(); statusLine();
    // the person may have switched screens while this was loading
    if (section === 'today' ? homeMissing() : !FIX[currentComp()]) setTimeout(refresh, 0);
  }
}

/* tracked matches: updated every 5 minutes while the page is open and visible */
async function refreshTracked(manual = false){
  clearTimeout(trackTimer);
  const due = tracked.filter(t => { const m = MATCH[t.key]?.m; return manual || !m || !DONE.has(m.st.s); });
  await Promise.all(due.map(t => loadMatch(t.key)));
  const before = tracked.length;
  tracked = tracked.filter(t => { const m = MATCH[t.key]?.m; return !(m && DONE.has(m.st.s) && Date.now() - m.ts * 1000 > 30 * 3600e3); });
  if (tracked.length !== before) store.set('fl3_tracked', tracked);
  scheduleTracked();
  if (!manual){ renderAll(); statusLine(); }
}
function scheduleTracked(){
  clearTimeout(trackTimer); nextTrackAt = null;
  const pending = tracked.filter(t => { const m = MATCH[t.key]?.m; return !m || !DONE.has(m.st.s); });
  if (!pending.length || document.hidden) return;
  const soonest = Math.min(...pending.map(t => MATCH[t.key]?.next ?? TRACK_EVERY));
  const wait = Math.min(TRACK_EVERY, Math.max(30, soonest + 5));
  nextTrackAt = Date.now() + wait * 1000;
  trackTimer = setTimeout(() => refreshTracked(false), wait * 1000);
}
function toggleTrack(key){
  if (!key) return;
  const [comp, id] = key.split(':');
  if (isTracked(key)) tracked = tracked.filter(t => t.key !== key);
  else { tracked.push({ key, comp, id: +id }); loadMatch(key).then(() => { scheduleTracked(); renderAll(); }); }
  store.set('fl3_tracked', tracked);
  scheduleTracked(); renderAll(); statusLine();
}
function flash(key){
  setTimeout(() => document.querySelectorAll(`.m[data-key="${CSS.escape(key)}"]`).forEach(el => { el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash'); }), 50);
}

function statusLine(){
  const el = $('stxt');
  if (busy){ el.className = 'stxt'; el.innerHTML = '<b>Updating…</b>'; return; }
  let at = 0, problem = '';
  if (section === 'today'){
    const src = c => isToday() ? WIN[c] : dayData(c, viewDate());
    const l = homeComps().filter(src); at = Math.max(0, ...l.map(c => src(c).at || 0));
    const bad = l.filter(c => src(c).error || src(c).warning); if (bad.length === l.length && l.length) problem = src(bad[0]).error || src(bad[0]).warning;
  } else { const d = FIX[currentComp()]; at = d?.at || 0; problem = d?.error || d?.warning || ''; }
  const parts = [];
  if (at) parts.push(`Data from ${tTime(new Date(at))}`);
  if (tracked.length) parts.push(`tracking ${tracked.length}`);
  el.className = 'stxt' + (problem ? ' err' : '');
  el.innerHTML = `<b>${problem ? 'Problem' : at ? 'Up to date' : 'Ready'}</b> · ${parts.join(' · ') || 'tap Refresh'}`;
  el.title = problem || '';
}
function setupNeeded(){
  $('stxt').className = 'stxt err'; $('stxt').innerHTML = '<b>Setup needed</b>';
  $('p-today').innerHTML = `<div class="msg"><h3>One step left</h3>Open <code>index.html</code>, find <code>WORKER_URL</code> near the top of the script, and paste your Cloudflare Worker address.</div>`;
}
function tickCountdowns(){
  const left = nextTrackAt ? Math.max(0, Math.round((nextTrackAt - Date.now()) / 1000)) : null;
  document.querySelectorAll('[data-cd]').forEach(el => el.textContent = left === null ? 'paused' : mmss(left));
}
function tickClock(){
  $('clk').textContent = new Date().toLocaleTimeString('en-GB', {timeZone:TZ});
  tickCountdowns();
}

/* ── EVENTS ── */
// true when the Today screen has competitions with no data yet (date, sport or screen changed)
function homeMissing(){ const d = viewDate(); return homeComps().some(c => isToday() ? !WIN[c] : !dayData(c, d)); }
function setDate(d){
  homeDate = (!d || d === todayKey()) ? null : d;
  renderAll(); statusLine();
  if (homeMissing()) refresh();
}
function go(sec, comp){
  section = sec; store.set('fl3_section', section);
  if (comp){ lastComp[sec] = comp; store.set('fl3_comp', lastComp); }
  renderAll(); statusLine(); window.scrollTo(0, 0);
  if (section === 'today'){ if (homeMissing()) refresh(); }
  else if (!FIX[currentComp()]) refresh();
}
document.addEventListener('click', e => {
  const b = e.target.closest('[data-act]');
  const cardEl = e.target.closest('.m[data-key]');
  if (!b){ if (cardEl && !e.target.closest('.sheet')) openSheet(cardEl.dataset.key); return; }
  const key = b.dataset.key || cardEl?.dataset.key || (b.closest('#sheet') ? sheetKey : null);
  switch (b.dataset.act){
    case 'section': go(b.dataset.v); break;
    case 'comp': go(section, b.dataset.v); break;
    case 'track': toggleTrack(key); break;
    case 'untrack': tracked = tracked.filter(t => t.key !== key); store.set('fl3_tracked', tracked); scheduleTracked(); renderAll(); statusLine(); break;
    case 'details': openSheet(key); break;
    case 'close': closeSheets(); break;
    case 'stab': sheetTab = b.dataset.t; renderSheet(); break;
    case 'refresh-match': loadMatch(sheetKey).then(renderAll); break;
    case 'round': {
      const comp = currentComp(), d = FIX[comp], rs = rounds(d.list), i = rs.indexOf(roundSel[comp]) + +b.dataset.step;
      if (i >= 0 && i < rs.length){ roundSel[comp] = rs[i]; renderMatches(); window.scrollTo(0, 0); }
      break;
    }
    case 'sport': homeSport = b.dataset.v; store.set('fl3_sport', homeSport); renderAll(); statusLine(); if (homeMissing()) refresh(); break;
    case 'day': setDate(shiftDate(viewDate(), +b.dataset.step)); break;
    case 'dtoday': setDate(null); break;
    case 'mode': homeMode = b.dataset.v; store.set('fl3_mode', homeMode); renderAll(); if (setOpen) renderSettings(); break;
    case 'settings': openSettings(); break;
    case 'tz': TZ = b.dataset.v; store.set('fl3_tz', TZ); homeDate = null; renderAll(); statusLine(); if (setOpen) renderSettings(); if (section === 'today' && homeMissing()) refresh(); break;
    case 'theme': themePref = b.dataset.v; store.set('fl3_theme', themePref); applyTheme(); if (setOpen) renderSettings(); break;
    case 'setcomp': setComp = b.dataset.v; setQuery = ''; renderSettings(); if (!TEAMS[setComp]) loadTeams(setComp); break;
    case 'favtoggle': toggleFav(+b.dataset.id); break;
    case 'unfav': favs.splice(+b.dataset.i, 1); saveFavs(); renderSettings(); renderAll(); break;
    case 'resetfavs': favs = DEFAULT_TEAMS.map(t => ({ ...t, id: null, logo: '' })); saveFavs(); renderSettings(); renderAll(); break;
  }
});
document.addEventListener('input', e => { if (e.target.id === 'tsearch'){ setQuery = e.target.value; renderTeamList(); } });
document.addEventListener('change', e => { if (e.target.id === 'dpick' && /^\d{4}-\d{2}-\d{2}$/.test(e.target.value)) setDate(e.target.value); });
$('sheetBg').onclick = closeSheets;
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSheets(); });
$('rf').onclick = refresh;
document.querySelectorAll('.nav button').forEach(b => b.onclick = () => { panel = b.dataset.p; renderShell(); window.scrollTo(0, 0); });
document.addEventListener('visibilitychange', () => {
  if (document.hidden){ clearTimeout(trackTimer); nextTrackAt = null; tickCountdowns(); }
  else if (tracked.length) refreshTracked(false);
});

/* start */
applyTheme();
setInterval(tickClock, 1000); tickClock();
renderAll(); statusLine();
refresh();
if (tracked.length) refreshTracked(false);
</script>
</body>
</html>