Spaces:
Running
Running
File size: 46,695 Bytes
561d53a 3a61d39 561d53a cf64017 561d53a cf64017 561d53a 204fe27 | 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 | <!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">
<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);
--teal:#2dd4bf;--tlbg:rgba(45,212,191,.13);
--live:#ff3b3b;
--nav-h:62px;
}
*,*::before,*::after{margin:0;padding:0;box-sizing:border-box}
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))}
body.noscroll{overflow:hidden}
button{font-family:inherit;cursor:pointer}
.wrap{max-width:860px;margin:0 auto}
/* header + competition switcher */
.hdr{background:linear-gradient(180deg,#0e1122 0%,var(--bg) 100%);border-bottom:1px solid var(--bdr2);padding:16px 16px 12px;text-align:center;position:relative}
.hdr::after{content:'';position:absolute;left:0;right:0;bottom:0;height:2px;background:linear-gradient(90deg,transparent,var(--gold),transparent)}
.hdr h1{font-family:'Bebas Neue';font-size:clamp(28px,7vw,44px);letter-spacing:4px;color:var(--gold);line-height:1;text-shadow:0 0 28px rgba(244,196,48,.3)}
.hdr-sub{font-size:10px;font-weight:600;letter-spacing:2.5px;color:var(--gr);text-transform:uppercase;margin-top:4px}
.comp{display:inline-flex;margin-top:12px;background:var(--s2);border:1px solid var(--bdr2);border-radius:10px;padding:3px;gap:3px}
.comp button{border:0;background:none;color:var(--gr);font-weight:700;font-size:12px;padding:7px 14px;border-radius:7px}
.comp button.on{background:var(--gold);color:#16130a}
/* sticky bar with the refresh button */
.sbar{position:sticky;top:0;z-index:30;background:rgba(11,13,23,.97);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}
.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:#a9c8ff;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:14px 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 code{font-family:'JetBrains Mono';background:rgba(255,255,255,.07);padding:1px 6px;border-radius:4px;color:var(--w);font-size:12px}
.msg.err{border-color:rgba(255,159,67,.45)}
/* 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 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}
.m.done .tm:not(.win) 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:#fff}
.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}
.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:rgba(255,255,255,.06);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}
.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)}
.cd{font-family:'JetBrains Mono';color:var(--gold)}
/* matches tab: 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}
.mw button:disabled{opacity:.3}
.mw div{text-align:center}
.mw b{font-family:'Bebas Neue';font-size:23px;letter-spacing:2px;color:var(--gold);display:block;line-height:1.1}
.mw small{font-size:11px;color:var(--gr)}
/* table */
.tbl{width:100%;border-collapse:collapse;background:var(--s1);border:1px solid var(--bdr);border-radius:12px;overflow:hidden}
.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)}
.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)}
.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}
.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)}
.z-ucl td.pos{border-left-color:var(--blue)} .z-uel td.pos{border-left-color:var(--orange)}
.z-uecl td.pos{border-left-color:var(--teal)} .z-rel td.pos{border-left-color:var(--red)}
.z-r16 td.pos{border-left-color:var(--green)} .z-po td.pos{border-left-color:var(--orange)}
.q-ucl td{background:var(--blbg)} .q-uel td{background:var(--orbg)} .q-uecl td{background:var(--tlbg)}
.q-r16 td{background:var(--grbg)} .q-po td{background:var(--orbg)}
.q-out td{opacity:.55} .q-rel td{background:var(--rdbg)}
.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}
.b-ucl{background:var(--blue);color:#06142d}.b-uel{background:var(--orange);color:#2a1300}.b-uecl{background:var(--teal);color:#032a25}
.b-r16{background:var(--green);color:#03200f}.b-po{background:var(--orange);color:#2a1300}
.b-rel,.b-out{background:var(--red);color:#2d0000}
.tbl tr.playing td.l{color:var(--gold2)}
.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-top:10px}
.legend span::before{content:'';display:inline-block;width:9px;height:9px;border-radius:2px;margin-right:5px;vertical-align:-1px;background:var(--c)}
/* stats */
.sc-row img.ph{width:30px;height:30px;border-radius:50%;object-fit:cover;background:var(--s3)}
.sc-row .who{display:flex;align-items:center;gap:9px}
.sc-row .who small{display:flex;align-items:center;gap:5px;color:var(--gr);font-weight:500;font-size:11px}
.sc-row .who small img{width:14px;height:14px}
.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 span{font-size:13px}.tm img{width:22px;height:22px}}
/* match details sheet */
.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:92vh;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))}
.sheet.on{transform:none}
@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:10px 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-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(--gold);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 b{font-weight:700}
.ev small{display:block;color:var(--gr);font-size:11px}
.ev-sum{display:flex;justify-content:space-around;font-size:12px;color:var(--gr);margin-bottom:8px}
/* 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;position:relative}
.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)}
/* 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:rgba(11,13,23,.98);border-top:1px solid var(--bdr2);display:flex}
.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;position:relative}
.nav button.on{color:var(--gold)}
.nav .ico{font-size:20px;line-height:1}
.nav .dot{position:absolute;top:8px;right:calc(50% - 18px);width:8px;height:8px;border-radius:50%;background:var(--live);display:none;animation:blink 1s infinite}
.nav .dot.show{display:block}
.cal{width:22px;height:22px;border-radius:4px;overflow:hidden;background:#fff;display:flex;flex-direction:column}
.cal b{background:var(--red);color:#fff;font-size:6px;line-height:8px;text-align:center}
.cal i{font-style:normal;font-weight:800;font-size:11px;line-height:14px;color:#111;text-align:center}
.nav button.on .cal{box-shadow:0 0 0 2px var(--gold)}
</style>
</head>
<body>
<header class="hdr">
<h1>Football Live</h1>
<div class="hdr-sub">2026/27 Β· All times Dubai (GMT+4)</div>
<div class="comp" role="tablist">
<button data-comp="39">Premier League</button>
<button data-comp="2">Champions League</button>
</div>
</header>
<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>
<nav class="nav">
<button class="on" data-p="today"><span class="cal"><b id="calM">JAN</b><i id="calD">1</i></span>Today<span class="dot" id="liveDot"></span></button>
<button data-p="matches"><span class="ico">β½</span>Matches</button>
<button data-p="table"><span class="ico">π</span>Table</button>
<button data-p="stats"><span class="ico">π</span>Scorers</button>
</nav>
<script>
/* ββ SETTINGS ββββββββββββββββββββββββββββββββββββββββββββββ
Paste your Cloudflare Worker address here (see SETUP.md). */
const WORKER_URL = 'https://pl-live-scores.footballive.workers.dev';
const TRACK_EVERY = 5 * 60; // seconds between updates of tracked matches
/* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
const TZ = 'Asia/Dubai';
const COMPS = { '39': 'Premier League', '2': 'Champions League' };
const LIVE = new Set(['1H','HT','2H','ET','BT','P','SUSP','INT','LIVE']);
const DONE = new Set(['FT','AET','PEN','AWD','WO']);
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 */
const DATA = {}; // DATA[league] = { fix:[], table:[], scorers:[], at, warning }
const MATCH = {}; // MATCH[id] = { fx, at, next } β detailed answers from /match
let comp = String(store.get('fl_comp', '39'));
if (!COMPS[comp]) comp = '39';
let tracked = store.get('fl_tracked', []); // [{ id, league, added }]
if (!Array.isArray(tracked)) tracked = [];
let roundSel = {}, sheetId = null, sheetTab = 'events';
let trackTimer = null, nextTrackAt = null, busy = false;
/* ββ small helpers ββ */
const $ = id => document.getElementById(id);
const esc = s => String(s ?? '').replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[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 = f => new Date(f.fixture.timestamp * 1000);
const st = f => f.fixture.status.short;
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 = id => tracked.some(t => t.id === id);
const trackable = f => !DONE.has(st(f)) && !OFF.has(st(f));
/* freshest copy of a match: the detailed /match answer if it is newer than the list */
function best(f){ const m = MATCH[f.fixture.id]; return m && m.fx && m.at >= (DATA[f.league.id]?.at || 0) ? m.fx : f; }
function allFixtures(){ return Object.values(DATA).flatMap(d => d.fix || []); }
function roundLabel(r){
r = String(r || '');
let m = r.match(/^Regular Season - (\d+)$/i); if (m) return 'Matchweek ' + m[1];
m = r.match(/^League Stage - (\d+)$/i); if (m) return 'League phase Β· Matchday ' + m[1];
return r;
}
/* ββ one match card ββ */
function card(raw, opts = {}){
const f = best(raw), s = st(f), live = LIVE.has(s), done = DONE.has(s), off = OFF.has(s);
const h = f.teams.home, a = f.teams.away, g = f.goals, id = f.fixture.id, on = isTracked(id);
let mid, pill;
if (live){
const min = s === 'HT' ? 'Half time' : s === 'BT' ? 'Break' : s === 'P' ? 'Penalties'
: (f.fixture.status.elapsed ?? '') + (f.fixture.status.extra ? '+' + f.fixture.status.extra : '') + "'";
mid = `<div class="sc">${g.home ?? 0} β ${g.away ?? 0}</div>`;
pill = `<span class="st lv"><i></i>${esc(min)}</span>`;
} else if (done){
mid = `<div class="sc">${g.home} β ${g.away}</div>`;
pill = `<span class="st ft">${s === 'FT' ? 'Full time' : s === 'PEN' ? 'After pens' : s === 'AET' ? 'After ET' : esc(s)}</span>`;
} else if (off){
mid = `<div class="ko">${tTime(when(f))}</div>`;
pill = `<span class="st pp">${s === 'PST' ? 'Postponed' : s === 'CANC' ? 'Cancelled' : 'Abandoned'}</span>`;
} else {
mid = `<div class="ko">${s === 'TBD' ? 'TBD' : tTime(when(f))}</div>`;
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"><span>${esc(t.name)}</span></div>`;
let info = `${tShort(when(f))} Β· ${tTime(when(f))}${f.fixture.venue?.name ? ' Β· ' + esc(f.fixture.venue.name) : ''}`;
if (opts.tracking){
info = `${COMPS[f.league.id] || ''} Β· ${done ? 'Final score, tracking stopped' : `updates every 5 min Β· next in <span class="cd" data-cd>β</span>`}`;
}
const trackBtn = (trackable(f) || on)
? `<button class="btn trk ${on ? 'on' : ''}" data-act="track">${on ? 'β
Tracking' : 'β Track'}</button>` : '';
const removeBtn = opts.tracking ? `<button class="btn x" data-act="untrack" aria-label="Stop tracking">β</button>` : '';
return `<div class="m ${live ? 'live' : done ? 'done' : ''} ${on ? 'tracked' : ''}" data-id="${id}" data-lg="${f.league.id}">
${team(h,'home')}<div class="mid">${mid}${pill}</div>${team(a,'away')}
<div class="acts"><span class="info">${info}</span>${opts.tracking ? '' : trackBtn}<button class="btn" data-act="details">Details βΊ</button>${removeBtn}</div>
</div>`;
}
function byDay(list){
let out = '', last = '';
list.forEach(f => {
const k = dKey(when(f));
if (k !== last){ out += `<div class="day">${tDay(when(f))}</div>`; last = k; }
out += card(f);
});
return out;
}
/* ββ TODAY ββ */
function renderToday(){
const d = DATA[comp];
let h = '';
// tracked matches, from either competition
if (tracked.length){
const cards = tracked.map(t => {
const f = MATCH[t.id]?.fx || allFixtures().find(x => x.fixture.id === t.id);
return f ? card(f, {tracking:true}) : `<div class="m" data-id="${t.id}"><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('');
h += `<div class="sec">β
Tracking <small>updates every 5 minutes while this page is open</small></div>` + cards;
}
if (!d){ $('p-today').innerHTML = h + `<div class="empty">Loading ${COMPS[comp]}β¦</div>`; return; }
if (d.error && !d.fix.length){ $('p-today').innerHTML = h + errorBox(d.error); return; }
const todayKey = dKey(new Date());
const fix = d.fix;
const live = fix.filter(f => LIVE.has(st(best(f))) && !isTracked(f.fixture.id)); // tracked ones are shown above
const today = fix.filter(f => dKey(when(f)) === todayKey && !LIVE.has(st(best(f))) && !isTracked(f.fixture.id)).sort((a,b) => when(a) - when(b));
if (live.length) h += `<div class="sec">π΄ Live now <small>score as of your last refresh. Tap β Track for 5-minute updates</small></div>` + live.map(f => card(f)).join('');
if (today.length) h += `<div class="sec">Today <small>${tDay(new Date())}</small></div>` + today.map(f => card(f)).join('');
if (!live.length && !today.length){
h += `<div class="sec">No ${COMPS[comp]} matches today</div>`;
const up = fix.filter(f => trackable(f) && when(f) > Date.now()).sort((a,b) => when(a) - when(b));
if (up.length){ const k = dKey(when(up[0])); h += `<div class="sec">Next match day <small>${tDay(when(up[0]))}</small></div>` + up.filter(f => dKey(when(f)) === k).map(f => card(f)).join(''); }
}
const recent = fix.filter(f => DONE.has(st(f)) && dKey(when(f)) !== todayKey).sort((a,b) => when(b) - when(a)).slice(0, 6);
if (recent.length) h += `<div class="sec">Latest results</div>` + recent.map(f => card(f)).join('');
$('p-today').innerHTML = h || `<div class="empty">No fixtures yet.</div>`;
}
/* ββ MATCHES (by round) ββ */
function rounds(fix){
const first = {};
fix.forEach(f => { if (OFF.has(st(f))) return; const r = f.league.round, t = f.fixture.timestamp; if (!(r in first) || t < first[r]) first[r] = t; });
fix.forEach(f => { if (!(f.league.round in first)) first[f.league.round] = f.fixture.timestamp; });
return Object.keys(first).sort((a,b) => first[a] - first[b]);
}
function currentRound(fix){
const cut = Date.now() - 3 * 3600e3;
const next = fix.filter(f => trackable(f) && when(f) >= cut).sort((a,b) => when(a) - when(b))[0];
const rs = rounds(fix);
return next ? next.league.round : rs[rs.length - 1];
}
function renderMatches(){
const d = DATA[comp];
if (!d || !d.fix.length){ $('p-matches').innerHTML = d?.error ? errorBox(d.error) : `<div class="empty">No fixtures yet.</div>`; return; }
const rs = rounds(d.fix), cur = currentRound(d.fix);
if (!rs.includes(roundSel[comp])) roundSel[comp] = cur;
const r = roundSel[comp], i = rs.indexOf(r);
const list = d.fix.filter(f => f.league.round === r).sort((a,b) => when(a) - when(b));
$('p-matches').innerHTML = `
<div class="mw">
<button data-act="round" data-step="-1" ${i <= 0 ? 'disabled' : ''} aria-label="Previous round">βΉ</button>
<div><b>${esc(roundLabel(r))}</b><small>${r === cur ? 'Current' : i < rs.indexOf(cur) ? 'Played' : 'Upcoming'}</small></div>
<button data-act="round" data-step="1" ${i >= rs.length - 1 ? 'disabled' : ''} aria-label="Next round">βΊ</button>
</div>` + byDay(list);
}
/* ββ TABLE + qualification status ββ */
function zoneOf(desc, league){
const d = String(desc || '').toLowerCase();
if (league === '2'){
if (/round of 16|1\/8/.test(d)) return 'r16';
if (/play.?off|1\/16/.test(d)) return 'po';
return '';
}
if (d.includes('champions league')) return 'ucl';
if (d.includes('europa league')) return 'uel';
if (d.includes('conference')) return 'uecl';
if (d.includes('relegation')) return 'rel';
return '';
}
/* Which places are mathematically certain.
A team has secured a top-k place when fewer than k other teams can still reach its points.
A team can no longer reach the top k when k other teams already have more points than its maximum.
Ties are treated as "not yet certain", because goal difference can still change. */
function clinchStatus(table, league){
const n = table.length;
const games = league === '2' ? 8 : (n - 1) * 2;
const rows = table.map(r => ({ r, pts: r.points, max: r.points + 3 * Math.max(0, games - r.all.played), zone: zoneOf(r.description, league) }));
const count = z => rows.filter(x => x.zone === z).length;
const secured = (t, k) => k > 0 && rows.filter(o => o !== t && o.max >= t.pts).length <= k - 1;
const outOf = (t, k) => rows.filter(o => o !== t && o.pts > t.max).length >= k;
const out = new Map();
if (league === '2'){
const k16 = count('r16'), kPO = k16 + count('po');
rows.forEach(t => {
if (secured(t, k16)) out.set(t.r.team.id, ['r16', 'Last 16 β']);
else if (kPO && secured(t, kPO)) out.set(t.r.team.id, ['po', 'Play-offs β']);
else if (kPO && outOf(t, kPO)) out.set(t.r.team.id, ['out', 'Eliminated']);
});
} else {
const kU = count('ucl'), kE = kU + count('uel'), kC = kE + count('uecl'), safe = n - count('rel');
rows.forEach(t => {
if (secured(t, kU)) out.set(t.r.team.id, ['ucl', 'UCL β']);
else if (count('uel') && secured(t, kE)) out.set(t.r.team.id, ['uel', 'Europa β']);
else if (count('uecl') && secured(t, kC)) out.set(t.r.team.id, ['uecl', 'Conference β']);
else if (count('rel') && outOf(t, safe)) out.set(t.r.team.id, ['rel', 'Relegated']);
});
}
return out;
}
function renderTable(){
const d = DATA[comp];
if (!d || !d.table.length){ $('p-table').innerHTML = d?.tableError ? errorBox(d.tableError) : `<div class="empty">Table not available yet.</div>`; return; }
const playing = new Set(d.fix.filter(f => LIVE.has(st(best(f)))).flatMap(f => [f.teams.home.id, f.teams.away.id]));
const status = clinchStatus(d.table, comp);
const rows = d.table.map(r => {
const z = zoneOf(r.description, comp), s = status.get(r.team.id);
return `<tr class="${z ? 'z-' + z : ''} ${s ? 'q-' + s[0] : ''} ${playing.has(r.team.id) ? 'playing' : ''}">
<td class="pos">${r.rank}</td>
<td class="l"><div class="c"><img src="${esc(r.team.logo)}" alt="" loading="lazy">${esc(r.team.name)}${playing.has(r.team.id) ? ' π΄' : ''}${s ? ` <span class="bdg b-${s[0]}">${s[1]}</span>` : ''}</div></td>
<td>${r.all.played}</td><td class="hide-sm">${r.all.win}</td><td class="hide-sm">${r.all.draw}</td><td class="hide-sm">${r.all.lose}</td>
<td>${r.goalsDiff > 0 ? '+' : ''}${r.goalsDiff}</td><td class="pts">${r.points}</td>
<td class="hide-sm"><div class="form">${[...(r.form || '')].slice(-5).map(c => `<i class="${esc(c)}">${esc(c)}</i>`).join('')}</div></td>
</tr>`;
}).join('');
const legend = comp === '2'
? `<span style="--c:var(--green)">Last 16 (1β8)</span><span style="--c:var(--orange)">Knockout play-offs (9β24)</span>`
: `<span style="--c:var(--blue)">Champions League</span><span style="--c:var(--orange)">Europa League</span><span style="--c:var(--teal)">Conference League</span><span style="--c:var(--red)">Relegation</span>`;
$('p-table').innerHTML = `
${playing.size ? `<div class="note">π΄ Matches are in progress. Tap Refresh for the latest table.</div>` : ''}
<div class="note">${status.size
? '<b>Shaded rows with a β badge have mathematically secured that place.</b> Nobody below can catch them, even by winning every remaining match.'
: 'Coloured edges show the places as things stand. Badges (UCL β, Europa β, Relegated) appear once a place is mathematically certain, usually in the last month of the season.'}</div>
<table class="tbl"><thead><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><th class="hide-sm">Form</th></tr></thead><tbody>${rows}</tbody></table>
<div class="legend">${legend}</div>
<div class="empty" style="font-size:11px">Which positions qualify comes from the competition data. Cup winners or an extra European place can change it during the season.</div>`;
}
/* ββ TOP SCORERS ββ */
function renderStats(){
const d = DATA[comp];
if (!d || !d.scorers.length){ $('p-stats').innerHTML = d?.scorersError ? errorBox(d.scorersError) : `<div class="empty">No goals scored yet this season.</div>`; return; }
const rows = d.scorers.slice(0, 20).map((x, i) => {
const s = x.statistics?.[0] || {};
return `<tr class="sc-row"><td class="pos">${i + 1}</td>
<td class="l"><div class="who"><img class="ph" src="${esc(x.player.photo)}" alt="" loading="lazy"><div>${esc(x.player.name)}<small><img src="${esc(s.team?.logo)}" alt="">${esc(s.team?.name)}</small></div></div></td>
<td class="big">${s.goals?.total ?? 0}</td><td>${s.goals?.assists ?? 0}</td><td class="hide-sm">${s.penalty?.scored ?? 0}</td><td class="hide-sm">${s.games?.appearences ?? 'β'}</td></tr>`;
}).join('');
$('p-stats').innerHTML = `<div class="sec">Top goal scorers <small>${COMPS[comp]}</small></div>
<table class="tbl"><thead><tr><th>#</th><th class="l">Player</th><th>Goals</th><th>Assists</th><th class="hide-sm">Pens</th><th class="hide-sm">Apps</th></tr></thead><tbody>${rows}</tbody></table>`;
}
function errorBox(e){
return `<div class="msg err"><h3>No data from the score service</h3>${esc(e)}<br><br>The scores come from ESPN's public feed through your Cloudflare Worker. Try Refresh in a minute; if it keeps failing, open your Worker address with <code>/fixtures</code> at the end to see what it says.</div>`;
}
function renderAll(){
renderToday(); renderMatches(); renderTable(); renderStats();
if (sheetId) renderSheet();
const anyLive = Object.values(DATA).some(d => d.fix.some(f => LIVE.has(st(best(f))))) || tracked.some(t => { const f = MATCH[t.id]?.fx; return f && LIVE.has(st(f)); });
$('liveDot').classList.toggle('show', anyLive);
document.querySelectorAll('.comp button').forEach(b => b.classList.toggle('on', b.dataset.comp === comp));
tickCountdowns();
}
/* ββ MATCH DETAILS SHEET ββ */
function openSheet(id){
sheetId = id; sheetTab = 'events';
$('sheet').classList.add('on'); $('sheetBg').classList.add('on'); document.body.classList.add('noscroll');
$('sheet').scrollTop = 0;
renderSheet();
loadMatch(id).then(renderAll);
}
function closeSheet(){
sheetId = null;
$('sheet').classList.remove('on'); $('sheetBg').classList.remove('on'); document.body.classList.remove('noscroll');
}
function renderSheet(){
const m = MATCH[sheetId];
const f = m?.fx || allFixtures().find(x => x.fixture.id === sheetId);
if (!f){ $('sheet').innerHTML = `<div class="sh-body">${m?.error ? esc(m.error) : 'Loadingβ¦'} <button class="btn x" data-act="close">β</button></div>`; return; }
const s = st(f), live = LIVE.has(s), done = DONE.has(s), on = isTracked(f.fixture.id);
const score = (live || done) ? `${f.goals.home ?? 0} β ${f.goals.away ?? 0}` : tTime(when(f));
const status = live ? (s === 'HT' ? 'Half time' : `${f.fixture.status.elapsed ?? ''}'`) : done ? 'Full time' : OFF.has(s) ? 'Postponed' : 'Kick-off';
const updated = m?.fx ? `Updated ${tTime(new Date(m.at))}` : 'Loading detailsβ¦';
const body = !m ? `<div class="empty">Loading goals, cards and line-upsβ¦</div>`
: !m.fx ? `<div class="msg err">${esc(m.error || 'No details')}</div>`
: sheetTab === 'events' ? eventsHtml(f) : lineupsHtml(f);
$('sheet').innerHTML = `
<div class="sh-top">
<div class="sh-bar"><span class="ttl">${esc(COMPS[f.league.id] || '')} Β· ${esc(roundLabel(f.league.round))} Β· ${tShort(when(f))} Β· ${updated}</span>
${(trackable(f) || on) ? `<button class="btn trk ${on ? 'on' : ''}" data-act="track" data-id="${f.fixture.id}" data-lg="${f.league.id}">${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(f.teams.home.logo)}" alt="">${esc(f.teams.home.name)}</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(f.teams.away.logo)}" alt="">${esc(f.teams.away.name)}</div>
</div>
<div class="sh-tabs"><button data-act="stab" data-t="events" class="${sheetTab === 'events' ? 'on' : ''}">Goals & cards</button><button data-act="stab" data-t="lineups" class="${sheetTab === 'lineups' ? 'on' : ''}">Line-ups</button></div>
</div>
<div class="sh-body">${body}</div>`;
}
function eventsOf(f){
return (f.events || []).filter(e => e.type === 'Goal' || e.type === 'Card')
.sort((a,b) => (a.time.elapsed - b.time.elapsed) || ((a.time.extra || 0) - (b.time.extra || 0)));
}
function eventIcon(e){
if (e.type === 'Goal') return e.detail === 'Missed Penalty' ? 'β' : 'β½';
if (/second yellow/i.test(e.detail)) return 'π¨π₯';
return /red/i.test(e.detail) ? 'π₯' : 'π¨';
}
function eventsHtml(f){
const evs = eventsOf(f);
if (!evs.length) return `<div class="empty">${LIVE.has(st(f)) || DONE.has(st(f)) ? 'No goals or cards yet.' : 'Goals and cards will appear here once the match starts.'}</div>`;
const home = f.teams.home.id;
const yellows = team => evs.filter(e => e.team.id === team && e.type === 'Card' && /^yellow/i.test(e.detail)).length;
const reds = team => evs.filter(e => e.team.id === team && e.type === 'Card' && /red|second yellow/i.test(e.detail)).length;
const sum = team => `π¨ ${yellows(team)} Β· π₯ ${reds(team)}`;
return `<div class="ev-sum"><span>${sum(home)}</span><span>Cards</span><span>${sum(f.teams.away.id)}</span></div>` + evs.map(e => {
const what = e.type === 'Goal'
? (e.detail === 'Own Goal' ? 'Own goal' : e.detail === 'Penalty' ? 'Penalty' : e.detail === 'Missed Penalty' ? 'Missed penalty' : 'Goal')
: (/second yellow/i.test(e.detail) ? 'Second yellow β red' : /red/i.test(e.detail) ? 'Red card' : 'Yellow card');
const sub = e.type === 'Goal' && e.assist?.name ? `${what} Β· assist ${esc(e.assist.name)}` : what;
const txt = `${eventIcon(e)} <b>${esc(e.player?.name || '')}</b><small>${sub}</small>`;
const min = `${e.time.elapsed}${e.time.extra ? '+' + e.time.extra : ''}'`;
return e.team.id === home
? `<div class="ev"><div class="h">${txt}</div><div class="min">${min}</div><div></div></div>`
: `<div class="ev"><div></div><div class="min">${min}</div><div>${txt}</div></div>`;
}).join('');
}
function lineupsHtml(f){
const L = f.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.team.id === f.teams.home.id) || L[0];
const away = L.find(l => l.team.id === f.teams.away.id) || L[1];
const evs = f.events || [];
const tags = pid => {
let t = '';
evs.forEach(e => {
if (e.player?.id !== pid) return;
if (e.type === 'Goal' && e.detail !== 'Missed Penalty') t += e.detail === 'Own Goal' ? 'β½<sup>OG</sup>' : 'β½';
if (e.type === 'Card') t += /second yellow/i.test(e.detail) ? 'π₯' : eventIcon(e); // first yellow is already shown
});
return t;
};
// grid "row:col": row 1 = goalkeeper. Home attacks downwards; away is mirrored so its keeper is at the bottom.
const rowsOf = (lu, flip) => {
const byRow = {};
(lu.startXI || []).forEach(({player:p}) => {
const [r, c] = String(p.grid || '').split(':').map(Number);
const row = r || ({G:1, D:2, M:3, F:4}[p.pos] || 3);
(byRow[row] = byRow[row] || []).push({ p, c: c || 0 });
});
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].sort((a,b) => a.c - b.c);
if (flip) ps = ps.reverse();
return `<div class="prow">${ps.map(({p}) => `<div class="pl"><div class="n">${esc(p.number ?? '')}</div><div class="nm">${esc(lastName(p.name))}</div><div class="tags">${tags(p.id)}</div></div>`).join('')}</div>`;
}).join('');
};
const subs = lu => (lu.substitutes || []).map(({player:p}) => `<div><span class="num">${esc(p.number ?? '')}</span>${esc(p.name)} ${tags(p.id)}</div>`).join('') || '<div>β</div>';
return `
<div class="form-head"><span>${esc(home.team.name)} Β· <b>${esc(home.formation || 'β')}</b></span><span><b>${esc(away.formation || 'β')}</b> Β· ${esc(away.team.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="form-head" style="margin-top:8px"><span>Coach: ${esc(home.coach?.name || 'β')}</span><span>Coach: ${esc(away.coach?.name || 'β')}</span></div>
<div class="subs"><div><h4>${esc(home.team.name)} subs</h4>${subs(home)}</div><div><h4>${esc(away.team.name)} subs</h4>${subs(away)}</div></div>`;
}
/* ββ 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;
}
/* Refresh button: fixtures, table and scorers for the competition on screen, plus tracked matches. */
async function refreshAll(){
if (busy) return;
if (WORKER_URL.includes('YOUR-WORKER')){ setupNeeded(); return; }
busy = true; $('rf').disabled = true; $('rf').classList.add('busy');
const lg = comp;
try {
const [fx, tb, sc] = await Promise.allSettled([getJson('/fixtures?league=' + lg), getJson('/standings?league=' + lg), getJson('/scorers?league=' + lg)]);
const d = { fix:[], table:[], scorers:[], ...(DATA[lg] || {}) };
if (fx.status === 'fulfilled'){ d.fix = fx.value.response || []; d.at = Date.parse(fx.value.updatedAt); d.warning = fx.value.warning; d.error = null; }
else d.error = fx.reason.message;
if (tb.status === 'fulfilled'){ d.table = tb.value.response?.[0]?.league?.standings?.[0] || []; d.tableError = null; } else d.tableError = tb.reason.message;
if (sc.status === 'fulfilled'){ d.scorers = sc.value.response || []; d.scorersError = null; } else d.scorersError = sc.reason.message;
DATA[lg] = d;
await refreshTracked(true);
} finally {
busy = false; $('rf').disabled = false; $('rf').classList.remove('busy');
renderAll(); statusLine();
}
}
async function loadMatch(id){
try {
const lg = tracked.find(t => t.id === id)?.league || allFixtures().find(x => x.fixture.id === id)?.league.id || comp;
const j = await getJson('/match?id=' + id + '&league=' + lg);
const fx = j.response?.[0];
const old = MATCH[id]?.fx;
if (fx){
MATCH[id] = { fx, at: Date.parse(j.updatedAt), next: j.nextRefreshIn };
if (old && (old.goals.home !== fx.goals.home || old.goals.away !== fx.goals.away)) flash(id);
} else if (!old) MATCH[id] = { at: Date.now(), error: j.warning || 'Match not found' };
} catch (e) {
if (!MATCH[id]?.fx) MATCH[id] = { at: Date.now(), error: e.message };
}
}
/* 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 f = MATCH[t.id]?.fx; return manual || !f || !DONE.has(st(f)); });
for (const t of due) await loadMatch(t.id);
// drop tracked matches that finished more than a day ago
const before = tracked.length;
tracked = tracked.filter(t => { const f = MATCH[t.id]?.fx; return !(f && DONE.has(st(f)) && Date.now() - when(f) > 30 * 3600e3); });
if (tracked.length !== before) store.set('fl_tracked', tracked);
scheduleTracked();
if (!manual){ renderAll(); statusLine(); }
}
function scheduleTracked(){
clearTimeout(trackTimer); nextTrackAt = null;
const pending = tracked.filter(t => { const f = MATCH[t.id]?.fx; return !f || !DONE.has(st(f)); });
if (!pending.length || document.hidden) return;
// ask again just after the Worker has new data, and never wait longer than 5 minutes
const soonest = Math.min(...pending.map(t => MATCH[t.id]?.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(id, lg){
if (!id) return;
if (isTracked(id)) tracked = tracked.filter(t => t.id !== id);
else { tracked.push({ id, league: String(lg), added: Date.now() }); loadMatch(id).then(() => { scheduleTracked(); renderAll(); }); }
store.set('fl_tracked', tracked);
scheduleTracked(); renderAll(); statusLine();
}
function untrack(id){
tracked = tracked.filter(t => t.id !== id);
store.set('fl_tracked', tracked);
scheduleTracked(); renderAll(); statusLine();
}
function flash(id){
setTimeout(() => document.querySelectorAll(`.m[data-id="${id}"]`).forEach(el => { el.classList.remove('flash'); void el.offsetWidth; el.classList.add('flash'); }), 50);
}
function statusLine(){
const d = DATA[comp], el = $('stxt');
if (!d){ el.className = 'stxt'; el.innerHTML = '<b>Ready</b> Β· tap Refresh'; return; }
const n = tracked.length, parts = [];
if (d.at) parts.push(`League data from ${tTime(new Date(d.at))}`);
if (n) parts.push(`tracking ${n} match${n > 1 ? 'es' : ''}`);
const problem = d.warning || d.error;
el.className = 'stxt' + (problem ? ' err' : '');
el.innerHTML = `<b>${problem ? (d.fix.length ? 'Using saved data' : 'Problem') : 'Up to date'}</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. <code>SETUP.md</code> has the click-by-click steps.</div>`;
}
/* countdowns on tracked cards + clock */
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(){
const n = new Date();
$('calM').textContent = n.toLocaleDateString('en-GB',{timeZone:TZ,month:'short'}).toUpperCase();
$('calD').textContent = n.toLocaleDateString('en-GB',{timeZone:TZ,day:'numeric'});
$('clk').textContent = n.toLocaleTimeString('en-GB',{timeZone:TZ});
tickCountdowns();
}
/* ββ EVENTS ββ */
document.addEventListener('click', e => {
const b = e.target.closest('[data-act]');
const cardEl = e.target.closest('.m[data-id]');
if (!b){ if (cardEl && !e.target.closest('#sheet')) openSheet(+cardEl.dataset.id); return; }
const id = +(b.dataset.id || cardEl?.dataset.id || 0);
const lg = b.dataset.lg || cardEl?.dataset.lg;
switch (b.dataset.act){
case 'track': toggleTrack(id, lg); break;
case 'untrack': untrack(id); break;
case 'details': openSheet(id); break;
case 'close': closeSheet(); break;
case 'stab': sheetTab = b.dataset.t; renderSheet(); break;
case 'refresh-match': loadMatch(sheetId).then(renderAll); break;
case 'round': {
const d = DATA[comp], rs = rounds(d.fix), i = rs.indexOf(roundSel[comp]) + +b.dataset.step;
if (i >= 0 && i < rs.length){ roundSel[comp] = rs[i]; renderMatches(); window.scrollTo(0, 0); }
break;
}
}
});
$('sheetBg').onclick = closeSheet;
document.addEventListener('keydown', e => { if (e.key === 'Escape') closeSheet(); });
$('rf').onclick = refreshAll;
document.querySelectorAll('.nav button').forEach(b => b.onclick = () => {
document.querySelectorAll('.nav button').forEach(x => x.classList.toggle('on', x === b));
document.querySelectorAll('.panel').forEach(p => p.classList.toggle('on', p.id === 'p-' + b.dataset.p));
window.scrollTo(0, 0);
});
document.querySelectorAll('.comp button').forEach(b => b.onclick = () => {
if (comp === b.dataset.comp) return;
comp = b.dataset.comp; store.set('fl_comp', comp);
renderAll(); statusLine();
if (!DATA[comp]) refreshAll();
});
document.addEventListener('visibilitychange', () => {
if (document.hidden){ clearTimeout(trackTimer); nextTrackAt = null; tickCountdowns(); }
else if (tracked.length) refreshTracked(false); // catch up straight away when you come back
});
/* start: one load of the league, then only tracked matches update by themselves */
setInterval(tickClock, 1000); tickClock();
renderAll();
refreshAll();
</script>
</body>
</html>
|