import {initLanguage, t} from "./i18n.mjs"; import {dailyCalendar} from "./calendar.mjs"; import {normalize, dayKey, dailyMatch} from "./matches.mjs"; const el = id => document.getElementById(id); const maxAttempts = 6; const memory = new Map(); let match, key, day, state, selected; const field = []; function selectDaily() { day = dayKey(); match = dailyMatch(day); key = 'de-cabeca-v1-' + day; const scheduled = dailyCalendar[day]?.matchId === match.id ? dailyCalendar[day] : null; if (scheduled) key += "-" + match.id; const blank = { started: 0, ended: 0, hits: [] }; try { state = JSON.parse(localStorage.getItem(key)) ?? memory.get(key) ?? blank; } catch { state = memory.get(key) ?? blank; } state.guesses ??= {}; selected = null; const url = new URL(location.href); if (url.searchParams.has("partida")) { url.searchParams.delete("partida"); history.replaceState(null,"",url); } el("edition").textContent = t("Desafio diário") + " · " + day.split("-").reverse().slice(0,2).join("/"); const fixture = el("todayFixture"); fixture.hidden = !scheduled; fixture.textContent = scheduled ? t("Jogo do dia") + " · " + scheduled.fixture : ""; if (scheduled) fixture.href = scheduled.source; else fixture.removeAttribute("href"); el("competition").textContent = match.competition.split(" · ").map(part => t(part).replace(/^(\d+)ª rodada$/, (_, round) => t("{0}ª rodada", round))).join(" · "); el("team").textContent = match.team; el("score").textContent = match.score; el("opponent").textContent = match.opponent; el("matchDetails").textContent = match.details.split(" · ").map(part => t(part)).join(" · "); el("source").href = match.source; el("player").value = ""; feedback(""); makePitch(); tick(); render(); } function makePitch() { el("pitch").replaceChildren(); field.length = 0; for (const count of match.rows) { const row = document.createElement("div"); row.className = "row"; for (let i = 0; i < count; i++) { const player = match.players[field.length]; const index = field.length; const slot = document.createElement("button"); slot.type = "button"; slot.setAttribute("aria-controls","playerPanel"); slot.onclick = () => openPlayer(index); slot.className = "slot"; const marker = document.createElement("i"); const name = document.createElement("span"); const clue = document.createElement("small"); clue.className = "clue"; marker.textContent = player.shirt; if (player.scored) { const ball = document.createElement("span"); ball.className = "goal-ball"; ball.textContent = "⚽"; ball.setAttribute("aria-hidden","true"); marker.append(ball); } clue.textContent = t("{0} letras", player.letters); slot.append(marker,name,clue); field.push(slot); // The lineup lists the team’s right side first. The pitch is viewed with attack at the top. row.prepend(slot); } el("pitch").prepend(row); } } function save() { memory.set(key,state); try { localStorage.setItem(key,JSON.stringify(state)); } catch { /* The active page still retains progress. */ } } function formatTime(seconds) { return String(Math.floor(seconds / 60)).padStart(2,"0") + ":" + String(seconds % 60).padStart(2,"0"); } function elapsed() { return state.started ? Math.max(0, Math.floor(((state.ended || Date.now()) - state.started) / 1000)) : 0; } function tick() { el("timer").textContent = formatTime(elapsed()); if (day !== dayKey() && (!state.started || state.ended)) selectDaily(); } function guessesFor(index) { return state.guesses[index] ?? []; } function unavailable(index) { return state.hits.includes(index) || guessesFor(index).length >= maxAttempts; } export function grade(guess, answer) { const remaining = [...answer]; const marks = Array.from(guess, (letter, index) => { if (letter !== answer[index]) return "absent"; remaining[index] = ""; return "exact"; }); return marks.map((mark, index) => { if (mark === "exact") return mark; const target = remaining.indexOf(guess[index]); if (target < 0) return mark; remaining[target] = ""; return "present"; }); } function renderPlayer() { const active = selected !== null && !state.ended; el("ready").hidden = active || Boolean(state.ended); el("playerPanel").hidden = !active; if (!active) return; const player = match.players[selected]; const guesses = guessesFor(selected); const groups = player.letters.split(",").map(Number); const answer = normalize(player.name); const locked = unavailable(selected); const draft = locked ? "" : normalize(el("player").value).replace(/[^a-z]/g,"").slice(0,answer.length); el("guess").hidden = locked; el("playerTitle").textContent = t("Camisa {0}", player.shirt); el("attempts").textContent = state.hits.includes(selected) ? t("{0} confirmado!", player.name) : locked ? t("Sem palpites restantes · {0}", player.name) : t("{0} de {1} tentativas usadas", guesses.length, maxAttempts); const grid = el("tiles"); grid.replaceChildren(); for (let round = 0; round < maxAttempts; round++) { const isDraft = !locked && round === guesses.length; const guess = guesses[round] ?? ""; const marks = guess ? grade(guess,answer) : []; const row = document.createElement("div"); row.className = "tile-row"; const labels = []; let index = 0; for (const length of groups) { const group = document.createElement("div"); group.className = "tile-group"; for (let letter = 0; letter < length; letter++, index++) { const tile = document.createElement("span"); tile.className = "tile " + (marks[index] ?? ""); tile.textContent = ((isDraft ? draft[index] : guess[index]) ?? "").toUpperCase(); if (guess) labels.push(tile.textContent + " " + t({exact:"No lugar certo",present:"Em outro lugar",absent:"Fora do nome"}[marks[index]])); group.append(tile); } row.append(group); } row.setAttribute("role", "img"); row.setAttribute("aria-label", guess ? t("Palpite {0}. {1}", round + 1, labels.join(", ")) : t(isDraft && draft ? "Tentativa {0} em edição" : "Tentativa {0} em branco", round + 1)); if (locked && !guess) break; grid.append(row); } } function render() { const done = Boolean(state.ended); el("finish").hidden = !state.started || done; el("result").hidden = !done; el("count").firstChild.textContent = state.hits.length; el("progress").value = state.hits.length; field.forEach((slot, i) => { const player = match.players[i]; const found = state.hits.includes(i); const missed = !found && (done || unavailable(i)); slot.className = "slot" + (found ? " hit" : missed ? " missed" : ""); slot.disabled = done; slot.setAttribute("aria-pressed", String(selected === i)); slot.setAttribute("aria-label", t("Camisa {0}", player.shirt) + ", " + (found || missed ? player.name : t("{0} letras", player.letters)) + (player.scored ? ", " + t("marcou gol") : "")); slot.children[1].textContent = found || missed ? player.name : ""; }); renderPlayer(); if (done) { el("resultTitle").textContent = state.hits.length === 11 ? t("Escalação completa!") : t("Fim de jogo"); el("resultText").textContent = t("Você lembrou {0} de 11 titulares. Tempo usado {1}.", state.hits.length, formatTime(elapsed())); } } function openPlayer(index) { if (state.ended) return; if (!state.started) { state.started = Date.now(); save(); } if (selected !== index) el("player").value = ""; selected = index; feedback(""); render(); if (unavailable(index)) { el("playerTitle").setAttribute("tabindex","-1"); el("playerTitle").focus(); } else { el("player").focus(); } } function feedback(message) { el("feedback").textContent = message; } function end(time = Date.now()) { if (state.ended) return; state.ended = time; save(); feedback(""); render(); } el("player").addEventListener("input",renderPlayer); el("guess").addEventListener("submit",event => { event.preventDefault(); if (state.ended || selected === null || unavailable(selected)) return; const input = el("player"); const guess = normalize(input.value); const player = match.players[selected]; const answer = normalize(player.name); const correct = player.aliases.some(alias => normalize(alias) === guess); const previous = guessesFor(selected); if (!correct && (guess.length !== answer.length || !/^[a-z]+$/.test(guess))) { feedback(t("Use {0} letras seguindo o formato do nome. O palpite não foi descontado.", player.letters)); input.select(); return; } if (previous.includes(guess)) { feedback(t("Você já fez esse palpite para esta camisa.")); input.select(); return; } state.guesses[selected] = [...previous, correct ? answer : guess]; if (correct) state.hits.push(selected); input.value = ""; save(); if (match.players.every((_,index) => unavailable(index))) { end(); el("share").focus(); return; } render(); if (unavailable(selected)) { feedback(correct ? t("{0} confirmado! Escolha outra camisa.", player.name) : t("Você usou as seis tentativas. Escolha outra camisa.")); field[selected].focus(); } else { feedback(t("Confira as pistas e tente outra vez.")); input.focus(); } }); el("finish").onclick = () => { if (window.confirm(t("Encerrar a tentativa e revelar a escalação?"))) { end(); tick(); el("share").focus(); } }; function shareText() { const url = new URL(location.href); url.search = ""; const played = formatTime(elapsed()); const blocks = "🟩".repeat(state.hits.length) + "⬜".repeat(11 - state.hits.length); return "⚽ De Cabeça\n" + match.team + " × " + match.opponent + " (" + match.details.slice(6,10) + ")\n" + blocks + "\n" + t("Acertei {0}/11 em {1}. Consegue bater?", state.hits.length, played) + "\n" + url; } el("share").onclick = () => window.open("https://wa.me/?text=" + encodeURIComponent(shareText()),"_blank","noopener,noreferrer"); el("copy").onclick = async () => { try { await navigator.clipboard.writeText(shareText()); feedback(t("Resultado copiado.")); } catch { window.prompt(t("Copie seu resultado:"),shareText()); } }; initLanguage(); selectDaily(); setInterval(tick,250);