sokko-g/website/src/features/cards/PackPanel.jsx
Shinuwa fd47514d81 Freeze pack rates in a campaign when it is created
A gifted pack using the pack's own rates was drawn with whatever rates
were in force when the player opened it. Campaigns now copy those rates
at creation (packRates), every pack of the code draws with them, and the
reveal shows them. Older campaigns keep following the live rates.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 16:50:51 +01:00

184 lines
12 KiB
JavaScript

// Rôle : présente les paquets en tuiles cliquables par catégorie et gère la révélation des trois cartes.
import { useEffect, useRef, useState } from "react";
import { claimReward, completeOpening, openGiftPack, openPack } from "./cardsApi.js";
import { DashboardAside } from "./CardsDashboard.jsx";
import { CollectionCardBack } from "./CollectionCardBack.jsx";
import { formatPercent, rarityPercentages } from "./dropRates.js";
import { NebulaCard } from "./NebulaCard.jsx";
import { OpeningReserve } from "./OpeningReserve.jsx";
import { packDetails, summarizeReward } from "./rewardText.js";
export function PackPanel({ catalog, state, runMutation, busy, content, reserveContent }) {
const activeCollections = catalog.collections.filter((collection) => collection.active);
const [completedOpening, setCompletedOpening] = useState(null);
const opening = state.pendingOpening || completedOpening;
// L'enchaînement remplace l'étape : le focus clavier passe à la suivante au lieu de retomber en haut de page.
const focusNextStageRef = useRef(false);
// Une tuile n'a qu'une action : la réserve rechargeable d'abord, puis les ouvertures achetées.
const hasReserve = state.recharge.openingsBalance > 0;
const hasPurchased = state.wallet.purchasedOpenings > 0;
const openCollection = (collectionId) => runMutation(() => openPack(collectionId, { purchased: !hasReserve }));
if (opening) {
// Un paquet offert ou de la boutique ne consomme aucune ouverture : l'enchaîner en dépenserait une sans le même tirage.
const canOpenAnother = !opening.options && (hasReserve || hasPurchased)
&& activeCollections.some((collection) => collection.id === opening.collectionId && collection.packCategory !== "shop");
return <OpeningStage
key={opening.id}
catalog={catalog}
opening={opening}
busy={busy}
content={content}
shopShare={state.shop.shopPackShare}
remaining={{ reserve: state.recharge.openingsBalance, purchased: state.wallet.purchasedOpenings }}
onComplete={async () => {
setCompletedOpening(opening);
return runMutation(() => completeOpening(opening.id));
}}
onDismiss={() => setCompletedOpening(null)}
focusOnMountRef={focusNextStageRef}
onOpenAnother={canOpenAnother ? async () => {
focusNextStageRef.current = true;
const result = await openCollection(opening.collectionId);
if (result) setCompletedOpening(null);
else focusNextStageRef.current = false;
} : null}
/>;
}
const giftPacks = state.giftPacks || [];
const categories = [
["permanent", content.permanent, content.permanentDescription],
["event", content.event, content.eventDescription]
];
return <div className="nebula-pack-page">
<div className="nds-section-heading nebula-pack-page-heading">
<div><p className="eyebrow">{content.eyebrow}</p><h2>{content.title}</h2></div>
</div>
<DashboardAside>
<OpeningReserve recharge={state.recharge} content={reserveContent} compact />
{hasPurchased && <section className="nds-panel nebula-purchased-openings" aria-label={content.purchasedLabel}>
<strong>{state.wallet.purchasedOpenings}</strong>
<span>ouverture{state.wallet.purchasedOpenings > 1 ? "s" : ""} achetée{state.wallet.purchasedOpenings > 1 ? "s" : ""}</span>
<p className="nebula-form-help">{content.purchasedHelp}</p>
</section>}
</DashboardAside>
<RedeemCode catalog={catalog} runMutation={runMutation} busy={busy} content={content} />
{!hasReserve && !hasPurchased && <p className="nds-inline-notice" data-variant="info">{content.noOpening}</p>}
{giftPacks.length > 0 && <section className="nds-panel nebula-pack-category nebula-gift-packs" aria-labelledby="nebula-gift-packs-title">
<div className="nds-section-heading nebula-pack-category-heading"><div><h3 id="nebula-gift-packs-title">{content.giftTitle}</h3><p>{content.giftDescription}</p></div><span className="nds-badge" data-variant="gold">{giftPacks.length}</span></div>
<div className="nebula-pack-grid">{giftPacks.map((gift) => {
const collection = catalog.collections.find((item) => item.id === gift.collectionId);
const details = packDetails(gift.options, catalog);
return <button key={gift.id} type="button" className="nebula-pack nebula-gift-pack" disabled={busy} aria-label={`${content.giftOpen} : ${collection?.name} (${gift.sourceName ?? gift.campaignName})`} onClick={() => runMutation(() => openGiftPack(gift.id))}>
<span className="nebula-pack-back" data-card-size="md"><CollectionCardBack collection={collection} /></span>
<span className="nebula-pack-note">
<span className="nebula-pack-copy">{gift.source === "expedition" ? `${content.giftFromExpedition} · ${gift.sourceName}` : gift.campaignName}</span>
{details.length > 0 && <span className="nebula-gift-pack-details">{details.join(" · ")}</span>}
</span>
</button>;
})}</div>
</section>}
<div className="nebula-pack-categories">{categories.map(([category, label, description]) => {
const collections = activeCollections.filter((collection) => collection.packCategory === category);
return <section key={category} className="nds-panel nebula-pack-category" aria-labelledby={`nebula-pack-category-${category}`}>
<div className="nds-section-heading nebula-pack-category-heading"><div><h3 id={`nebula-pack-category-${category}`}>{label}</h3><p>{description}</p></div><span className="nds-badge" data-variant={category === "event" ? "gold" : "neutral"}>{collections.length}</span></div>
{collections.length ? <div className="nebula-pack-grid">{collections.map((collection) => <button key={collection.id} type="button" className="nebula-pack" disabled={busy || (!hasReserve && !hasPurchased)} aria-label={`${content.open} : ${collection.name}`} onClick={() => openCollection(collection.id)}>
<span className="nebula-pack-back" data-card-size="md"><CollectionCardBack collection={collection} /></span>
<span className="nebula-pack-note"><span className="nebula-pack-copy" title={collection.description}>{collection.description}</span></span>
</button>)}</div> : <div className="nds-empty-state"><p>{content.empty}</p></div>}
</section>;
})}</div>
</div>;
}
function RedeemCode({ catalog, runMutation, busy, content }) {
const [code, setCode] = useState("");
const [received, setReceived] = useState(null);
return <section className="nds-panel nebula-redeem" aria-labelledby="nebula-redeem-title">
<div><h3 id="nebula-redeem-title">{content.redeemTitle}</h3><p className="nebula-form-help">{content.redeemHelp}</p></div>
<form className="nebula-redeem-form" onSubmit={async (event) => {
event.preventDefault();
const result = await runMutation(() => claimReward(code));
if (result?.reward) {
setReceived(result.reward);
setCode("");
}
}}>
<input className="nds-input" value={code} onChange={(event) => { setCode(event.target.value.toUpperCase()); setReceived(null); }} placeholder={content.redeemPlaceholder} aria-label={content.redeemTitle} autoComplete="off" required />
<button className="nds-button" data-variant="secondary" type="submit" disabled={busy || !code.trim()}>{content.redeemButton}</button>
</form>
{received && <p className="nds-inline-notice" data-variant="success" role="status">{content.redeemReceived} <strong>{summarizeReward(received, catalog)}</strong>. {content.redeemWhere}</p>}
</section>;
}
function OpeningOdds({ catalog, opening, collection, content, shopShare }) {
// Un paquet offert peut avoir ses propres taux et une garantie : ce sont eux qui s'appliquent à ce tirage.
const weights = opening.options?.rarityWeights || opening.options?.packRates || collection?.dropWeights;
const details = packDetails(opening.options, catalog);
if (collection?.packCategory === "shop") details.push(`${shopShare} % ${content.shopShare} ${collection.name}`);
return <section className="nds-panel nebula-opening-odds" aria-labelledby="nebula-opening-odds-title">
<h3 id="nebula-opening-odds-title">{content.probabilities}</h3>
<ul className="nebula-shop-rates" aria-labelledby="nebula-opening-odds-title">{rarityPercentages(catalog.rarities, weights, collection?.drawableRarities).map(({ rarity, percent }) => <li key={rarity.id} data-rarity={rarity.id}><span>{rarity.label}</span><strong>{formatPercent(percent)}</strong></li>)}</ul>
{details.length > 0 && <p className="nebula-form-help">{details.join(" · ")}</p>}
</section>;
}
// Révélation d'une ouverture ; la Boutique l'utilise aussi pour son paquet, qui s'ouvre sans quitter la boutique.
export function OpeningStage({ catalog, opening, onComplete, onDismiss, onOpenAnother, focusOnMountRef, remaining, busy, content, shopShare }) {
const [revealed, setRevealed] = useState(new Set());
const [finishedReveals, setFinishedReveals] = useState(new Set());
const [completed, setCompleted] = useState(false);
const completionRequestedRef = useRef(false);
const revealAllRef = useRef(null);
const allStarted = revealed.size === opening.cards.length;
const allRevealed = finishedReveals.size === opening.cards.length;
const collection = catalog.collections.find((item) => item.id === opening.collectionId);
useEffect(() => {
if (!allRevealed || completionRequestedRef.current) return;
completionRequestedRef.current = true;
void onComplete().then((result) => {
if (result) setCompleted(true);
});
}, [allRevealed, onComplete]);
useEffect(() => {
if (!focusOnMountRef.current) return;
focusOnMountRef.current = false;
revealAllRef.current?.focus();
}, [focusOnMountRef]);
// L'enregistrement automatique a pu échouer : le retenter avant de quitter cette ouverture.
const ensureCompleted = async () => completed || Boolean(await onComplete());
async function finish() {
if (await ensureCompleted()) onDismiss();
}
async function openAnother() {
if (await ensureCompleted()) await onOpenAnother();
}
return <section className="nebula-opening-stage" aria-labelledby="nebula-opening-title">
<div className="nds-section-heading nebula-section-heading"><div><p className="eyebrow">Paquet attribué</p><h2 id="nebula-opening-title">Révélez vos trois cartes</h2>
<div className="nebula-opening-remaining"><span>{content.remainingLabel} :</span>
<dl aria-label={content.remainingLabel}>
<div><dt>{content.remainingReserve}</dt><dd>{remaining.reserve}</dd></div>
<div><dt>{content.remainingPurchased}</dt><dd>{remaining.purchased}</dd></div>
</dl>
</div>
</div>
{!allStarted && <button ref={revealAllRef} className="nds-button" data-size="sm" data-variant="secondary" type="button" onClick={() => setRevealed(new Set(opening.cards.map((card) => card.id)))}>Tout révéler</button>}
{allRevealed && <div className="nds-toolbar">
<button className="nds-button" data-size="sm" data-variant="secondary" type="button" disabled={busy} onClick={finish}>{content.back}</button>
{onOpenAnother && <button className="nds-button" data-size="sm" data-variant="primary" type="button" disabled={busy} onClick={openAnother}>{content.openAnother}</button>}
</div>}
</div>
<div className="nebula-opening-cards">
{opening.cards.map((card) => <NebulaCard key={card.id} catalog={catalog} entry={card} size="lg" faceUp={false} backCollection={collection} newBadge={card.isNewEdition ? content.newBadge : null} revealed={revealed.has(card.id)} onReveal={() => setRevealed((current) => new Set([...current, card.id]))} onRevealComplete={() => setFinishedReveals((current) => new Set([...current, card.id]))} />)}
</div>
<OpeningOdds catalog={catalog} opening={opening} collection={collection} content={content} shopShare={shopShare} />
</section>;
}