import { api, adminApi } from "./js/api.js";
const state = {
isAuthenticated: false,
authMode: "login",
me: null,
phase: null,
counts: null,
mySuggestions: [],
allSuggestions: [],
myVotes: [],
results: []
};
const $ = (id) => document.getElementById(id);
const toastEl = $("toast");
function toast(msg, isError = false) {
if (!toastEl) return;
toastEl.textContent = msg;
toastEl.classList.remove("hidden");
toastEl.classList.toggle("error", isError);
setTimeout(() => toastEl.classList.add("hidden"), 2000);
}
function setAuthUI(isAuthed) {
const main = document.querySelector("main");
const statusBar = document.querySelector(".status-bar");
const authCard = $("auth-card");
[main, statusBar].forEach(el => el?.classList.toggle("hidden", !isAuthed));
if (authCard) authCard.classList.toggle("hidden", isAuthed);
const adminToggle = $("admin-toggle");
if (adminToggle) adminToggle.classList.toggle("hidden", !isAuthed || !state.me?.isAdmin);
if (!isAuthed) {
const adminCard = $("admin-card");
if (adminCard) adminCard.classList.add("hidden");
}
}
function setAuthMode(mode) {
state.authMode = mode;
document.querySelectorAll(".auth-form").forEach(form => {
form.classList.toggle("hidden", form.dataset.mode !== mode);
});
document.querySelectorAll("[data-auth-tab]").forEach(btn => {
btn.classList.toggle("active", btn.dataset.authTab === mode);
});
}
function clearUserState() {
state.me = null;
state.phase = null;
state.counts = null;
state.mySuggestions = [];
state.allSuggestions = [];
state.myVotes = [];
state.results = [];
const adminCard = $("admin-card");
if (adminCard) adminCard.classList.add("hidden");
}
function handleAuthError(err) {
if (err?.status === 401) {
clearUserState();
state.isAuthenticated = false;
setAuthUI(false);
return true;
}
toast(err?.message || "Unexpected error", true);
return false;
}
async function loadState() {
const [me, stateData] = await Promise.all([api.me(), api.state()]);
state.isAuthenticated = true;
state.me = me;
state.phase = stateData.currentPhase;
state.counts = stateData;
setAuthUI(true);
renderWelcome();
renderPhasePill();
renderCounts();
}
async function loadSuggestData() {
if (state.phase !== "Suggest") return;
state.mySuggestions = await api.mySuggestions();
renderMySuggestions();
}
async function loadRevealData() {
if (state.phase === "Reveal" || state.phase === "Vote" || state.phase === "Results") {
state.allSuggestions = await api.allSuggestions();
renderAllSuggestions();
}
}
async function loadVoteData() {
if (state.phase !== "Vote") return;
state.myVotes = await api.myVotes();
renderVotes();
}
async function loadResults() {
if (state.phase !== "Results") return;
state.results = await api.results();
renderResults();
}
function renderPhasePill() {
$("phase-pill").textContent = state.phase || "Loading…";
document.querySelectorAll(".phase-view").forEach((el) => el.classList.add("hidden"));
const viewMap = {
Suggest: "suggest-view",
Reveal: "reveal-view",
Vote: "vote-view",
Results: "results-view"
};
const id = viewMap[state.phase];
if (id) $(id).classList.remove("hidden");
const phaseSelect = $("phase-select");
if (phaseSelect && !phaseSelect.dataset.userEditing) {
phaseSelect.value = state.phase || "Suggest";
}
}
function renderCounts() {
if (!state.counts) return;
$("counts").textContent = `Players: ${state.counts.players} • Suggestions: ${state.counts.suggestions} • Votes: ${state.counts.votes}`;
}
function renderWelcome() {
const el = $("welcome-text");
if (!el) return;
const name = state.me?.displayName?.trim() || state.me?.username || "Player";
el.textContent = `Welcome, ${name}!`;
}
function renderMySuggestions() {
const wrap = $("my-suggestions");
if (!wrap) return;
wrap.innerHTML = "";
state.mySuggestions.forEach((s) => wrap.appendChild(buildCard(s, { showAuthor: false, allowDelete: true })));
}
function renderAllSuggestions() {
const list = $("all-suggestions");
if (!list) return;
list.innerHTML = "";
state.allSuggestions.forEach((s) => list.appendChild(buildCard(s, { showAuthor: true })));
}
function renderVotes() {
const list = $("vote-list");
if (!list) return;
list.innerHTML = "";
const votesMap = Object.fromEntries(state.myVotes.map((v) => [v.suggestionId, v.score]));
state.allSuggestions.forEach((s) => {
const li = buildCard(s, { showAuthor: true });
const current = votesMap[s.id] ?? 0;
const footer = document.createElement("div");
footer.className = "vote-controls";
footer.innerHTML = `
${current}`;
li.querySelector(".card-body").appendChild(footer);
list.appendChild(li);
});
list.querySelectorAll("input[type=range]").forEach((input) => {
input.addEventListener("input", (e) => {
const val = Number(e.target.value);
$("score-" + e.target.dataset.id).textContent = val;
});
input.addEventListener("change", async (e) => {
const suggestionId = Number(e.target.dataset.id);
const score = Number(e.target.value);
try {
await api.vote(suggestionId, score);
toast("Saved vote");
await loadVoteData();
} catch (err) {
toast(err.message, true);
}
});
});
}
function renderResults() {
const container = $("results-list");
container.innerHTML = "";
const table = document.createElement("table");
table.className = "results-table";
table.innerHTML = `
Rank
Game
Author
Votes
Avg
Total
Links
${s.genre}
` : ""} ${s.description ? `${s.description}
` : ""}${title || ""}