GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Websites and apps / youengineer-code-review / world-cup-knockout

Youengineer Code Review — World Cup Knockout and 2 more files

A JavaScript file that loads picks (`loadPicks`), saves picks (`savePicks`) and gets official winner (`getOfficialWinnerKey`). Served with the page at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.

363 lines of JavaScript and HTML from youengineer-code-review, in 3 files. Topic: Websites and apps. Section 2043 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Youengineer Code Review — World Cup Knockout Page render · youengineer-code-review / world-cup-knockout/index.html lines 1–37
  2. Script Grid render · youengineer-code-review / world-cup-knockout/script-grid.js lines 1–35
  3. Youengineer Code Review — World Cup Knockout render · youengineer-code-review / world-cup-knockout/script.js lines 1–291

Youengineer Code Review — World Cup Knockout Page

A web page. Published at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.

renderyouengineer-code-review / world-cup-knockout/index.html · lines 1–37 of 37 · Entry point

What it does
It draws its content. Side effects: changes the web page (DOM).
Why it exists in the grid workflow
README: "Download or clone the repo, then open `index.html` or `civilisation-atlas-v8/index.html` in a browser."
Inputs & outputs
Out: web page.
Downstream impact
Used directly by 1 file: Youengineer Code Review — Index Page (youengineer-code-review, https://ventusltd.github.io/youengineer-code-review/). Reached from 1 other entry point, including Civilisation Map (youengineer-code-review, https://ventusltd.github.io/youengineer-code-review/civilisation-map.html). It is itself an entry point, published at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.
What it achieves
The README says: Download or clone the repo, then open `index.html` or `civilisation-atlas-v8/index.html` in a browser.
Why it matters
Loaded by the Youengineer Code Review page at https://ventusltd.github.io/youengineer-code-review/.
Application
youengineer-code-review · world-cup-knockout · page
Uses
Youengineer Code Review — World Cup Knockout Style Sheet (stylesheet), Script Grid (script src)
Used by
linked from Youengineer Code Review — Index Page (link)
Produces
none declared
Defines here
none
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
youengineer-code-review@929a6d4a955524122e4fd18bd3c85ceaf1a86c56 world-cup-knockout/index.html:1-37 · blob cb4c45587b345d7ffeb5426957a200e5ddb566f3 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom · domain stage: unknown · users: none · canonical: unknown
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  <title>Knockout Predictor</title>
  <link rel="stylesheet" href="styles.css?v=2" />
  <script src="script-grid.js?v=2" defer></script>
</head>
<body>
  <main class="app-shell">
    <header class="topbar">
      <div>
        <p class="eyebrow">YouEngineer Football Lab</p>
        <h1>World Cup Knockout Predictor</h1>
      </div>
      <div class="actions">
        <button id="resetButton" type="button">Reset</button>
        <button id="fullscreenButton" type="button">Fullscreen</button>
      </div>
    </header>
    <nav class="round-nav" aria-label="Round navigation">
      <button data-round="round-32" type="button">Round of 32</button>
      <button data-round="round-16" type="button">Round of 16</button>
      <button data-round="quarter-finals" type="button">Quarter-finals</button>
      <button data-round="semi-finals" type="button">Semi-finals</button>
      <button data-round="final" type="button">Final</button>
    </nav>
    <section class="scoreboard" aria-live="polite">
      <div><span class="label">Predicted champion</span><strong id="championName">TBD</strong></div>
      <div><span class="label">Selections</span><strong id="selectionCount">0 / 31</strong></div>
    </section>
    <section class="bracket-wrap" aria-label="Knockout bracket"><div id="bracket" class="bracket"></div></section>
    <footer class="note">Current Round of 32 predictor snapshot. Not a live feed.</footer>
  </main>
</body>
</html>

Script Grid

A JavaScript file in the world cup knockout folder of Youengineer Code Review that sets focus (`setFocus`) and draws SVG graphics. Served with the page at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.

renderyouengineer-code-review / world-cup-knockout/script-grid.js · lines 1–35 of 35 · Entry point · pattern scrollRound (shared by 2 files)

What it does
It draws its content. Defines 11 functions or classes, including key, team, entrants, clearAfter, pick. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem); SVG drawing.
Downstream impact
Used directly by 1 file: Youengineer Code Review — World Cup Knockout Page (youengineer-code-review, https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/). Reached from 2 other entry points, including Civilisation Map (youengineer-code-review, https://ventusltd.github.io/youengineer-code-review/civilisation-map.html); Youengineer Code Review — Index Page (youengineer-code-review, https://ventusltd.github.io/youengineer-code-review/). It is itself an entry point, published at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.
What it achieves
It sets focus (`setFocus`) and is built from the clear after helper (`clearAfter`) and the pick step (`pick`). Defines `key`, `team`, `entrants` and 7 more. It responds to fullscreenchange, scroll and resize events.
Why it matters
Loaded by the World Cup Knockout page at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.
Application
youengineer-code-review · world-cup-knockout · script
Uses
none found
Used by
loaded by Youengineer Code Review — World Cup Knockout Page (script src)
Produces
key, team, entrants, clearAfter, pick, css, a, flag, nav, scrollRound, setFocus
Defines here
key, team, entrants, clearAfter, pick, css, a, flag, nav, scrollRound, setFocus
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
youengineer-code-review@929a6d4a955524122e4fd18bd3c85ceaf1a86c56 world-cup-knockout/script-grid.js:1-35 · blob c4b741416378a0ff4aca9afedaad1ae8ef3dd96c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unknown
"use strict";
const STORE="youengineer-wc-grid-v4";
document.head.insertAdjacentHTML("beforeend",'<style>.england-flag{position:relative;overflow:hidden;background:#fff;border:1px solid rgba(255,255,255,.45)}.england-flag:before,.england-flag:after{content:"";position:absolute;background:#cf142b}.england-flag:before{left:0;right:0;top:50%;height:28%;transform:translateY(-50%)}.england-flag:after{top:0;bottom:0;left:50%;width:28%;transform:translate  … [line shortened here: 419 characters; full line on GitHub]
const T={rsa:["South Africa","🇿🇦"],can:["Canada","🇨🇦"],ned:["Netherlands","🇳🇱"],mar:["Morocco","🇲🇦"],ger:["Germany","🇩🇪"],par:["Paraguay","🇵🇾"],fra:["France","🇫🇷"],swe:["Sweden","🇸🇪"],por:["Portugal","🇵🇹"],cro:["Croatia","🇭🇷"],esp:["Spain","🇪🇸"],aut:["Austria","🇦🇹"],usa:["United States","🇺🇸"],bih:["Bosnia and Herzegovina","🇧🇦"],bel:["Belgium","🇧🇪"],sen:["Senegal","🇸🇳"],bra:["Brazil","🇧🇷"],jpn:["Ja  … [line shortened here: 715 characters; full line on GitHub]
const M=[
["rsa","can","Sun 28 Jun, 20:00","FT",[0,1],"can"],["ned","mar","Tue 30 Jun, 02:00","FT",["1 (2p)","1 (3p)"],"mar"],["ger","par","Mon 29 Jun, 21:30","FT",["1 (3p)","1 (4p)"],"par"],["fra","swe","Tue 30 Jun, 22:00","FT",[3,0],"fra"],
["por","cro","Fri 3 Jul, 00:00","R32"],["esp","aut","Thu 2 Jul, 20:00","R32"],["usa","bih","Thu 2 Jul, 01:00","R32"],["bel","sen","Wed 1 Jul, 21:00","FT",[3,2],"bel"],
["bra","jpn","Mon 29 Jun, 18:00","FT",[2,1],"bra"],["civ","nor","Tue 30 Jun, 18:00","FT",[1,2],"nor"],["mex","ecu","Wed 1 Jul, 02:00","FT",[2,0],"mex"],["eng","cod","Wed 1 Jul, 17:00","FT",[2,1],"eng"],
["arg","cpv","Fri 3 Jul, 23:00","R32"],["aus","egy","Fri 3 Jul, 19:00","R32"],["sui","dza","Fri 3 Jul, 04:00","R32"],["col","gha","Sat 4 Jul, 02:30","R32"]];
const R=[
["round-32","Round of 32",16,M.map(m=>m[2])],
["round-16","Round of 16",8,["Sat 4 Jul, 18:00","Sat 4 Jul, 22:00","Mon 6 Jul, 20:00","Tue 7 Jul, 01:00","Sun 5 Jul, 21:00","Mon 6 Jul, 01:00","Tue 7 Jul, 17:00","Tue 7 Jul, 21:00"]],
["quarter-finals","Quarter-finals",4,["Thu 9 Jul, 21:00","Fri 10 Jul, 20:00","Sat 11 Jul, 22:00","Sun 12 Jul, 02:00"]],
["semi-finals","Semi-finals",2,["Tue 14 Jul, 20:00","Wed 15 Jul, 20:00"]],
["final","Final",1,["Sun 19 Jul, 20:00"]]
];
let picks=load(),pos=[],focus=false;
function key(k){return k&&T[k]?`${T[k][1]} ${T[k][0]}`:""} function load(){try{return JSON.parse(localStorage.getItem(STORE))||{}}catch{return{}}} function save(){localStorage.setItem(STORE,JSON.stringify(picks))}
function team(k){return k&&T[k]?{id:k,name:T[k][0],flag:T[k][1]}:null} function winner(r,i){return r===0&&M[i][5]?M[i][5]:picks[`r${r}m${i}`]||""}
function entrants(r,i){return r===0?[team(M[i][0]),team(M[i][1])]:[team(winner(r-1,i*2)),team(winner(r-1,i*2+1))]}
function clearAfter(r){Object.keys(picks).forEach(k=>{const m=k.match(/^r(\d+)/);if(m&&+m[1]>r)delete picks[k]})}
function pick(r,i,t){if(!t||(r===0&&M[i][5]))return;picks[`r${r}m${i}`]=t.id;clearAfter(r);save();render()}
function css(n,f){const v=parseFloat(getComputedStyle(document.documentElement).getPropertyValue(n));return Number.isFinite(v)?v:f}
function geometry(){const w=css("--card-w",220),h=css("--card-h",130),g=css("--round-gap",16),cg=css("--col-gap",56),p=css("--bracket-pad",12),to=css("--title-offset",38),xs=R.map((_,r)=>p+r*(w+cg));pos=[];pos[0]=M.map((_,i)=>({x:xs[0],y:p+to+i*(h+g)}));for(let r=1;r<R.length;r++){pos[r]=[];for(let i=0;i<R[r][2];i++){const a=pos[r-1][i*2],b=pos[r-1][i*2+1],cy=(a.y+h/2+b.y+h/2)/2;pos[r][i]={x:xs[r]  … [line shortened here: 506 characters; full line on GitHub]
function a(label,href){const x=document.createElement("a");x.textContent=label;x.href=href;x.target="_blank";x.rel="noopener noreferrer";return x}
function tools(t){const d=document.createElement("div");d.className="team-tools";if(!t)return d;const q=encodeURIComponent(`${t.name} football team World Cup 2026`);d.append(a("News",`https://news.google.com/search?q=${q}`));d.append(a("Wiki",`https://en.wikipedia.org/w/index.php?search=${encodeURIComponent(t.name+" national football team")}`));d.append(a("Images",`https://www.google.com/search?tb  … [line shortened here: 426 characters; full line on GitHub]
function flag(t){return `<span class="flag ${t.id==="eng"?"england-flag":""}">${t.id==="eng"?"":t.flag}</span>`}
function teamRow(r,i,t,sel,score){const wrap=document.createElement("div"),b=document.createElement("button");b.className="team-button";b.type="button";if(!t){b.disabled=true;b.innerHTML='<span class="flag">◇</span><span class="team-name">TBD</span><span></span>';wrap.append(b);return wrap}const locked=r===0&&M[i][5],s=sel===t.id;if(s)b.classList.add("selected");if(locked){b.classList.add("locked"  … [line shortened here: 631 characters; full line on GitHub]
function card(r,i){const [x,y]=entrants(r,i),sel=winner(r,i),m=document.createElement("article");m.className="match-card";m.style.left=pos[r][i].x+"px";m.style.top=pos[r][i].y+"px";if(r===4)m.classList.add("champion-card");const meta=document.createElement("div");meta.className="match-meta";meta.innerHTML=`<span>${R[r][3][i]||"TBD"}</span><span>${r===0?M[i][3]:"Predict"}</span>`;m.append(meta,team  … [line shortened here: 502 characters; full line on GitHub]
function lines(br,g){const s=document.createElementNS("http://www.w3.org/2000/svg","svg");s.classList.add("connector-layer");s.setAttribute("width",g.width);s.setAttribute("height",g.height);s.setAttribute("viewBox",`0 0 ${g.width} ${g.height}`);for(let r=0;r<R.length-1;r++)for(let i=0;i<R[r][2];i++){const m=pos[r][i],n=pos[r+1][Math.floor(i/2)],x1=m.x+g.w,y1=m.y+g.h/2,x2=n.x,y2=n.y+g.h/2,mid=x1+(  … [line shortened here: 600 characters; full line on GitHub]
function render(){const wrap=document.querySelector(".bracket-wrap"),br=document.getElementById("bracket"),sl=wrap.scrollLeft,st=wrap.scrollTop,g=geometry();br.innerHTML="";br.style.width=g.width+"px";br.style.height=g.height+"px";lines(br,g);R.forEach((r,ri)=>{const title=document.createElement("h2");title.className="round-title";title.id=r[0];title.dataset.round=r[0];title.textContent=r[1];title  … [line shortened here: 800 characters; full line on GitHub]
function nav(){const wrap=document.querySelector(".bracket-wrap"),titles=[...document.querySelectorAll(".round-title")];let active=titles[0]?.dataset.round;titles.forEach(t=>{if(t.offsetLeft-60<=wrap.scrollLeft)active=t.dataset.round});document.querySelectorAll(".round-nav button").forEach(b=>b.classList.toggle("active",b.dataset.round===active))}
function scrollRound(id){const w=document.querySelector(".bracket-wrap"),t=document.getElementById(id);if(t)w.scrollTo({left:Math.max(0,t.offsetLeft-12),behavior:"smooth"})}
function setFocus(v){focus=v;document.body.classList.toggle("focus-mode",v);document.getElementById("fullscreenButton").textContent=v?"Exit":"Fullscreen";setTimeout(render,120)}
document.getElementById("resetButton").onclick=()=>{picks={};save();render()};document.getElementById("fullscreenButton").onclick=async()=>{if(focus){if(document.fullscreenElement&&document.exitFullscreen)await document.exitFullscreen().catch(()=>{});setFocus(false);return}setFocus(true);if(document.documentElement.requestFullscreen)await document.documentElement.requestFullscreen().catch(()=>{})}  … [line shortened here: 789 characters; full line on GitHub]

Youengineer Code Review — World Cup Knockout

A JavaScript file that loads picks (`loadPicks`), saves picks (`savePicks`) and gets official winner (`getOfficialWinnerKey`). Served with the page at https://ventusltd.github.io/youengineer-code-review/world-cup-knockout/.

renderyouengineer-code-review / world-cup-knockout/script.js · lines 1–291 of 291 · Not reached from any entry point (candidate for review) · pattern makeLink (shared by 2 files)

What it does
It draws its content. Defines 18 functions or classes, including matchId, teamKey, loadPicks, savePicks, teamFromKey. Side effects: changes the web page (DOM); uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
README: "Update `script.js` when official fixtures, teams and match times are required."
Inputs & outputs
In: browser storage (getItem). Out: browser storage (setItem).
What it achieves
It matches id (`matchId`), loads picks (`loadPicks`) and saves picks (`savePicks`). The README says: Update `script.js` when official fixtures, teams and match times are required. It responds to click, fullscreenchange and scroll events.
Why it matters
No other file in the estate was found to import it.
Application
youengineer-code-review · world-cup-knockout · script
Uses
none found
Used by
none found
Produces
matchId, teamKey, loadPicks, savePicks, teamFromKey, getOfficialWinnerKey, getWinnerKey, getTeamsForMatch, pruneAfter, selectWinner, makeLink, renderTeamTools
Defines here
matchId, teamKey, loadPicks, savePicks, teamFromKey, getOfficialWinnerKey, getWinnerKey, getTeamsForMatch, pruneAfter, selectWinner, makeLink, renderTeamTools, renderTeamButton, renderMatch, render, updateNavState, scrollToRound, setFocusMode
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
youengineer-code-review@929a6d4a955524122e4fd18bd3c85ceaf1a86c56 world-cup-knockout/script.js:1-291 · blob 741c742134f22c9d6b88727bebc539310cbe947b · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, storage · domain stage: unknown · users: none · canonical: unreached_review
"use strict";

const STORAGE_KEY = "youengineer-world-cup-knockout-picks-v2";

const teams = {
  rsa: { name: "South Africa", flag: "🇿🇦" },
  can: { name: "Canada", flag: "🇨🇦" },
  ned: { name: "Netherlands", flag: "🇳🇱" },
  mar: { name: "Morocco", flag: "🇲🇦" },
  ger: { name: "Germany", flag: "🇩🇪" },
  par: { name: "Paraguay", flag: "🇵🇾" },
  fra: { name: "France", flag: "🇫🇷" },
  swe: { name: "Sweden", flag: "🇸🇪" },
  por: { name: "Portugal", flag: "🇵🇹" },
  cro: { name: "Croatia", flag: "🇭🇷" },
  esp: { name: "Spain", flag: "🇪🇸" },
  aut: { name: "Austria", flag: "🇦🇹" },
  usa: { name: "United States", flag: "🇺🇸" },
  bih: { name: "Bosnia and Herzegovina", flag: "🇧🇦" },
  bel: { name: "Belgium", flag: "🇧🇪" },
  sen: { name: "Senegal", flag: "🇸🇳" },
  bra: { name: "Brazil", flag: "🇧🇷" },
  jpn: { name: "Japan", flag: "🇯🇵" },
  civ: { name: "Ivory Coast", flag: "🇨🇮" },
  nor: { name: "Norway", flag: "🇳🇴" },
  mex: { name: "Mexico", flag: "🇲🇽" },
  ecu: { name: "Ecuador", flag: "🇪🇨" },
  eng: { name: "England", flag: "🏴" },
  cod: { name: "DR Congo", flag: "🇨🇩" },
  arg: { name: "Argentina", flag: "🇦🇷" },
  cpv: { name: "Cape Verde", flag: "🇨🇻" },
  aus: { name: "Australia", flag: "🇦🇺" },
  egy: { name: "Egypt", flag: "🇪🇬" },
  sui: { name: "Switzerland", flag: "🇨🇭" },
  dza: { name: "Algeria", flag: "🇩🇿" },
  col: { name: "Colombia", flag: "🇨🇴" },
  gha: { name: "Ghana", flag: "🇬🇭" }
};

const baseMatches = [
  { teams: [teams.rsa, teams.can], time: "Sun 28 Jun, 20:00", status: "FT", score: [0, 1], officialWinner: teamKey(teams.can) },
  { teams: [teams.ned, teams.mar], time: "Tue 30 Jun, 02:00", status: "R32" },
  { teams: [teams.ger, teams.par], time: "Mon 29 Jun, 21:30", status: "R32" },
  { teams: [teams.fra, teams.swe], time: "Tue 30 Jun, 22:00", status: "R32" },
  { teams: [teams.por, teams.cro], time: "Fri 3 Jul, 00:00", status: "R32" },
  { teams: [teams.esp, teams.aut], time: "Thu 2 Jul, 20:00", status: "R32" },
  { teams: [teams.usa, teams.bih], time: "Thu 2 Jul, 01:00", status: "R32" },
  { teams: [teams.bel, teams.sen], time: "Wed 1 Jul, 21:00", status: "R32" },
  { teams: [teams.bra, teams.jpn], time: "Mon 29 Jun, 18:00", status: "R32" },
  { teams: [teams.civ, teams.nor], time: "Tue 30 Jun, 18:00", status: "R32" },
  { teams: [teams.mex, teams.ecu], time: "Wed 1 Jul, 02:00", status: "R32" },
  { teams: [teams.eng, teams.cod], time: "Wed 1 Jul, 17:00", status: "R32" },
  { teams: [teams.arg, teams.cpv], time: "Fri 3 Jul, 23:00", status: "R32" },
  { teams: [teams.aus, teams.egy], time: "Fri 3 Jul, 19:00", status: "R32" },
  { teams: [teams.sui, teams.dza], time: "Fri 3 Jul, 04:00", status: "R32" },
  { teams: [teams.col, teams.gha], time: "Sat 4 Jul, 02:30", status: "R32" }
];

const roundMeta = [
  { id: "round-32", title: "Round of 32", count: 16, times: baseMatches.map((match) => match.time) },
  { id: "round-16", title: "Round of 16", count: 8, times: ["Sat 4 Jul, 18:00", "Sat 4 Jul, 22:00", "Mon 6 Jul, 20:00", "Tue 7 Jul, 01:00", "Sun 5 Jul, 21:00", "Mon 6 Jul, 01:00", "Tue 7 Jul, 17:00", "Tue 7 Jul, 21:00"] },
  { id: "quarter-finals", title: "Quarter-finals", count: 4, times: ["Thu 9 Jul, 21:00", "Fri 10 Jul, 20:00", "Sat 11 Jul, 22:00", "Sun 12 Jul, 02:00"] },
  { id: "semi-finals", title: "Semi-finals", count: 2, times: ["Tue 14 Jul, 20:00", "Wed 15 Jul, 20:00"] },
  { id: "final", title: "Final", count: 1, times: ["Sun 19 Jul, 20:00"] }
];

let picks = loadPicks();
let focusMode = false;

function matchId(roundIndex, matchIndex) {
  return `r${roundIndex}-m${matchIndex}`;
}

function teamKey(team) {
  return team ? `${team.flag} ${team.name}` : "";
}

function loadPicks() {
  try {
    return JSON.parse(localStorage.getItem(STORAGE_KEY)) || {};
  } catch {
    return {};
  }
}

function savePicks() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(picks));
}

function teamFromKey(key) {
  if (!key) return null;
  return Object.values(teams).find((team) => teamKey(team) === key) || null;
}

function getOfficialWinnerKey(roundIndex, matchIndex) {
  if (roundIndex !== 0) return "";
  return baseMatches[matchIndex]?.officialWinner || "";
}

function getWinnerKey(roundIndex, matchIndex) {
  return getOfficialWinnerKey(roundIndex, matchIndex) || picks[matchId(roundIndex, matchIndex)] || "";
}

function getTeamsForMatch(roundIndex, matchIndex) {
  if (roundIndex === 0) {
    return baseMatches[matchIndex].teams;
  }

  const leftWinner = teamFromKey(getWinnerKey(roundIndex - 1, matchIndex * 2));
  const rightWinner = teamFromKey(getWinnerKey(roundIndex - 1, matchIndex * 2 + 1));
  return [leftWinner, rightWinner];
}

function pruneAfter(roundIndex) {
  Object.keys(picks).forEach((id) => {
    const pickedRound = Number(id.match(/^r(\d+)-/)?.[1]);
    if (pickedRound > roundIndex) delete picks[id];
  });
}

function selectWinner(roundIndex, matchIndex, team) {
  if (!team || getOfficialWinnerKey(roundIndex, matchIndex)) return;
  picks[matchId(roundIndex, matchIndex)] = teamKey(team);
  pruneAfter(roundIndex);
  savePicks();
  render();
}

function makeLink(label, href) {
  const a = document.createElement("a");
  a.textContent = label;
  a.href = href;
  a.target = "_blank";
  a.rel = "noopener noreferrer";
  return a;
}

function renderTeamTools(team) {
  const tools = document.createElement("div");
  tools.className = "team-tools";
  if (!team) return tools;

  const q = encodeURIComponent(`${team.name} football team World Cup 2026`);
  const wiki = encodeURIComponent(`${team.name} national football team`);
  tools.appendChild(makeLink("News", `https://news.google.com/search?q=${q}`));
  tools.appendChild(makeLink("Wiki", `https://en.wikipedia.org/w/index.php?search=${wiki}`));
  tools.appendChild(makeLink("Images", `https://www.google.com/search?tbm=isch&q=${q}`));
  return tools;
}

function renderTeamButton(roundIndex, matchIndex, team, selectedKey, score) {
  const wrapper = document.createElement("div");
  const button = document.createElement("button");
  button.className = "team-button";
  button.type = "button";

  if (!team) {
    button.disabled = true;
    button.innerHTML = `<span class="flag">◇</span><span class="team-name">TBD</span><span></span>`;
    wrapper.appendChild(button);
    return wrapper;
  }

  const isOfficial = Boolean(getOfficialWinnerKey(roundIndex, matchIndex));
  const selected = selectedKey === teamKey(team);
  if (selected) button.classList.add("selected");
  if (isOfficial) button.classList.add("locked");
  if (isOfficial) button.disabled = true;

  const indicator = score !== undefined ? `${score}${selected ? " ✓" : ""}` : (selected ? "✓" : "›");
  button.innerHTML = `<span class="flag">${team.flag}</span><span class="team-name">${team.name}</span><span class="pick-indicator">${indicator}</span>`;
  button.addEventListener("click", () => selectWinner(roundIndex, matchIndex, team));
  wrapper.appendChild(button);
  wrapper.appendChild(renderTeamTools(team));
  return wrapper;
}

function renderMatch(roundIndex, matchIndex) {
  const [teamA, teamB] = getTeamsForMatch(roundIndex, matchIndex);
  const selectedKey = getWinnerKey(roundIndex, matchIndex);
  const card = document.createElement("article");
  card.className = "match-card";

  if (roundIndex === 4) card.classList.add("champion-card");

  const meta = document.createElement("div");
  meta.className = "match-meta";
  const base = baseMatches[matchIndex];
  const time = roundMeta[roundIndex].times[matchIndex] || "TBD";
  const status = roundIndex === 0 ? base.status : "Predict";
  meta.innerHTML = `<span>${time}</span><span>${status}</span>`;
  card.appendChild(meta);

  const scoreA = roundIndex === 0 ? base.score?.[0] : undefined;
  const scoreB = roundIndex === 0 ? base.score?.[1] : undefined;
  card.appendChild(renderTeamButton(roundIndex, matchIndex, teamA, selectedKey, scoreA));
  card.appendChild(renderTeamButton(roundIndex, matchIndex, teamB, selectedKey, scoreB));
  return card;
}

function render() {
  const bracket = document.getElementById("bracket");
  bracket.innerHTML = "";

  roundMeta.forEach((round, roundIndex) => {
    const column = document.createElement("section");
    column.className = "round-column";
    column.id = round.id;
    column.dataset.round = round.id;

    const title = document.createElement("h2");
    title.className = "round-title";
    title.textContent = round.title;
    column.appendChild(title);

    for (let i = 0; i < round.count; i++) {
      column.appendChild(renderMatch(roundIndex, i));
    }

    bracket.appendChild(column);
  });

  const champion = teamFromKey(getWinnerKey(4, 0));
  const officialCount = baseMatches.filter((match) => match.officialWinner).length;
  document.getElementById("championName").textContent = champion ? `${champion.flag} ${champion.name}` : "TBD";
  document.getElementById("selectionCount").textContent = `${Object.keys(picks).length + officialCount} / 31`;
  updateNavState();
}

function updateNavState() {
  const wrap = document.querySelector(".bracket-wrap");
  const columns = [...document.querySelectorAll(".round-column")];
  let activeId = columns[0]?.id;
  const left = wrap.scrollLeft;

  columns.forEach((column) => {
    if (column.offsetLeft - 80 <= left) activeId = column.id;
  });

  document.querySelectorAll(".round-nav button").forEach((button) => {
    button.classList.toggle("active", button.dataset.round === activeId);
  });
}

function scrollToRound(roundId) {
  const wrap = document.querySelector(".bracket-wrap");
  const target = document.getElementById(roundId);
  if (!wrap || !target) return;
  wrap.scrollTo({ left: target.offsetLeft - 12, behavior: "smooth" });
}

function setFocusMode(active) {
  focusMode = active;
  document.body.classList.toggle("focus-mode", active);
  document.getElementById("fullscreenButton").textContent = active ? "Exit" : "Fullscreen";
  setTimeout(updateNavState, 120);
}

document.getElementById("resetButton").addEventListener("click", () => {
  picks = {};
  savePicks();
  render();
});

document.getElementById("fullscreenButton").addEventListener("click", async () => {
  if (focusMode) {
    if (document.fullscreenElement && document.exitFullscreen) {
      await document.exitFullscreen().catch(() => {});
    }
    setFocusMode(false);
    return;
  }

  setFocusMode(true);
  if (document.documentElement.requestFullscreen) {
    await document.documentElement.requestFullscreen().catch(() => {});
  }
});

document.addEventListener("fullscreenchange", () => {
  if (!document.fullscreenElement && focusMode) setFocusMode(false);
});

document.querySelector(".round-nav").addEventListener("click", (event) => {
  const button = event.target.closest("button[data-round]");
  if (button) scrollToRound(button.dataset.round);
});

document.querySelector(".bracket-wrap").addEventListener("scroll", updateNavState, { passive: true });

render();