document.addEventListener("DOMContentLoaded", async () => { "use strict";
const $ = (s,c) => (c||document).querySelector(s);
function $$(x,y,z,a){a=(z||document).querySelectorAll(x);if(typeof y=="function")[].forEach.call(a,y);return a}
function m(a,b,c){c=document;b=c.createElement(b||"p");b.innerHTML=a.trim();for(a=c.createDocumentFragment();c=b.firstChild;)a.appendChild(c);return a.firstChild}
const board = [];
const boardEl = document.createElement("table");
$("#board").appendChild(boardEl);
for (let i=0;i<6;i++) {
let o = "
";
for (let j=0;j<6;j++) o += ` | `;
o = m(o, "tbody");
boardEl.appendChild(o);
board.push(o);
}
function setRow(r, s) {
s = s.toUpperCase();
$$("td", (e,i) => e.innerHTML = s.charAt(i)||" ", r);
}
function setRowState(r, s) {
$$("td", (e,i) => {
e.classList.add({
"=":"found",
"-":"present",
" ":"absent"
}[s.charAt(i)]);
}, r);
}
let done = false;
let currentRow = 0;
let currentStr = "";
function processKey(key) {
if (done || !/^([a-z]|enter|bspc)$/.test(key)) return;
if (key === "enter") {
return tryWord();
} else if (key === "bspc") {
currentStr = currentStr.slice(0,-1);
} else {
currentStr += key;
currentStr = currentStr.slice(0,6);
}
setRow(board[currentRow], currentStr);
}
async function tryWord() {
if (currentStr.length !== 6) return alert("Guesses must use all six letters!");
const r = await fetch("/guess/"+currentStr).then(r => r.json());
if (r.result === false) return alert("Not in word list!");
setRowState(board[currentRow], r.result);
if (r.result === "======") {
setTimeout(() => alert("Congratulations!"));
done = true;
return;
}
currentStr = "";
currentRow++;
if (currentRow === 6) {
setTimeout(() => alert("Better luck next time!"));
done = true;
}
}
document.addEventListener("keydown", e =>
e.ctrlKey || e.altKey || e.metaKey ||
processKey(e.key.toLowerCase()
.replace("backspace", "bspc")));
$$("td[data-key]", k => k.addEventListener("click",
() => processKey(k.dataset.key)));
//if ("serviceWorker" in navigator) {
// navigator.serviceWorker.register("sw.js")
// .then(() => console.log("Service worker registered"));
//}
});