// view-admin-game.jsx — Vue Admin KODAMA façon « 🌳 La Cabane » :
// liste des jeux à gauche, fiche détaillée à droite (Informations · Chiffres · Productions).
// 3 mises en page au choix via Tweaks : liste+fiche, fiche à onglets, sélecteur en haut.

const ADMIN_NAV_KEY = "kodama-admin-nav-v2";

function euro(n) {
  if (n == null || n === "" || isNaN(n)) return "—";
  return Number(n).toLocaleString("fr-FR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + " €";
}

// Jeux + agrégats calculés depuis les prints / productions
function buildGameRows(db) {
  const map = {};
  const blank = (id, name) => ({ id, name, pctDone: null, catalogue: null, releaseDate: null, yearFR: null, ppttc: null, ppht: null,
    note: "", image: null, quoteFiles: [], presseFr: "", presseEn: "", bgg: "", prints: [], totalQty: 0, activeQty: 0, activeCount: 0, partnerIds: {} });
  (db.games || []).forEach((g) => { map[g.id] = { ...blank(g.id, g.name), ...g, prints: [], totalQty: 0, activeQty: 0, activeCount: 0, partnerIds: {} }; });
  db.prints.forEach((pr) => {
    if (!map[pr.gameId]) map[pr.gameId] = blank(pr.gameId, pr.game);
    map[pr.gameId].prints.push(pr);
  });
  const printGame = {};
  db.prints.forEach((pr) => { printGame[pr.id] = pr.gameId; });
  db.productions.forEach((p) => {
    const g = map[printGame[p.printId]];
    if (!g) return;
    g.totalQty += p.qty || 0;
    g.partnerIds[p.partnerId] = true;
    if (p.statut !== "Terminé") { g.activeQty += p.qty || 0; g.activeCount++; }
  });
  // Liste principale : uniquement les jeux avec une production en cours — le reste va au « catalogue »
  const rows = Object.values(map).filter((g) => g.activeCount > 0)
    .sort((a, b) => a.name.localeCompare(b.name, "fr"));
  const catalog = Object.values(map).filter((g) => g.activeCount === 0)
    .sort((a, b) => a.name.localeCompare(b.name, "fr"));
  return { rows, catalog };
}

function setGameField(update, push, game, key, value, label) {
  update((d) => {
    const g = (d.games || []).find((x) => x.id === game.id);
    if (!g) return;
    g[key] = value;
    if (key === "ppttc") { g.ppht = (value == null || value === "" || isNaN(value)) ? null : Math.round((Number(value) / 1.2) * 100) / 100; }
    d.log.unshift({ ts: nowStamp(), actor: "KODAMA (admin)", action: "Fiche jeu modifiée", detail: `${game.name} — ${label}` });
  });
  push("Modification enregistrée dans Airtable.");
}

// ——— Lignes de la fiche (label à gauche, champ à droite — à la Airtable) ———
function FicheRow({ label, children }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "190px 1fr", gap: 16, alignItems: "center", padding: "7px 0" }}>
      <div style={{ fontSize: 12.5, fontWeight: 700, color: K.sub }}>{label}</div>
      <div style={{ minWidth: 0 }}>{children}</div>
    </div>
  );
}

const ficheInput = { fontFamily: K.font, fontSize: 13.5, fontWeight: 600, color: K.ink, background: "#FAF9F7",
  border: `1.5px solid ${K.line}`, borderRadius: 9, padding: "7px 12px", width: "100%", boxSizing: "border-box" };

function FicheSelect({ value, options, onChange, placeholder }) {
  return (
    <select value={value || ""} onChange={(e) => onChange(e.target.value || null)} style={{ ...ficheInput, cursor: "pointer", maxWidth: 420 }}>
      <option value="">{placeholder || "—"}</option>
      {options.map((o) => <option key={o} value={o}>{o}</option>)}
    </select>
  );
}

function FicheDate({ value, onChange }) {
  return <input type="date" value={value ? value.slice(0, 10) : ""} onChange={(e) => onChange(e.target.value || null)} style={{ ...ficheInput, maxWidth: 200, cursor: "pointer" }} />;
}

function FicheMoney({ value, onChange }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState("");
  const save = () => { setEditing(false); const v = draft === "" ? null : Number(String(draft).replace(",", ".")); if (!isNaN(v ?? 0) && v !== value) onChange(v); };
  if (editing) return (
    <input autoFocus value={draft} onChange={(e) => setDraft(e.target.value)} onBlur={save}
      onKeyDown={(e) => { if (e.key === "Enter") save(); if (e.key === "Escape") setEditing(false); }}
      style={{ ...ficheInput, maxWidth: 140, fontFamily: K.mono }} />
  );
  return (
    <button onClick={() => { setDraft(value == null ? "" : String(value)); setEditing(true); }} title="Cliquer pour modifier"
      style={{ ...ficheInput, maxWidth: 200, textAlign: "left", cursor: "text", fontSize: 15, fontWeight: 800 }}>{euro(value)}</button>
  );
}

function FicheNote({ value, onChange }) {
  const [draft, setDraft] = React.useState(value || "");
  React.useEffect(() => setDraft(value || ""), [value]);
  const dirty = draft !== (value || "");
  return (
    <div>
      <textarea className="k-textarea" rows={3} value={draft} placeholder="Aucune note." onChange={(e) => setDraft(e.target.value)} style={{ fontSize: 13 }}></textarea>
      {dirty && <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <button className="k-btn k-btn-primary k-btn-sm" onClick={() => onChange(draft)}>Enregistrer la note</button>
        <button className="k-btn k-btn-ghost k-btn-sm" onClick={() => setDraft(value || "")}>Annuler</button>
      </div>}
    </div>
  );
}

function FicheUrl({ value, onChange, label }) {
  const [editing, setEditing] = React.useState(false);
  const [draft, setDraft] = React.useState("");
  const save = () => { setEditing(false); const v = draft.trim() ? extUrl(draft.trim()) : ""; if (v !== (value || "")) onChange(v); };
  if (editing) return (
    <input autoFocus className="k-input" value={draft} placeholder="https://…" onChange={(e) => setDraft(e.target.value)} onBlur={save}
      onKeyDown={(e) => { if (e.key === "Enter") save(); if (e.key === "Escape") setEditing(false); }}
      style={{ width: 220, padding: "4px 8px", fontSize: 11.5, borderRadius: 7, fontFamily: K.mono }} />
  );
  if (value) return (
    <span style={{ display: "inline-flex", gap: 7, alignItems: "center" }}>
      <ExtLink href={value} style={{ fontSize: 12.5 }}>↗ {label}</ExtLink>
      <button title="Modifier le lien" onClick={() => { setDraft(value); setEditing(true); }} style={{ background: "none", border: "none", cursor: "pointer", color: K.sub, fontSize: 12, padding: 0 }}>✎</button>
    </span>
  );
  return (
    <button onClick={() => { setDraft(""); setEditing(true); }}
      style={{ background: "none", border: "none", borderBottom: `1.5px dashed ${K.line}`, cursor: "text", padding: "2px 1px", fontSize: 12, color: K.sub, fontFamily: K.font }}>+ {label}</button>
  );
}

function PctBar({ pct }) {
  const v = pct == null ? null : Math.max(0, Math.min(100, pct));
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
      <div style={{ flex: 1, maxWidth: 420, height: 10, borderRadius: 99, background: "#EFECE7", overflow: "hidden" }}>
        <div style={{ width: (v || 0) + "%", height: "100%", borderRadius: 99, background: v === 100 ? K.green : K.grad, transition: "width .3s" }}></div>
      </div>
      <span className="k-mono" style={{ fontSize: 12.5, fontWeight: 600, color: v === 100 ? K.green : K.ink }}>{v == null ? "—" : v + "%"}</span>
    </div>
  );
}

// ——— Sections de la fiche ———
function GameInfoSection({ game, update, push }) {
  const basic = null; // résumé BASIC DATA passé via props plus bas si dispo
  const set = (key, label) => (v) => setGameField(update, push, game, key, v, label);
  return (
    <div className="k-card" style={{ marginTop: 12, padding: "16px 22px 14px" }}>
      <div className="k-round" style={{ fontSize: 16, fontWeight: 700, marginBottom: 8 }}>Informations</div>
      <FicheRow label="Catalogue Export"><FicheSelect value={game.catalogue} options={GAME_CATALOGUES} onChange={set("catalogue", "catalogue export")} placeholder="Choisir un catalogue…" /></FicheRow>
      <FicheRow label="Année de Sortie FR"><FicheSelect value={game.yearFR} options={GAME_YEARS} onChange={set("yearFR", "année de sortie FR")} placeholder="Choisir une année…" /></FicheRow>
      <FicheRow label="PPTTC"><FicheMoney value={game.ppttc} onChange={set("ppttc", "PPTTC")} /></FicheRow>
      <FicheRow label="PPHT"><span style={{ fontSize: 13.5, fontWeight: 600, color: K.sub }}>{euro(game.ppht)} <span style={{ fontWeight: 400, fontSize: 11.5 }}>(calculé)</span></span></FicheRow>
      <FicheRow label="Date de sortie 🚀"><FicheDate value={game.releaseDate} onChange={set("releaseDate", "date de sortie")} /></FicheRow>
      <FicheRow label="% Done"><PctBar pct={game.pctDone} /></FicheRow>
      <FicheRow label="Liens">
        <div style={{ display: "flex", gap: 18, flexWrap: "wrap", alignItems: "center" }}>
          <FicheUrl value={game.bgg} label="Page BGG" onChange={set("bgg", "page BGG")} />
          <FicheUrl value={game.presseFr} label="Drive Presse FR" onChange={set("presseFr", "drive presse FR")} />
          <FicheUrl value={game.presseEn} label="Drive Presse EN" onChange={set("presseEn", "drive presse EN")} />
        </div>
      </FicheRow>
      {game.quoteFiles.length > 0 && (
        <FicheRow label="Quote">
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            {game.quoteFiles.map((f) => <ExtLink key={f.name} href={f.url} style={{ fontSize: 12.5 }}>↓ {f.name}</ExtLink>)}
          </div>
        </FicheRow>
      )}
      <FicheRow label="Note"><FicheNote value={game.note} onChange={set("note", "note")} /></FicheRow>
    </div>
  );
}

function BigNum({ label, value, sub, bg, fg, big }) {
  return (
    <div className="k-card" style={{ padding: big ? "16px 22px" : "13px 18px", background: bg || "#FFF", border: "none" }}>
      <div style={{ fontSize: 11.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: fg || K.sub }}>{label}</div>
      <div className="k-round" style={{ fontSize: big ? 38 : 27, fontWeight: 700, color: fg || K.ink, lineHeight: 1.15, marginTop: 2 }}>{value}</div>
      {sub ? <div style={{ fontSize: 12, color: fg || K.sub, opacity: .8 }}>{sub}</div> : null}
    </div>
  );
}

function GameStatsSection({ game, basic }) {
  const nf = (n) => (n || 0).toLocaleString("fr-FR");
  const partnerCount = Object.keys(game.partnerIds).length;
  const valeur = game.ppht != null ? game.totalQty * game.ppht : null;
  return (
    <div style={{ marginTop: 12 }}>
      <BigNum label="Total imprimé (export)" value={nf(game.totalQty) + " ex."} sub={game.prints.length + " print" + (game.prints.length > 1 ? "s" : "")} bg={K.blueBg} fg={K.blueS} big={true} />
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 10, marginTop: 10 }}>
        <BigNum label="En production" value={nf(game.activeQty) + " ex."} sub={game.activeCount + " production" + (game.activeCount > 1 ? "s" : "") + " en cours"} />
        <BigNum label="Partenaires" value={partnerCount} sub="ayant commandé ce jeu" />
        <BigNum label="Valeur prix public HT" value={valeur == null ? "—" : Math.round(valeur).toLocaleString("fr-FR") + " €"} sub={valeur == null ? "renseignez le PPTTC" : nf(game.totalQty) + " ex. × " + euro(game.ppht)} />
      </div>
      <p style={{ fontSize: 11.5, color: K.sub, margin: "8px 2px 0" }}>Chiffres calculés depuis les productions export du portail — les ventes France (Entrées / Sorties) ne sont pas encore connectées.</p>
      {basic && (
        <div className="k-card" style={{ marginTop: 10, padding: "12px 18px", display: "flex", gap: 26, flexWrap: "wrap" }}>
          {[["EAN 13", basic.ean13], ["EAN 14", basic.ean14], ["Poids unité", basic.gameWeight ? basic.gameWeight + " kg" : null], ["Jeux / carton", basic.unitsPerCarton], ["Jeux / palette", basic.gamesPerPallet]].map(([k, v]) => (
            <div key={k}>
              <div style={{ fontSize: 10.5, fontWeight: 800, letterSpacing: ".05em", textTransform: "uppercase", color: K.sub }}>{k}</div>
              <div className="k-mono" style={{ fontSize: 13, fontWeight: 600, color: v ? K.ink : K.sub }}>{v || "—"}</div>
            </div>
          ))}
          <div style={{ alignSelf: "center", marginLeft: "auto", fontSize: 11.5, color: K.sub }}>BASIC DATA — maintenu par l'usine</div>
        </div>
      )}
    </div>
  );
}

function GameProdsSection({ game, db, update, push, readOnly }) {
  const active = activePrintIds(db);
  return (
    <div style={{ marginTop: 4 }}>
      {game.prints.map((pr, i) => (
        <AdminPrintCard key={pr.id} print={pr} db={db} update={update} push={push} defaultOpen={active.has(pr.id)} readOnly={readOnly} />
      ))}
      {game.prints.length === 0 && <div className="k-card" style={{ marginTop: 12, padding: 20, color: K.sub, textAlign: "center" }}>Aucun print pour ce jeu.</div>}
    </div>
  );
}

// ——— La fiche complète d'un jeu ———
function GameSheet({ game, db, update, push, tabbed, restricted }) {
  const gc = gameColor(game.name);
  const [tab, setTab] = React.useState("prods");
  React.useEffect(() => setTab("prods"), [game.id]);
  const basic = db.basicData[game.id] || null;
  const tabBtn = (k, lbl) => (
    <button key={k} onClick={() => setTab(k)} style={{ border: "none", padding: "6px 16px", fontSize: 12.5, fontWeight: 700, cursor: "pointer", fontFamily: K.font,
      background: tab === k ? K.black : "transparent", color: tab === k ? "#FFF" : K.sub }}>{lbl}</button>
  );
  return (
    <div data-comment-anchor={"admin-game-" + game.id}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, flexWrap: "wrap" }}>
        {game.image
          ? <img src={game.image} alt={game.name} style={{ width: 54, height: 54, borderRadius: 12, objectFit: "cover", border: `1.5px solid ${K.line}` }} />
          : null}
        <div className="k-round" style={{ fontSize: 24, fontWeight: 700, padding: "4px 18px", borderRadius: 12, background: gc.fg, color: "#FFF" }}>{game.name}</div>
        {game.yearFR ? <Pill fg={gc.fg} bg={gc.soft}>Sortie FR {game.yearFR}</Pill> : null}
        {game.catalogue ? <Pill fg={K.gray} bg={K.grayBg}>{game.catalogue}</Pill> : null}
        {game.activeCount > 0
          ? <span style={{ fontSize: 12.5, color: K.sub, fontWeight: 600 }}>{game.activeCount} production{game.activeCount > 1 ? "s" : ""} en cours</span>
          : <span style={{ fontSize: 12.5, color: K.sub }}>aucune production en cours</span>}
      </div>
      {restricted ? (
        <div>
          <SectionLabel style={{ marginTop: 22 }}>Productions <span style={{ fontWeight: 400, textTransform: "none", letterSpacing: 0 }}>(lecture seule)</span></SectionLabel>
          <GameProdsSection game={game} db={db} update={update} push={push} readOnly={true} />
        </div>
      ) : tabbed ? (
        <div style={{ marginTop: 14 }}>
          <div style={{ display: "inline-flex", border: `1.5px solid ${K.line}`, borderRadius: 99, overflow: "hidden", background: "#FFF" }}>
            {tabBtn("prods", "Productions")}{tabBtn("infos", "Informations")}{tabBtn("chiffres", "Chiffres")}
          </div>
          {tab === "infos" && <GameInfoSection game={game} update={update} push={push} />}
          {tab === "chiffres" && (
            <div>
              <GameStatsSection game={game} basic={basic} />
              <GameFinanceSection game={game} db={db} update={update} push={push} />
            </div>
          )}
          {tab === "prods" && <GameProdsSection game={game} db={db} update={update} push={push} />}
        </div>
      ) : (
        <div>
          <SectionLabel style={{ marginTop: 22 }}>Productions</SectionLabel>
          <GameProdsSection game={game} db={db} update={update} push={push} />
          <GameInfoSection game={game} update={update} push={push} />
          <SectionLabel style={{ marginTop: 26 }}>Quantités produites</SectionLabel>
          <GameStatsSection game={game} basic={basic} />
          <GameFinanceSection game={game} db={db} update={update} push={push} />
        </div>
      )}
    </div>
  );
}

// ——— Pages utilitaires (conservées de l'ancienne page admin) ———
function LinksSection({ db, update, push, restricted }) {
  const base = "https://portal.kodama.games";
  const tk = window.ACCESS_TOKENS || {};
  const internal = [
    ["🏭 Usine (Whatz Games)", "factory", tk.factory],
    ["🌳 Admin KODAMA", "admin", tk.admin],
    ["🗂 Admin BlackRock", "blackrock", tk.blackrock, "productions seules — sans liens partenaires ni fiches jeux"],
  ].filter((l) => l[2]);
  return (
    <div>
      <div className="k-card" style={{ marginTop: 10, overflow: "hidden" }}>
        <table style={{ width: "100%", borderCollapse: "collapse" }}>
          <tbody>
            {db.partners.map((p) => <TokenRow key={p.id} partner={p} db={db} update={update} push={push} readOnly={restricted} />)}
          </tbody>
        </table>
      </div>
      {!restricted && <React.Fragment>
      <SectionLabel style={{ marginTop: 26 }}>Liens internes</SectionLabel>
      <div className="k-card" style={{ marginTop: 10, padding: "6px 18px" }}>
        {internal.map(([lbl, seg, tok, hint], i) => {
          const url = `${base}/${seg}/${tok}`;
          return (
            <div key={seg} style={{ display: "flex", gap: 12, alignItems: "baseline", flexWrap: "wrap", padding: "10px 0", borderTop: i === 0 ? "none" : `1px solid ${K.line}` }}>
              <strong style={{ fontSize: 13, whiteSpace: "nowrap" }}>{lbl}</strong>
              <span className="k-mono" style={{ fontSize: 11.5, color: K.sub, flex: 1, minWidth: 200, overflow: "hidden", textOverflow: "ellipsis" }}>{url}</span>
              {hint ? <span style={{ fontSize: 11.5, color: K.sub }}>{hint}</span> : null}
              <CopyBtn text={url} label="Copier" />
            </div>
          );
        })}
      </div>
      <p style={{ fontSize: 12, color: K.sub, margin: "8px 2px 0" }}>Chaque lien ouvre uniquement son interface — la racine du site est verrouillée. Pour changer un lien interne, modifiez son jeton dans « Portail KODAMA.html » (ACCESS_TOKENS) et redéployez.</p>
      </React.Fragment>}
      {restricted && <p style={{ fontSize: 12, color: K.sub, margin: "8px 2px 0" }}>Chaque lien ouvre la page indépendante du partenaire — en lecture pour consultation.</p>}
    </div>
  );
}

function JournalSection({ db, count }) {
  return (
    <div className="k-card" style={{ marginTop: 10, padding: "6px 20px" }}>
      {db.log.slice(0, count || 14).map((l, i) => (
        <div key={i} style={{ display: "flex", gap: 14, padding: "9px 0", borderTop: i === 0 ? "none" : `1px solid ${K.line}`, fontSize: 13, alignItems: "baseline" }}>
          <span className="k-mono" style={{ fontSize: 11, color: K.sub, whiteSpace: "nowrap" }}>{l.ts}</span>
          <span style={{ fontWeight: 700, whiteSpace: "nowrap" }}>{l.actor}</span>
          <span style={{ color: K.blueS, fontWeight: 600, whiteSpace: "nowrap" }}>{l.action}</span>
          <span style={{ color: K.sub, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{l.detail}</span>
        </div>
      ))}
      {db.log.length === 0 && <div style={{ padding: "12px 0", color: K.sub, fontSize: 13 }}>Aucune entrée pour l'instant.</div>}
    </div>
  );
}

// ——— Barre latérale : jeux + pages utilitaires ———
function GameSidebar({ rows, catalog, nav, setNav, restricted }) {
  const [showCatalog, setShowCatalog] = React.useState(false);
  const item = (selected, onClick, content, key) => (
    <button key={key} onClick={onClick} style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", textAlign: "left", border: "none", cursor: "pointer",
      background: selected ? K.black : "transparent", color: selected ? "#FFF" : K.ink, borderRadius: 10, padding: "8px 11px", fontFamily: K.font, fontSize: 13.5, fontWeight: 700 }}>
      {content}
    </button>
  );
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
      <div className="k-label" style={{ padding: "2px 11px 6px" }}>Jeux · en production</div>
      {rows.map((g) => item(
        nav.page === "game" && nav.gameId === g.id,
        () => setNav({ page: "game", gameId: g.id }),
        <React.Fragment>
          <span style={{ width: 9, height: 9, borderRadius: 99, background: gameColor(g.name).mid, flexShrink: 0 }}></span>
          <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{g.name}</span>
          {g.activeCount > 0 && <span style={{ fontSize: 10.5, fontWeight: 800, borderRadius: 99, padding: "1px 7px", background: nav.page === "game" && nav.gameId === g.id ? "rgba(255,255,255,0.25)" : K.amberBg, color: nav.page === "game" && nav.gameId === g.id ? "#FFF" : K.amber }}>{g.activeCount}</span>}
        </React.Fragment>, g.id))}
      {catalog.length > 0 && (
        <button onClick={() => setShowCatalog(!showCatalog)} style={{ background: "none", border: "none", cursor: "pointer", textAlign: "left", padding: "7px 11px", fontFamily: K.font, fontSize: 12, fontWeight: 700, color: K.sub }}>
          <span style={{ display: "inline-block", transform: showCatalog ? "rotate(90deg)" : "none", transition: "transform .15s", marginRight: 7 }}>▸</span>
          {catalog.length} jeu{catalog.length > 1 ? "x" : ""} sans production en cours
        </button>
      )}
      {showCatalog && catalog.map((g) => item(
        nav.page === "game" && nav.gameId === g.id,
        () => setNav({ page: "game", gameId: g.id }),
        <React.Fragment>
          <span style={{ width: 9, height: 9, borderRadius: 99, background: gameColor(g.name).soft, flexShrink: 0 }}></span>
          <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: 500 }}>{g.name}</span>
        </React.Fragment>, g.id))}
      <div style={{ height: 1, background: K.line, margin: "10px 6px" }}></div>
      {item(nav.page === "links", () => setNav({ ...nav, page: "links" }), <span>🔗&nbsp; Liens partenaires</span>, "links")}
      {item(nav.page === "journal", () => setNav({ ...nav, page: "journal" }), <span>🗒&nbsp; Journal</span>, "journal")}
    </div>
  );
}

// ——— Vue Admin (restricted = Admin BlackRock : productions seules, sans liens ni fiches) ———
function AdminView({ db, update, t, restricted }) {
  const [toasts, push] = useToasts();
  const { rows, catalog } = buildGameRows(db);
  const all = rows.concat(catalog);
  const layout = (t && t.adminLayout) || "A · Liste + fiche";
  const [navRaw, setNavState] = React.useState(() => {
    try { const v = JSON.parse(localStorage.getItem(ADMIN_NAV_KEY)); if (v && v.page) return v; } catch (e) {}
    return { page: "game", gameId: rows[0] && rows[0].id };
  });
  const setNav = (v) => { setNavState(v); try { localStorage.setItem(ADMIN_NAV_KEY, JSON.stringify(v)); } catch (e) {} };
  // Les ids changent quand les données réelles remplacent la démo — revalider
  let nav = navRaw;
  if (nav.page === "game" && !all.find((g) => g.id === nav.gameId)) {
    nav = { page: "game", gameId: rows[0] && rows[0].id };
  }
  const game = nav.page === "game" ? all.find((g) => g.id === nav.gameId) : null;

  const header = (
    <TopBar title="Administration" right={
      restricted
        ? <div><div style={{ fontWeight: 700, color: "#FFF" }}>BLACKROCK</div>
          <div style={{ fontSize: 12, color: "rgba(255,255,255,0.65)" }}>Suivi production</div></div>
        : <div><div style={{ fontWeight: 700, color: "#FFF" }}>KODAMA GAMES</div>
          <div style={{ fontSize: 12, color: "rgba(255,255,255,0.65)" }}>Vue interne · FR 🇫🇷</div></div>
    } />
  );

  // ——— Variante C : sélecteur en haut, fiche pleine largeur, liens + journal dessous ———
  if (layout.startsWith("C")) {
    return (
      <div style={{ minHeight: "100vh", background: K.bg }}>
        {header}
        <div style={{ padding: "24px 44px 48px", maxWidth: 1440, margin: "0 auto" }}>
          <SectionLabel>Jeux</SectionLabel>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 10 }}>
            {all.map((g) => {
              const selected = game && game.id === g.id;
              return (
                <button key={g.id} onClick={() => setNav({ page: "game", gameId: g.id })}
                  style={{ border: `1.5px solid ${selected ? K.black : K.line}`, background: selected ? K.black : "#FFF", color: selected ? "#FFF" : K.ink,
                    borderRadius: 99, padding: "6px 16px", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: K.font }}>
                  {g.name}{g.activeCount > 0 ? <span style={{ opacity: .65, fontWeight: 600 }}> · {g.activeCount}</span> : null}
                </button>
              );
            })}
          </div>
          <div style={{ marginTop: 22 }}>
            {game ? <GameSheet game={game} db={db} update={update} push={push} tabbed={false} restricted={restricted} /> : <div className="k-card" style={{ marginTop: 12, padding: 20, color: K.sub, textAlign: "center" }}>Aucun jeu.</div>}
          </div>
          {!restricted && <React.Fragment>
            <SectionLabel style={{ marginTop: 34 }}>Liens magiques partenaires</SectionLabel>
            <LinksSection db={db} update={update} push={push} />
          </React.Fragment>}
          {restricted && <React.Fragment>
            <SectionLabel style={{ marginTop: 34 }}>Liens partenaires</SectionLabel>
            <LinksSection db={db} update={update} push={push} restricted={true} />
          </React.Fragment>}
          <SectionLabel style={{ marginTop: 34 }}>Journal complet</SectionLabel>
          <JournalSection db={db} count={14} />
        </div>
        <ToastHost toasts={toasts} />
      </div>
    );
  }

  // ——— Variantes A / B : liste des jeux à gauche, fiche à droite ———
  const tabbed = layout.startsWith("B");
  return (
    <div style={{ minHeight: "100vh", background: K.bg }}>
      {header}
      <div style={{ display: "grid", gridTemplateColumns: "256px minmax(0, 1fr)", gap: 34, maxWidth: 1520, margin: "0 auto", padding: "24px 44px 48px", alignItems: "start" }}>
        <div style={{ position: "sticky", top: 76 }}>
          <GameSidebar rows={rows} catalog={catalog} nav={nav} setNav={setNav} restricted={restricted} />
        </div>
        <div style={{ minWidth: 0 }}>
          {nav.page === "game" && game && <GameSheet game={game} db={db} update={update} push={push} tabbed={tabbed} restricted={restricted} />}
          {nav.page === "game" && !game && <div className="k-card" style={{ padding: 20, color: K.sub, textAlign: "center" }}>Aucun jeu.</div>}
          {nav.page === "links" && (
            <div>
              <div className="k-round" style={{ fontSize: 22, fontWeight: 700 }}>{restricted ? "Liens partenaires" : "Liens magiques partenaires"}</div>
              <LinksSection db={db} update={update} push={push} restricted={restricted} />
            </div>
          )}
          {nav.page === "journal" && (
            <div>
              <div className="k-round" style={{ fontSize: 22, fontWeight: 700 }}>Journal complet</div>
              <JournalSection db={db} count={30} />
            </div>
          )}
        </div>
      </div>
      <ToastHost toasts={toasts} />
    </div>
  );
}

Object.assign(window, { AdminView, GameSheet, buildGameRows, BigNum });
