// Rôle : assemble l'authentification, les sections adressables et le cache local de Sokko TCG.
import "../../styles/cards-route.scss";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import { navigate } from "../../router/hashRouter.js";
import { clearCardsCache, readLatestCardsCache, writeCardsCache } from "./cardCache.js";
import { AccountPanel } from "./AccountPanel.jsx";
import { deleteCardsAccount, devLogin, loadCardsSession, loadCardsState, logoutCards } from "./cardsApi.js";
import { CardsAccount, CardsDashboardLayout } from "./CardsDashboard.jsx";
import { CardsHomePanel } from "./CardsHomePanel.jsx";
import { CollectionPanel } from "./CollectionPanel.jsx";
import { DailyPanel } from "./DailyPanel.jsx";
import { ExpeditionsPanel } from "./ExpeditionsPanel.jsx";
import { HistoryPanel } from "./HistoryPanel.jsx";
import { PackPanel } from "./PackPanel.jsx";
import { publishCardsReserve } from "./cardsReserve.js";
import { PrivacyNotice } from "./PrivacyNotice.jsx";
import { GuildPanel } from "./GuildPanel.jsx";
import { pendingQuestCount } from "./guildQuests.js";
import { RacePanel } from "./RacePanel.jsx";
import { ShopPanel } from "./ShopPanel.jsx";
import { TeamPanel } from "./TeamPanel.jsx";
import { TransfersPanel } from "./TransfersPanel.jsx";
// Le jeu, puis l'économie et les échanges, puis le journal : mêmes groupes séparés par un filet que l'administration.
const PLAYER_NAVIGATION = [["home", "guild", "packs", "collection"], ["shop", "transfers"], ["history", "account"]];
// Sections sans entrée de menu, ouvertes depuis une autre : le menu y désigne cette section parente.
const SUBSECTION_PARENTS = { daily: "guild", team: "guild", race: "guild", expeditions: "guild" };
const PLAYER_SECTIONS = new Set([...PLAYER_NAVIGATION.flat(), ...Object.keys(SUBSECTION_PARENTS)]);
// Ancienne adresse conservée pour les favoris : le recyclage vit désormais dans la Collection.
const PLAYER_SECTION_ALIASES = { recycling: "collection" };
const DISCORD_AUTH_PARAM = "cardsAuth";
// Réservée aux administrateurs : les joueurs ne téléchargent pas son code.
const AdminPanel = lazy(() => import("./admin/AdminPanel.jsx").then((module) => ({ default: module.AdminPanel })));
// React peut abandonner un rendu ou remonter la page : l'initialiseur ne fait que lire, le nettoyage attend un écran affiché.
function readDiscordAuthFailure() {
return new URLSearchParams(window.location.search).get(DISCORD_AUTH_PARAM) || "";
}
// Le cache est un confort hors connexion : un refus du stockage ne doit ni bloquer le jeu ni laisser une promesse rejetée.
function saveCardsCache(state, catalog) {
void writeCardsCache(state, catalog).catch(() => {});
}
function clearDiscordAuthFailure() {
const params = new URLSearchParams(window.location.search);
if (!params.has(DISCORD_AUTH_PARAM)) return;
params.delete(DISCORD_AUTH_PARAM);
const query = params.toString();
window.history.replaceState(window.history.state, "", `${window.location.pathname}${query ? `?${query}` : ""}${window.location.hash}`);
}
export function CardsPage({ siteContent, cardsConfig, playerSection = "", playerSubsection = "", adminMode = false, adminSection = "", adminSubsection = "" }) {
const content = siteContent.cards;
const [status, setStatus] = useState("loading");
const [state, setState] = useState(null);
const [cachedCatalog, setCachedCatalog] = useState(null);
const [offline, setOffline] = useState(false);
const [error, setError] = useState("");
const [authFailure] = useState(readDiscordAuthFailure);
const [busy, setBusy] = useState(false);
const [accountDeleted, setAccountDeleted] = useState(false);
const [privacyOpen, setPrivacyOpen] = useState(false);
const privacyPanelRef = useRef(null);
const resolvedSection = PLAYER_SECTION_ALIASES[playerSection] || playerSection;
const section = PLAYER_SECTIONS.has(resolvedSection) ? resolvedSection : "home";
const [transferDraft, setTransferDraft] = useState(null);
const clearTransferDraft = useCallback(() => setTransferDraft(null), []);
const catalog = cardsConfig.catalog || cachedCatalog;
const { loading: configLoading, enabled: configEnabled, error: configError } = cardsConfig;
// Le catalogue peut être remplacé par l'administration : le chargement initial ne doit pas se relancer pour autant.
const configCatalogRef = useRef(cardsConfig.catalog);
useEffect(() => { configCatalogRef.current = cardsConfig.catalog; }, [cardsConfig.catalog]);
// Une relecture de l'état ne s'applique que si rien de plus récent ne l'a dépassée : chaque mutation, déconnexion ou
// nouvelle lecture change la génération, et une réponse partie avant ce changement est ignorée.
const stateGeneration = useRef(0);
const latestMutation = useRef(0);
const refreshInFlight = useRef(null);
const reloadState = useCallback(async () => {
const generation = ++stateGeneration.current;
const next = await loadCardsState();
if (generation !== stateGeneration.current) return null;
setState(next);
return next;
}, []);
useEffect(() => {
let active = true;
async function load() {
if (configLoading) return;
let playerId = null;
try {
if (!configEnabled) throw new Error(configError || content.disabled);
const session = await loadCardsSession();
if (!active) return;
if (!session.authenticated) {
void clearCardsCache().catch(() => {});
setStatus("anonymous");
return;
}
playerId = session.player.id;
const next = await loadCardsState();
if (!active) return;
setState(next);
setStatus("ready");
setOffline(false);
saveCardsCache(next, configCatalogRef.current);
} catch (loadError) {
// Session reconnue : seule la copie de ce joueur peut s'afficher. Serveur injoignable : la dernière copie enregistrée.
const cached = await readLatestCardsCache(playerId).catch(() => null);
if (!active) return;
if (cached?.state && cached?.catalog) {
setState(cached.state);
setCachedCatalog(cached.catalog);
setOffline(true);
setStatus("ready");
setError(loadError.message);
} else {
setStatus(configEnabled ? "error" : "disabled");
setError(loadError.message);
}
}
}
void load();
return () => { active = false; };
}, [configLoading, configEnabled, configError, content.disabled]);
useEffect(() => {
if (status !== "loading") clearDiscordAuthFailure();
}, [status]);
// La pastille du menu suit chaque état reçu, sans attendre sa propre relecture.
useEffect(() => {
if (status === "anonymous") publishCardsReserve(null);
else if (status === "ready" && !offline && state?.recharge) publishCardsReserve(state.recharge);
}, [offline, state?.recharge, status]);
// Le panneau s'ouvre sous le login, parfois hors de l'écran.
useEffect(() => {
if (privacyOpen) privacyPanelRef.current?.scrollIntoView({ block: "nearest" });
}, [privacyOpen]);
useEffect(() => {
const nextOpeningAt = state?.recharge?.nextOpeningAt;
if (status !== "ready" || offline || !nextOpeningAt) return undefined;
const timeout = window.setTimeout(async () => {
try {
const next = await reloadState();
if (next) saveCardsCache(next, catalog);
} catch {
// Le prochain chargement ou une mutation resynchronisera l'état serveur.
}
}, Math.max(0, nextOpeningAt - Date.now()) + 250);
return () => window.clearTimeout(timeout);
}, [catalog, offline, reloadState, state?.recharge?.nextOpeningAt, status]);
// Les propositions arrivent sans notification : l'état se resynchronise au retour sur la page.
useEffect(() => {
if (status !== "ready" || offline) return undefined;
// Le focus et visibilitychange arrivent ensemble au retour sur l'onglet : une seule lecture part.
function refresh() {
if (globalThis.document.visibilityState !== "visible" || refreshInFlight.current) return;
refreshInFlight.current = reloadState()
.catch(() => {
// Le prochain retour ou la prochaine action resynchronisera l'état serveur.
})
.finally(() => { refreshInFlight.current = null; });
}
window.addEventListener("focus", refresh);
globalThis.document.addEventListener("visibilitychange", refresh);
return () => {
window.removeEventListener("focus", refresh);
globalThis.document.removeEventListener("visibilitychange", refresh);
};
}, [offline, reloadState, status]);
async function runMutation(action) {
if (offline) return null;
setBusy(true);
setError("");
// Une lecture partie avant ou pendant la mutation décrit un état que la mutation a peut-être déjà remplacé :
// la génération change au début et à la fin, et seule la dernière mutation lancée applique son résultat.
const mutation = ++latestMutation.current;
stateGeneration.current += 1;
try {
const result = await action();
const next = result?.state || result;
if (next?.player && mutation === latestMutation.current) {
setState(next);
saveCardsCache(next, catalog);
}
return result;
} catch (mutationError) {
setError(mutationError.message);
return null;
} finally {
stateGeneration.current += 1;
setBusy(false);
}
}
async function loginAsDev() {
setBusy(true);
setError("");
try {
await devLogin();
const next = await reloadState();
if (!next) return;
setStatus("ready");
saveCardsCache(next, catalog);
} catch (loginError) {
setError(loginError.message);
} finally {
setBusy(false);
}
}
if (cardsConfig.loading || status === "loading") return {content.loadingText} {error || content.disabled} {error} {content.eyebrow} {content.loginDescription} {content.discordUnavailable} {content.discordErrors[authFailure] || content.discordErrors.failed} {error} {content.account.deleted}{content.loadingTitle}
{content.disabledTitle}
{content.errorTitle}

{content.title}
{content.privacy.title}
Mode hors connexion : la dernière collection enregistrée est consultable, les actions sont suspendues.
} {error &&{error}
} >; // L'administration a son propre en-tête compact (titre, actualisation, joueur). if (adminMode && state.player.isAdmin) return{content.loadingText}
}>{content.eyebrow}
{content.description}
{content.admin.restrictedText}
{content.admin.backToGame}