Skip to content

Calculator script API ​

A calculator is a small JavaScript function that turns a deck into a dashboard: a mana curve, a type breakdown, opening-hand odds. It returns data plus a widget type, never markup. Turny.gg draws each widget with its own trusted components, which is what makes it safe to show a calculator someone else wrote.

The no-code builder produces the same kind of script, so everything here also applies to a builder calculator you open as code. For a walkthrough of building and sharing calculators, see the calculators guide.

The contract ​

A calculator script defines one function, compute, and returns a dashboard:

js
export default function compute(pile, cardsById, ctx) {
  return {
    widgets: [{ kind: "stat", label: "Hello", value: "world" }],
  };
}

Turny.gg finds the function in one of three ways, in this order:

  1. export default function compute(...) { ... } (any name, or none, works here).
  2. export default <expression>, where the expression is a function.
  3. A top-level function declared as function compute(...) { ... }.

The script runs in the same sandbox as custom rulesets: no network, no timers, no async, and only a short list of built-in globals. See Script sandbox for exactly what is allowed. A script the safety check rejects never runs.

Arguments ​

#ArgumentTypeDescription
1pileRecord<string, number>The deck being viewed: card ref to number of copies. Refs are the keys of cardsById.
2cardsByIdRecord<string, Card>Every card in the pile, by ref. Game-specific fields live on card.game; see the card data reference for your game.
3contextCalculatorScriptContext | undefinedOptional catalog context (fields below). May be undefined: a script that reads it must work without it.

CalculatorScriptContext:

PropertyTypeDescription
globalsunknownThe game catalog's globals document (region, keyword and set lookup tables). Its shape is per game; null when the catalog has none or it failed to load.
attachedPile?CalculatorPileCards the deck must own but never plays from it (Hearthstone's E.T.C. band and Zilliax's modules), keyed like pile: card ref -> quantity. Never part of pile, so totals, curves and draw odds stay on the played deck; a cost calculator adds what it can price. Absent when the deck has none. Their cards are in cardsById too.

Things to know about the arguments:

  • They are read-only. pile, cardsById and ctx are frozen copies. Build new arrays and objects instead of changing them.
  • A card can be missing. Guard cardsById[ref] before reading from it; the default calculators treat a missing card as having no fields.
  • Card fields are per game. Everything game-specific lives on card.game. See the card data reference for Cyberpunk TCG, Flesh and Blood, Hearthstone, Legends of Runeterra, Magic: The Gathering, Palworld TCG, Pokémon TCG and Riftbound.
  • ctx may be absent. Any run can call compute without it, including the editor preview. Check it before use:
js
export default function compute(pile, cardsById, ctx) {
  const hasGlobals = ctx !== undefined && ctx.globals !== undefined;

  return {
    widgets: [
      {
        kind: "stat",
        label: "Catalog globals",
        value: hasGlobals ? "Yes" : "No",
      },
    ],
  };
}

Return value ​

compute returns an object with a widgets array. Widgets are drawn in array order. Each widget is a plain object whose kind picks how it is drawn; the rest of its fields are the data for that kind.

Widget examples ​

Every widget type with a minimal working compute:

js
export default function compute(pile) {
  let total = 0;

  Object.keys(pile).forEach((ref) => {
    total += pile[ref];
  });

  return {
    widgets: [
      { kind: "stat", label: "Deck size", value: total, unit: "cards" },
    ],
  };
}
js
export default function compute(pile) {
  // Distinct cards run as 1-ofs, 2-ofs and 3+-ofs.
  const buckets = [0, 0, 0];

  Object.keys(pile).forEach((ref) => {
    const copies = Math.min(Math.max(pile[ref], 1), 3);
    buckets[copies - 1] += 1;
  });

  return {
    widgets: [
      {
        kind: "histogram",
        label: "Copies per card",
        buckets: buckets,
        labels: ["1", "2", "3+"],
      },
    ],
  };
}
js
export default function compute(pile) {
  let singles = 0;
  let multiples = 0;

  Object.keys(pile).forEach((ref) => {
    if (pile[ref] === 1) {
      singles += 1;
    } else {
      multiples += 1;
    }
  });

  return {
    widgets: [
      {
        kind: "donut",
        label: "Singles vs multiples",
        segments: [
          { key: "singles", label: "1 copy", value: singles, color: "#3a78e8" },
          { key: "multiples", label: "2+ copies", value: multiples, color: "" },
        ],
      },
    ],
  };
}
js
export default function compute(pile) {
  let singles = 0;
  let multiples = 0;

  Object.keys(pile).forEach((ref) => {
    if (pile[ref] === 1) {
      singles += pile[ref];
    } else {
      multiples += pile[ref];
    }
  });

  return {
    widgets: [
      {
        kind: "gauge",
        label: "Copies in singles vs multiples",
        segments: [
          { key: "singles", label: "Singles", value: singles, color: "" },
          { key: "multiples", label: "Multiples", value: multiples, color: "" },
        ],
      },
    ],
  };
}
js
export default function compute(pile, cardsById) {
  const rows = Object.keys(pile)
    .sort((left, right) => pile[right] - pile[left])
    .slice(0, 5)
    .map((ref) => {
      const card = cardsById[ref];
      const name = card && typeof card.name === "string" ? card.name : ref;

      return [name, pile[ref]];
    });

  return {
    widgets: [
      {
        kind: "table",
        label: "Most copies",
        columns: ["Card", "Copies"],
        rows: rows,
      },
    ],
  };
}
js
export default function compute(pile) {
  // Odds of drawing at least one copy of your most-played card in 7 cards.
  let deckSize = 0;
  let mostCopies = 0;

  Object.keys(pile).forEach((ref) => {
    deckSize += pile[ref];
    mostCopies = Math.max(mostCopies, pile[ref]);
  });

  return {
    widgets: [
      {
        kind: "hypergeometric",
        label: "Top card in opening hand",
        population: deckSize,
        successCount: mostCopies,
        draws: 7,
        exactCounts: [1, 2],
      },
    ],
  };
}
js
export default function compute(pile) {
  let copies = 0;

  Object.keys(pile).forEach((ref) => {
    copies += pile[ref];
  });

  return {
    widgets: [
      {
        kind: "ratio",
        label: "Copies per card",
        numerator: copies,
        denominator: Object.keys(pile).length,
        format: "multiplier",
      },
    ],
  };
}

Widget reference ​

kindDescription
"stat"A single headline value in a stat tile (e.g. "Average cost: 3.4").
"histogram"A bar chart: one bar per bucket (e.g. a mana curve). Bars pair with labels by index.
"donut"A donut (pie) chart of labelled, coloured segments.
"gauge"A semicircular meter: segments fill a half-circle in proportion to their values. Same payload as donut, drawn as a gauge.
"bars"Horizontal bars, one per segment (e.g. regions, domains, mana sources).
"table"A table of rows under column headers.
"hypergeometric"A closed-form hypergeometric draw-odds widget: the probability of drawing successes when taking draws cards, without replacement, from a population of which successCount match a filter (e.g. "odds of opening at least one basic in a 7-card hand"). The renderer computes and shows P(X>=1); when exactCounts is given it also shows P(X=k) for each listed k in a small table.
"ratio"A derived index number: numerator / denominator, formatted per format. Renders as a stat tile. Guards against a zero denominator.

kind: "stat" ​

A single headline value in a stat tile (e.g. "Average cost: 3.4").

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
valuenumber | stringThe value. A finite number is formatted in the viewer's locale (Intl.NumberFormat); a string is shown verbatim (e.g. "12.5%").
unit?stringOptional suffix shown after the value (e.g. "cards").

kind: "histogram" ​

A bar chart: one bar per bucket (e.g. a mana curve). Bars pair with labels by index.

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
bucketsnumber[]Bar heights, left to right.
labelsstring[]One axis label per bucket, same order as buckets.
bucketCardRefs?string[][]Optional pile refs per bucket, parallel to buckets: the cards counted in each bar. A bar is clickable (selecting it highlights those cards on the deck page) only when its entry is a non-empty list. Capped like DeckStatSegment.cardRefs.

kind: "donut" ​

A donut (pie) chart of labelled, coloured segments.

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
vocabulary?stringOptional CalculatorVocabulary id resolving segment labels and colors per game.
segmentsDeckStatSegment[]Slices, drawn in order; zero-value slices are skipped.

kind: "gauge" ​

A semicircular meter: segments fill a half-circle in proportion to their values. Same payload as donut, drawn as a gauge.

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
vocabulary?stringOptional CalculatorVocabulary id resolving segment labels and colors per game.
segmentsDeckStatSegment[]Arcs, drawn in order; zero-value arcs are skipped.

kind: "bars" ​

Horizontal bars, one per segment (e.g. regions, domains, mana sources).

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
vocabulary?stringOptional CalculatorVocabulary id resolving segment labels and colors per game.
segmentsDeckStatSegment[]Bars, drawn in order.

kind: "table" ​

A table of rows under column headers.

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
columnsstring[]Column headers, left to right.
columnKeys?string[]Optional i18n keys under calculators.widgets.*, parallel to columns.
columnVocabularies?string[]Optional CalculatorVocabulary ids, parallel to columns ("" for none). A cell in a column naming one is a vocabulary key the game resolves to its translated label, as segment keys are; an unresolved key shows as-is.
rows(string | number)[][]Rows of cells; each row pairs with columns by index.

kind: "hypergeometric" ​

A closed-form hypergeometric draw-odds widget: the probability of drawing successes when taking draws cards, without replacement, from a population of which successCount match a filter (e.g. "odds of opening at least one basic in a 7-card hand"). The renderer computes and shows P(X>=1); when exactCounts is given it also shows P(X=k) for each listed k in a small table.

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
populationnumberPopulation size: the pile / deck size drawn from.
successCountnumberSuccesses in the population: cards matching the filter.
drawsnumberNumber of cards drawn (e.g. the opening-hand size).
exactCounts?number[]Optional exact-count targets. When present, the renderer adds a P(X=k) row per listed k alongside the headline P(X>=1) figure.

kind: "ratio" ​

A derived index number: numerator / denominator, formatted per format. Renders as a stat tile. Guards against a zero denominator.

PropertyTypeDescription
labelstringTitle shown on the widget.
labelKey?stringOptional i18n key under calculators.widgets.*; falls back to label.
numeratornumberTop of the fraction.
denominatornumberBottom of the fraction. A zero shows the no-data placeholder.
format?CalculatorRatioFormatHow to format the quotient. Defaults to number.

Segments ​

A donut slice or gauge arc (DeckStatSegment):

PropertyTypeDescription
keystringStable identifier for the segment (e.g. "spells").
labelstringLegend text.
valuenumberThe segment's size; segments are drawn in proportion to their values.
colorstringCSS color (e.g. "#3a78e8"). Empty picks a fallback palette color.
cardRefs?string[]The pile refs (the keys of compute's pile) of the cards counted in this segment. Optional: a segment is clickable (selecting it highlights those cards on the deck page) only when it carries a non-empty list. The runner keeps strings only, de-duplicated and capped (CALCULATOR_OUTPUT_CAPS.maxCardRefsPerSegment / maxCardRefsPerWidget).

Ratio formats ​

FormatShows
"number"The raw quotient to two decimals (e.g. 1.83).
"percent"The quotient as a percentage to one decimal (e.g. 65.0%).
"multiplier"The quotient to two decimals with a multiplier sign (e.g. 1.83×).
"ratio"The pair reduced to lowest terms (e.g. 11:6).

How bad output is handled ​

A calculator's return value is never trusted. Before anything is drawn it passes through a checker (normalizeCalculatorResult) that repairs or drops whatever does not fit the shapes above. The checker never throws, so a buggy script produces a smaller dashboard, not a crash:

Your script returnsWhat is drawn
Anything other than an object with a widgets arrayAn empty dashboard
A widget that is not an object, or has an unknown kindThat widget is dropped; the rest are kept
A missing or non-text labelAn empty label
A number field (value of a segment, buckets, population, numerator, ...)Converted with Number(); NaN, Infinity and non-numbers become 0
A text field set to a number or booleanConverted to text; any other value (object, null) becomes empty text
A stat valueKept as a number if it is one (non-finite becomes 0), otherwise text
A table cellKept as a number if it is one, otherwise text; a row that is not an array is dropped
A segment that is not an objectThat segment is dropped
unit, exactCounts or format of the wrong type (or an unknown format)That optional field is left out
Extra properties on a widgetDropped
More entries or longer text than the limits allowCut to the limit

An error thrown by your script, a syntax error, or a safety-check rejection is different: the calculator shows an error message instead of a dashboard.

A widget with nothing to show draws a "No data" placeholder instead of an empty chart: a stat whose value is empty text, a histogram or donut/gauge with no positive values, a table with no columns or no rows, a hypergeometric with a population of 0 or less, or a ratio with a denominator of 0.

Limits ​

Hard caps normalizeCalculatorResult applies to guest output. Guest code is untrusted: these clamp the blast radius of a hostile or buggy script on the trusted renderer. Output past a cap is truncated (extra entries dropped, strings cut), never rejected.

CapLimitApplies to
maxWidgets50Widgets kept per dashboard; later widgets are dropped.
maxSegments100Segments kept per donut, gauge or bars widget.
maxHistogramBuckets200Entries kept in a histogram's buckets and in its labels.
maxTableRows200Rows kept per table.
maxTableColumns20Entries kept in a table's columns, and cells kept per row.
maxLabelLength200Characters kept in every short string: widget labels and label keys, stat string values and units, segment keys, labels and colors, histogram labels and table column headers and column keys.
maxCellLength200Characters kept in a string table cell.
maxExactCounts50Entries kept in a hypergeometric widget's exactCounts.
maxCardRefsPerSegment250Card refs kept per segment cardRefs and per histogram bucket's bucketCardRefs entry, after dropping non-strings and duplicates.
maxCardRefsPerWidget2000Card refs kept across one widget's segments or buckets; once spent, later segments/buckets keep none. Bounds the payload a hostile script can emit.

Time limit: a run that takes longer than 5 seconds is stopped and the calculator shows an error instead of a dashboard.

Builder-generated scripts ​

A calculator made with the no-code builder is an ordinary script whose first line is a marker comment holding the builder's settings:

text
// @calculator-spec:v1 {"widgets":[...]}

The marker is only a comment, so it has no effect on how the script runs. The builder uses it to re-open the calculator:

  • Drop to code switches a builder calculator to the code editor.
  • While the code is still exactly what the builder generates from the marker (checked by rebuilding it and comparing byte for byte), you can switch back to the builder.
  • Once you edit the code by hand, the rebuilt code no longer matches and the calculator is detached from the builder: it stays a code calculator. Undoing your edits so the code matches again re-enables switching back.

To make sure hand edits are never replaced by the builder's version, delete the marker line before saving. A script without a readable marker always opens in the code editor.

Examples: the default calculators ​

Every game except Teamfight Tactics ships default calculators, and they are ordinary calculator scripts. The code below is pulled from the source the site runs, so it is always current. Copy one as a starting point for your own.

js
const COST_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+"];

const LEGEND_TYPE = "legend";

// Colour display order (the official database's order); unknown colours are not charted.
const COLOR_ORDER = ["red", "blue", "green", "yellow"];

// Main-deck card-type display order; unexpected types trail by count.
const TYPE_ORDER = ["unit", "gear", "program"];

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  const costBuckets = Array.from({ length: 11 }, () => 0);
  const typeCounts = new Map();
  const colorCounts = new Map();
  const ramLimits = new Map();
  const highestRam = new Map();
  const overLimit = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const costRefs = new Map();
  const typeRefs = new Map();
  const colorRefs = new Map();

  const mainCards = [];
  const mainDeck = {};
  let legendCount = 0;
  let mainCount = 0;
  let sellableCount = 0;
  let costTotal = 0;
  let costCount = 0;
  let powerTotal = 0;
  let powerCount = 0;

  Object.keys(deck).forEach((cardId) => {
    if (!isRecord(catalog[cardId])) {
      return;
    }

    const quantity = deck[cardId];
    const game = cardGame(catalog[cardId]);
    const type = typeof game.cardType === "string" && game.cardType.length > 0 ? game.cardType : "unknown";
    const color = COLOR_ORDER.indexOf(game.color) === -1 ? null : game.color;
    const ram = Number.isFinite(game.ram) ? Math.max(0, Math.floor(game.ram)) : 0;

    // Legends sit in their own pile: they only raise their colour's RAM limit.
    if (type === LEGEND_TYPE) {
      legendCount += quantity;
      if (color !== null) {
        ramLimits.set(color, (ramLimits.get(color) ?? 0) + ram * quantity);
      }
      return;
    }

    mainCount += quantity;
    mainDeck[cardId] = quantity;
    mainCards.push({ color, ram, quantity });

    if (Number.isFinite(game.cost)) {
      const cost = Math.max(0, Math.floor(game.cost));
      const costIndex = Math.min(cost, 10);
      costBuckets[costIndex] += quantity;
      addRef(costRefs, costIndex, cardId);
      costTotal += cost * quantity;
      costCount += quantity;
    }

    if (Number.isFinite(game.power)) {
      powerTotal += Math.max(0, game.power) * quantity;
      powerCount += quantity;
    }

    if (game.sellable === true) {
      sellableCount += quantity;
    }

    typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity);
    addRef(typeRefs, type, cardId);

    if (color !== null) {
      colorCounts.set(color, (colorCounts.get(color) ?? 0) + quantity);
      addRef(colorRefs, color, cardId);
      highestRam.set(color, Math.max(highestRam.get(color) ?? 0, ram));
    }
  });

  // Over-limit copies need every Legend's RAM first, so they are counted after the pass.
  mainCards.forEach((card) => {
    if (card.color !== null && card.ram > (ramLimits.get(card.color) ?? 0)) {
      overLimit.set(card.color, (overLimit.get(card.color) ?? 0) + card.quantity);
    }
  });

  // One row per colour the deck touches (a Legend or a main-deck card): its
  // main-deck cards, their highest RAM, the Legends' limit and the copies over it.
  const ramRows = COLOR_ORDER.filter((color) => colorCounts.has(color) || ramLimits.has(color)).map((color) => [
    titleCase(color),
    colorCounts.get(color) ?? 0,
    highestRam.get(color) ?? 0,
    ramLimits.get(color) ?? 0,
    overLimit.get(color) ?? 0,
  ]);

  const widgets = [
    { kind: "stat", label: "Total cards", labelKey: "totalCards", value: mainCount },
    { kind: "stat", label: "Legends", labelKey: "cyberpunk.legends", value: legendCount },
    {
      kind: "table",
      label: "RAM",
      labelKey: "cyberpunk.ram",
      columns: ["Color", "Cards", "Highest RAM", "RAM limit", "Over limit"],
      columnKeys: ["cyberpunk.ramTable.color", "cyberpunk.ramTable.cards", "cyberpunk.ramTable.highest", "cyberpunk.ramTable.limit", "cyberpunk.ramTable.overLimit"],
      rows: ramRows,
    },
    { kind: "histogram", label: "Cost curve", labelKey: "cyberpunk.costCurve", buckets: costBuckets, labels: COST_CURVE_LABELS, bucketCardRefs: bucketRefList(costRefs, costBuckets.length) },
    { kind: "ratio", label: "Sell tag share", labelKey: "cyberpunk.sellTagShare", numerator: sellableCount, denominator: mainCount, format: "percent" },
    { kind: "donut", label: "Card types", labelKey: "cyberpunk.cardTypes", vocabulary: "cyberpunk.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) },
    { kind: "donut", label: "Colors", labelKey: "cyberpunk.colors", vocabulary: "cyberpunk.color", segments: withCardRefs(orderedSegments(colorCounts, COLOR_ORDER), colorRefs) },
    { kind: "stat", label: "Average cost", labelKey: "cyberpunk.averageCost", value: costCount > 0 ? roundTo(costTotal / costCount, 2) : 0 },
    { kind: "stat", label: "Average power", labelKey: "cyberpunk.averagePower", value: powerCount > 0 ? roundTo(powerTotal / powerCount, 2) : 0 },
  ];

  {
    const pile = mainDeck;
    const chanceHand = 6;
    // Distinct-card table: one row per distinct card (keyed by name) in the
    // match set, with the configured metric columns. All combinatorics are
    // inline — the sandbox cannot import a helper.
    const containsValue = (haystack, needle) => {
      if (Array.isArray(haystack)) {
        return haystack.indexOf(needle) !== -1;
      }
      if (haystack === undefined || haystack === null) {
        return false;
      }
      return String(haystack).indexOf(String(needle)) !== -1;
    };
    const lineCopies = new Map();
    const linePrintings = new Map();
    const lineCards = new Map();
    const lineOrder = [];
    let deckSize = 0;
    let matchTotal = 0;
    Object.keys(pile).forEach((ref) => {
      const quantity = Number(pile[ref]) || 0;
      if (quantity <= 0) {
        return;
      }
      deckSize = deckSize + quantity;
      const card = cardsById[ref];
      const row = { quantity: quantity, card: card, ref: ref };
      if (!(true)) {
        return;
      }
      matchTotal = matchTotal + quantity;
      const key = String(row.card !== null && row.card !== undefined && typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref);
      if (!lineCopies.has(key)) {
        lineCopies.set(key, 0);
        linePrintings.set(key, 0);
        lineCards.set(key, row);
        lineOrder.push(key);
      }
      lineCopies.set(key, lineCopies.get(key) + quantity);
      linePrintings.set(key, linePrintings.get(key) + 1);
    });

    // P(the opening hand contains none of a pool of `excluded` cards), drawing
    // `drawCount` without replacement — a running product of draw ratios so a
    // 60-card deck never overflows a factorial. 0 when the pool leaves too few
    // safe cards to fill the hand.
    const probNoneOf = (excluded, drawCount) => {
      if (deckSize - excluded < drawCount) {
        return 0;
      }
      let probability = 1;
      for (let i = 0; i < drawCount; i = i + 1) {
        probability = (probability * (deckSize - excluded - i)) / (deckSize - i);
      }
      return probability;
    };

    // Clamp to [0,1] and render as a 2-decimal percentage string.
    const formatPercent = (value) => {
      const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
      return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
    };

    const entries = lineOrder.map((key) => {
      const copies = lineCopies.get(key);
      return {
        key: key,
        copies: copies,
        printings: linePrintings.get(key),
        row: lineCards.get(key),
        otherMatches: matchTotal - copies,
      };
    });

    // Highest copy count first (== highest possible-starter odds for fixed
    // draws); ties broken by key.
    entries.sort((left, right) => {
      if (right.copies !== left.copies) {
        return right.copies - left.copies;
      }
      return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
    });

    widgets.push({
      kind: "table",
      label: "Chance to see",
      columns: ["Card", "Hand", "Mulligan", "+1 draw", "+3 draws"],
      rows: entries.map((entry) => {
        const row = entry.row;
        return [entry.key, (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand, deckSize)))), (formatPercent(1 - Math.pow(probNoneOf(entry.copies, Math.min(chanceHand, deckSize)), 2))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 1, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 3, deckSize))))];
      }),
    });
    const chanceTable = widgets[widgets.length - 1];
    chanceTable.labelKey = "chanceToSee";
    chanceTable.columnKeys = [
      "chanceToSeeColumns.card",
      "chanceToSeeColumns.openingHand",
      "chanceToSeeColumns.mulligan",
      "chanceToSeeColumns.afterOneDraw",
      "chanceToSeeColumns.afterThreeDraws",
    ];
  }

  return { widgets };
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}
js
const COST_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7+"];

// Pitch value -> colour-bar key (the fab.pitch vocabulary is keyed by colour).
const PITCH_COLORS = { 1: "red", 2: "yellow", 3: "blue" };
const PITCH_ORDER = ["red", "yellow", "blue"];

// Types that never sit in a deck list: skipped everywhere but the total.
const NON_DECK_TYPES = ["token", "demi_hero", "macro", "event"];

// A main-deck card's one display type: the first of these its types carry. An
// attack action reads as "attack", any other action as "action".
const TYPE_ORDER = ["attack", "action", "attack_reaction", "defense_reaction", "instant", "block", "resource", "mentor"];
const TYPE_PRIORITY = ["attack_reaction", "defense_reaction", "instant", "attack", "action", "block", "resource", "mentor"];
// English fallbacks; the fab.cardType vocabulary supplies the shown label.
const TYPE_LABELS = {
  attack: "Attack",
  action: "Action",
  attack_reaction: "Attack reaction",
  defense_reaction: "Defense reaction",
  instant: "Instant",
  block: "Block",
  resource: "Resource",
  mentor: "Mentor",
};

// The attack vs non-attack split's second key, beside the "attack" card type.
const NON_ATTACK = "non_attack";

// Classes in canonical order; "generic" cards go in any deck and sit last.
const CLASS_ORDER = ["adjudicator", "assassin", "bard", "brute", "guardian", "illusionist", "mechanologist", "merchant", "necromancer", "ninja", "pirate", "ranger", "runeblade", "shapeshifter", "thief", "warrior", "wizard", "generic"];
const GENERIC = "generic";

// A card blocks well when its defense is at least this.
const BLOCKER_DEFENSE = 3;

// Hand size when the list names no hero (most adult and young heroes draw 4).
const DEFAULT_INTELLECT = 4;
// The opening-hand table's rows: at least 1, 2 and 3 of a colour bar.
const OPENING_HAND_AT_LEAST = [1, 2, 3];

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  const curveBuckets = Array.from({ length: COST_CURVE_LABELS.length }, () => 0);
  const pitchCounts = new Map();
  const typeCounts = new Map();
  const splitCounts = new Map();
  const classCounts = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const curveRefs = new Map();
  const pitchRefs = new Map();
  const typeRefs = new Map();
  const splitRefs = new Map();
  const classRefs = new Map();

  // The main deck by ref: what the chance-to-see odds draw from.
  const mainDeck = {};
  let total = 0;
  let heroes = 0;
  let weapons = 0;
  let equipment = 0;
  let main = 0;
  let pitchTotal = 0;
  let costTotal = 0;
  let costed = 0;
  let power = 0;
  let defense = 0;
  let blockers = 0;
  let intellect = DEFAULT_INTELLECT;

  Object.keys(deck).forEach((cardId) => {
    const quantity = deck[cardId];

    const card = catalog[cardId];
    if (!isRecord(card)) {
      total += quantity;
      return;
    }

    const game = cardGame(card);
    const types = Array.isArray(game.types) ? game.types : [];
    const has = (type) => types.indexOf(type) !== -1;

    if (has("hero") || game.isHero === true) {
      heroes += quantity;
      if (Number.isFinite(game.intelligence) && game.intelligence > 0) {
        intellect = Math.floor(game.intelligence);
      }
      return;
    }
    if (has("weapon")) {
      weapons += quantity;
      total += quantity;
      return;
    }
    // Inventory that is not a weapon: equipment, plus Companions (typed ally
    // and companion) that take the off-hand slot without the Equipment type.
    if (has("equipment") || (game.equipmentSlot !== undefined && game.equipmentSlot !== null)) {
      equipment += quantity;
      total += quantity;
      return;
    }
    if (NON_DECK_TYPES.some(has)) {
      return;
    }

    main += quantity;
    total += quantity;
    mainDeck[cardId] = quantity;

    const pitchColor = Number.isFinite(game.pitch) ? PITCH_COLORS[game.pitch] : undefined;
    if (pitchColor !== undefined) {
      pitchCounts.set(pitchColor, (pitchCounts.get(pitchColor) ?? 0) + quantity);
      addRef(pitchRefs, pitchColor, cardId);
      pitchTotal += game.pitch * quantity;
    }

    if (Number.isFinite(game.cost)) {
      const cost = Math.max(0, Math.floor(game.cost));
      const curveIndex = Math.min(cost, COST_CURVE_LABELS.length - 1);
      curveBuckets[curveIndex] += quantity;
      addRef(curveRefs, curveIndex, cardId);
      costTotal += cost * quantity;
      costed += quantity;
    }

    const type = TYPE_PRIORITY.find(has);
    if (type !== undefined) {
      typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity);
      addRef(typeRefs, type, cardId);
    }

    const split = has("attack") ? "attack" : NON_ATTACK;
    splitCounts.set(split, (splitCounts.get(split) ?? 0) + quantity);
    addRef(splitRefs, split, cardId);

    const cardClass = primaryClass(game);
    classCounts.set(cardClass, (classCounts.get(cardClass) ?? 0) + quantity);
    addRef(classRefs, cardClass, cardId);

    if (Number.isFinite(game.power)) {
      power += Math.max(0, game.power) * quantity;
    }
    if (Number.isFinite(game.defense)) {
      defense += Math.max(0, game.defense) * quantity;
      if (game.defense >= BLOCKER_DEFENSE) {
        blockers += quantity;
      }
    }
  });

  // Means over the main deck, to one decimal: pitch over every main-deck card
  // (a card without a colour bar pitches nothing), cost over the costed ones.
  const averagePitch = main > 0 ? roundTo(pitchTotal / main, 1) : 0;
  const averageCost = costed > 0 ? roundTo(costTotal / costed, 1) : 0;
  // Over every main-deck card, so a pitch-only or cost-only card still counts.
  const resourceSurplus = main > 0 ? roundTo((pitchTotal - costTotal) / main, 2) : 0;
  const blockerShare = main > 0 ? formatPercentValue(blockers / main) : "0.00%";

  const attackSplit = ["attack", NON_ATTACK].map((key) => ({
    key,
    label: key === NON_ATTACK ? "Non-attack" : "Attack",
    value: splitCounts.get(key) ?? 0,
    color: "",
    cardRefs: splitRefs.get(key) ?? [],
  }));

  const widgets = [
    { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total },
    {
      kind: "table",
      label: "Deck zones",
      labelKey: "fab.deckZones",
      columns: ["Hero", "Weapons", "Equipment", "Main deck"],
      columnKeys: ["fab.zones.hero", "fab.zones.weapons", "fab.zones.equipment", "fab.zones.mainDeck"],
      rows: [[heroes, weapons, equipment, main]],
    },
    { kind: "donut", label: "Pitch", labelKey: "fab.pitch", vocabulary: "fab.pitch", segments: withCardRefs(orderedSegments(pitchCounts, PITCH_ORDER), pitchRefs) },
    { kind: "stat", label: "Average pitch", labelKey: "fab.averagePitch", value: averagePitch },
    { kind: "histogram", label: "Cost curve", labelKey: "fab.costCurve", buckets: curveBuckets, labels: COST_CURVE_LABELS, bucketCardRefs: bucketRefList(curveRefs, curveBuckets.length) },
    { kind: "stat", label: "Average cost", labelKey: "fab.averageCost", value: averageCost },
    { kind: "donut", label: "Card types", labelKey: "fab.cardTypes", vocabulary: "fab.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER, TYPE_LABELS), typeRefs) },
    { kind: "gauge", label: "Attack / non-attack", labelKey: "fab.attackSplit", vocabulary: "fab.cardType", segments: attackSplit },
    { kind: "donut", label: "Classes", labelKey: "fab.classes", vocabulary: "fab.class", segments: withCardRefs(orderedSegments(classCounts, CLASS_ORDER), classRefs) },
    { kind: "stat", label: "Total power", labelKey: "fab.totalPower", value: power },
    { kind: "stat", label: "Total defense", labelKey: "fab.totalDefense", value: defense },
    { kind: "stat", label: "Blocks for 3+", labelKey: "fab.blockers", value: blockers },
    { kind: "stat", label: "Share that blocks for 3+", labelKey: "fab.blockerShare", value: blockerShare },
    { kind: "stat", label: "Pitch minus cost per card", labelKey: "fab.resourceSurplus", value: resourceSurplus },
    { kind: "stat", label: "Hand size (intellect)", labelKey: "fab.handSize", value: intellect },
  ].concat(openingHandTable(main, pitchCounts, intellect));

  {
    const pile = mainDeck;
    const chanceHand = intellect;
    // Distinct-card table: one row per distinct card (keyed by name) in the
    // match set, with the configured metric columns. All combinatorics are
    // inline — the sandbox cannot import a helper.
    const containsValue = (haystack, needle) => {
      if (Array.isArray(haystack)) {
        return haystack.indexOf(needle) !== -1;
      }
      if (haystack === undefined || haystack === null) {
        return false;
      }
      return String(haystack).indexOf(String(needle)) !== -1;
    };
    const lineCopies = new Map();
    const linePrintings = new Map();
    const lineCards = new Map();
    const lineOrder = [];
    let deckSize = 0;
    let matchTotal = 0;
    Object.keys(pile).forEach((ref) => {
      const quantity = Number(pile[ref]) || 0;
      if (quantity <= 0) {
        return;
      }
      deckSize = deckSize + quantity;
      const card = cardsById[ref];
      const row = { quantity: quantity, card: card, ref: ref };
      if (!(true)) {
        return;
      }
      matchTotal = matchTotal + quantity;
      const key = String((typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref) + (Number.isFinite(cardGame(row.card).pitch) && PITCH_COLORS[cardGame(row.card).pitch] !== undefined ? " (" + titleCase(PITCH_COLORS[cardGame(row.card).pitch]) + ")" : ""));
      if (!lineCopies.has(key)) {
        lineCopies.set(key, 0);
        linePrintings.set(key, 0);
        lineCards.set(key, row);
        lineOrder.push(key);
      }
      lineCopies.set(key, lineCopies.get(key) + quantity);
      linePrintings.set(key, linePrintings.get(key) + 1);
    });

    // P(the opening hand contains none of a pool of `excluded` cards), drawing
    // `drawCount` without replacement — a running product of draw ratios so a
    // 60-card deck never overflows a factorial. 0 when the pool leaves too few
    // safe cards to fill the hand.
    const probNoneOf = (excluded, drawCount) => {
      if (deckSize - excluded < drawCount) {
        return 0;
      }
      let probability = 1;
      for (let i = 0; i < drawCount; i = i + 1) {
        probability = (probability * (deckSize - excluded - i)) / (deckSize - i);
      }
      return probability;
    };

    // Clamp to [0,1] and render as a 2-decimal percentage string.
    const formatPercent = (value) => {
      const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
      return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
    };

    const entries = lineOrder.map((key) => {
      const copies = lineCopies.get(key);
      return {
        key: key,
        copies: copies,
        printings: linePrintings.get(key),
        row: lineCards.get(key),
        otherMatches: matchTotal - copies,
      };
    });

    // Highest copy count first (== highest possible-starter odds for fixed
    // draws); ties broken by key.
    entries.sort((left, right) => {
      if (right.copies !== left.copies) {
        return right.copies - left.copies;
      }
      return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
    });

    widgets.push({
      kind: "table",
      label: "Chance to see",
      columns: ["Card", "Hand", "2 hands"],
      rows: entries.map((entry) => {
        const row = entry.row;
        return [entry.key, (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand * 2, deckSize))))];
      }),
    });
    const chanceTable = widgets[widgets.length - 1];
    chanceTable.labelKey = "chanceToSee";
    chanceTable.columnKeys = [
      "chanceToSeeColumns.card",
      "chanceToSeeColumns.openingHand",
      "chanceToSeeColumns.twoHands",
    ];
  }

  return { widgets };
}

// The chance an opening hand of `handSize` cards from the main deck holds at
// least N cards of each colour bar (hypergeometric), one row per N.
function openingHandTable(deckSize, pitchCounts, handSize) {
  if (deckSize <= 0) {
    return [];
  }

  const dealt = Math.min(handSize, deckSize);

  return [
    {
      kind: "table",
      label: "Opening hand odds",
      labelKey: "fab.openingHand",
      columns: ["At least", "Red", "Yellow", "Blue"],
      columnKeys: ["fab.openingHandAtLeast", "fab.pitchColors.red", "fab.pitchColors.yellow", "fab.pitchColors.blue"],
      rows: OPENING_HAND_AT_LEAST.filter((count) => count <= dealt).map((count) =>
        [count].concat(
          PITCH_ORDER.map((color) => formatOdds(atLeastChance(deckSize, pitchCounts.get(color) ?? 0, dealt, count))),
        ),
      ),
    },
  ];
}

// P(at least `wanted` of `copies` among `draws` cards from `size`).
function atLeastChance(size, copies, draws, wanted) {
  const total = choose(size, draws);
  if (total <= 0) {
    return 0;
  }

  let below = 0;
  for (let hits = 0; hits < wanted; hits += 1) {
    below += (choose(copies, hits) * choose(size - copies, draws - hits)) / total;
  }

  return Math.max(0, 1 - below);
}

function choose(n, k) {
  if (k < 0 || k > n) {
    return 0;
  }
  let result = 1;
  for (let i = 1; i <= Math.min(k, n - k); i += 1) {
    result = (result * (n - Math.min(k, n - k) + i)) / i;
  }
  return result;
}

function formatOdds(value) {
  return (Math.round(value * 1000) / 10).toFixed(1) + "%";
}

// The class a card counts toward: its first non-generic class in canonical
// order (a hybrid card reads as the earlier class), else generic.
function primaryClass(game) {
  const classes = Array.isArray(game.classes) ? game.classes : [];
  const known = CLASS_ORDER.filter((value) => value !== GENERIC && classes.indexOf(value) !== -1);
  return known.length > 0 ? known[0] : GENERIC;
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}
js
const MANA_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7+"];

// The playable classes in canonical order; "neutral" is any class's card.
const CLASS_ORDER = ["deathknight", "demonhunter", "druid", "hunter", "mage", "paladin", "priest", "rogue", "shaman", "warlock", "warrior"];
const NEUTRAL = "neutral";
const CLASS_LABELS = {
  deathknight: "Death Knight",
  demonhunter: "Demon Hunter",
  druid: "Druid",
  hunter: "Hunter",
  mage: "Mage",
  paladin: "Paladin",
  priest: "Priest",
  rogue: "Rogue",
  shaman: "Shaman",
  warlock: "Warlock",
  warrior: "Warrior",
  neutral: "Neutral",
};

// Deck-card types in display order; unexpected types trail by count.
const TYPE_ORDER = ["minion", "spell", "weapon", "location", "hero"];

// Rarities lowest to highest; the rarity donut keeps this order.
const RARITY_ORDER = ["free", "common", "rare", "epic", "legendary"];

// Arcane Dust to craft one regular (non-golden) copy, by rarity — the in-game
// crafting table (https://hearthstone.wiki.gg/wiki/Crafting): Common 40, Rare
// 100, Epic 400, Legendary 1600. Free cards can't be crafted (every player owns
// them), so they cost nothing; an unknown rarity is treated the same. A copy of
// HEARTHSTONE_DUST_BY_RARITY's craft costs (a spec keeps them in sync).
const DUST_COST = { common: 40, rare: 100, epic: 400, legendary: 1600 };

// Upstream set tokens whose regular printings can't be crafted, so a printing
// from one costs no dust whatever its rarity: the Core set (free to every
// player; CORE_HIDDEN holds the stat-changed Core copies old deckstrings name),
// Demon Hunter Initiate (free with the class) and Event (reward cards). Path
// of Arthas is craftable. A copy of HEARTHSTONE_UNCRAFTABLE_SET_IDS (a spec
// keeps them in sync; its doc cites the sources).
const UNCRAFTABLE_SETS = ["CORE", "CORE_HIDDEN", "DEMON_HUNTER_INITIATE", "EVENT"];

// Draw odds. Going first you draw 3; on the coin you draw 4 and get The Coin,
// which comes from outside the deck. Both players also draw at the start of
// every turn, turn 1 included, so by your turn N you have seen 3 + N cards
// going first and 4 + N on the coin.
const OPENING_HAND_FIRST = 3;
const OPENING_HAND_COIN = 4;
const DRAW_ODDS_TURNS = [1, 2, 3, 4, 5, 6];
const DRAW_ODDS_COPIES = [1, 2];

export default function compute(pile, cardsById, ctx) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  const curveBuckets = Array.from({ length: MANA_CURVE_LABELS.length }, () => 0);
  const typeCounts = new Map();
  const rarityCounts = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const curveRefs = new Map();
  const typeRefs = new Map();
  const rarityRefs = new Map();

  let total = 0;
  let library = 0;
  let dust = 0;
  let legendaries = 0;

  const entries = [];

  Object.keys(deck).forEach((cardId) => {
    const quantity = deck[cardId];
    total += quantity;

    const card = catalog[cardId];
    // Only collectible cards are ever shuffled into the deck (as in the sample
    // hand); an unresolved card still counts, so the library never shrinks.
    if (!isRecord(card) || card.collectible !== false) {
      library += quantity;
    }
    if (!isRecord(card)) {
      return;
    }

    const game = cardGame(card);
    entries.push({ ref: cardId, quantity, classes: cardClasses(game) });

    const cost = Number.isFinite(game.cost) ? Math.max(0, Math.floor(game.cost)) : 0;
    const curveIndex = Math.min(cost, MANA_CURVE_LABELS.length - 1);
    curveBuckets[curveIndex] += quantity;
    addRef(curveRefs, curveIndex, cardId);

    if (typeof game.cardType === "string" && game.cardType.length > 0) {
      typeCounts.set(game.cardType, (typeCounts.get(game.cardType) ?? 0) + quantity);
      addRef(typeRefs, game.cardType, cardId);
    }

    const rarity = typeof game.rarity === "string" ? game.rarity : "";
    if (RARITY_ORDER.indexOf(rarity) !== -1) {
      rarityCounts.set(rarity, (rarityCounts.get(rarity) ?? 0) + quantity);
      addRef(rarityRefs, rarity, cardId);
    }
    dust += craftCost(card, cardId, rarity) * quantity;
    if (rarity === "legendary") {
      legendaries += quantity;
    }
  });

  // The sideboards: only collectible cards are crafted (E.T.C.'s band); an
  // unresolved ref can't be told from a Zilliax module, so it costs nothing.
  const attached = normalizePile(isRecord(ctx) ? ctx.attachedPile : null);
  Object.keys(attached).forEach((cardId) => {
    const card = catalog[cardId];
    if (!isRecord(card) || card.collectible === false || cardGame(card).zilliaxModule != null) {
      return;
    }
    const rarity = cardGame(card).rarity;
    dust += craftCost(card, cardId, typeof rarity === "string" ? rarity : "") * attached[cardId];
  });

  return {
    widgets: [
      { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total },
      { kind: "stat", label: "Dust cost", labelKey: "hearthstone.dustCost", value: dust },
      { kind: "stat", label: "Legendaries", labelKey: "hearthstone.legendaries", value: legendaries },
      { kind: "histogram", label: "Mana curve", labelKey: "hearthstone.manaCurve", buckets: curveBuckets, labels: MANA_CURVE_LABELS, bucketCardRefs: bucketRefList(curveRefs, curveBuckets.length) },
      { kind: "donut", label: "Classes", labelKey: "hearthstone.classes", vocabulary: "hearthstone.class", segments: classSegments(entries) },
      { kind: "bars", label: "Card types", labelKey: "cardTypes", vocabulary: "hearthstone.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) },
      { kind: "donut", label: "Rarity", labelKey: "hearthstone.rarity", vocabulary: "hearthstone.rarity", segments: withCardRefs(orderedSegments(rarityCounts, RARITY_ORDER), rarityRefs) },
    ].concat(drawOddsTables(library)),
  };
}

// ---- Draw odds ---------------------------------------------------------------
// The chance to have at least one copy of a card by your turn N, for a card the
// deck runs once or twice. The mulligan is modelled as hunting for that card:
// keep the opener when it holds a copy, otherwise replace every card. Like the
// game (and the sample hand), the replacements are drawn first and only then do
// the replaced cards shuffle back, so a replacement is never a card you just
// threw away. The deck size comes from the pile, so 30- and 40-card decks work.
function drawOddsTables(library) {
  if (library <= 0) {
    return [];
  }

  const table = (label, labelKey, opener) => ({
    kind: "table",
    label,
    labelKey,
    columns: ["Turn", "1 copy", "2 copies"],
    columnKeys: ["hearthstone.drawOdds.turn", "hearthstone.drawOdds.oneCopy", "hearthstone.drawOdds.twoCopies"],
    rows: DRAW_ODDS_TURNS.map((turn) =>
      [turn].concat(DRAW_ODDS_COPIES.map((copies) => formatOdds(drawOdds(library, copies, opener, turn)))),
    ),
  });

  return [
    table("Draw odds going first (mulligan for it)", "hearthstone.drawOddsGoingFirst", OPENING_HAND_FIRST),
    table("Draw odds on the coin (mulligan for it)", "hearthstone.drawOddsOnCoin", OPENING_HAND_COIN),
  ];
}

// P(at least one of `copies` in a `deckSize` deck by turn `turn`), from an
// `opener`-card opening hand and a mulligan that hunts for the card. It misses
// only when the opener, the replacements and the turn draws all miss.
function drawOdds(deckSize, copies, opener, turn) {
  const copiesInDeck = Math.min(copies, deckSize);
  const dealt = Math.min(opener, deckSize);
  const missOpener = missChance(deckSize, copiesInDeck, dealt);
  // After a full mulligan the opener's cards are back in the deck, but the
  // hand still holds `dealt` non-copies, so the rest draws from the others.
  const remaining = deckSize - dealt;
  const missReplacements = missChance(remaining, copiesInDeck, Math.min(dealt, remaining));
  const missDraws = missChance(remaining, copiesInDeck, Math.min(turn, remaining));
  return 1 - missOpener * missReplacements * missDraws;
}

// P(no copy among `draws` cards drawn from `size` cards holding `copies`).
function missChance(size, copies, draws) {
  if (draws <= 0 || copies <= 0) {
    return 1;
  }
  const total = choose(size, draws);
  return total > 0 ? choose(size - copies, draws) / total : 0;
}

function choose(n, k) {
  if (k < 0 || k > n) {
    return 0;
  }
  let result = 1;
  for (let i = 1; i <= Math.min(k, n - k); i += 1) {
    result = (result * (n - Math.min(k, n - k) + i)) / i;
  }
  return result;
}

function formatOdds(value) {
  return (Math.round(value * 1000) / 10).toFixed(1) + "%";
}

// Arcane Dust to craft one copy of the printing the pile names: its rarity's
// cost, or nothing for a Free, uncraftable-set or marked-uncraftable printing.
function craftCost(card, cardId, identityRarity) {
  const printing = cardPrinting(card, cardId);
  const craftRarity = printingRarity(printing, identityRarity);
  if (
    RARITY_ORDER.indexOf(craftRarity) === -1 ||
    UNCRAFTABLE_SETS.indexOf(printingSet(card, printing)) !== -1 ||
    markedUncraftable(card, printing)
  ) {
    return 0;
  }
  return DUST_COST[craftRarity] ?? 0;
}

// The printings entry the pile names; undefined for an identity ref.
function cardPrinting(card, cardId) {
  const printings = Array.isArray(card.printings) ? card.printings : [];
  return printings.find((entry) => isRecord(entry) && entry.id === cardId);
}

// The set of the printing the pile names: its setCode, else (an identity ref)
// the default printing's game.setId.
function printingSet(card, printing) {
  if (printing && typeof printing.setCode === "string") {
    return printing.setCode;
  }
  const game = cardGame(card);
  return typeof game.setId === "string" ? game.setId : "";
}

// The catalog marked the named printing (else, for an identity ref, the
// default printing) `metadata.craftable: false`: a card with a special unlock
// (Prince Renathal, the Gift cards, …) that can't be crafted (#1251). A copy of
// isHearthstonePrintingMarkedUncraftable.
function markedUncraftable(card, printing) {
  const named = printing ?? cardPrinting(card, cardGame(card).defaultPrintingId);
  return Boolean(named) && isRecord(named.metadata) && named.metadata.craftable === false;
}

// The named printing's own rarity (`metadata.rarity`), else the identity's: a
// Legacy Basic printing of a Core card is Free while the identity reads Common.
function printingRarity(printing, identityRarity) {
  const metadata = printing && isRecord(printing.metadata) ? printing.metadata : {};
  return typeof metadata.rarity === "string" && metadata.rarity.length > 0 ? metadata.rarity : identityRarity;
}

// The card's playable classes in canonical order; ["neutral"] when it names
// none (or only unknown tokens).
function cardClasses(game) {
  const classes = Array.isArray(game.classes) ? game.classes : [];
  const known = CLASS_ORDER.filter((value) => classes.indexOf(value) !== -1);
  return known.length > 0 ? known : [NEUTRAL];
}

// Class vs Neutral: the deck's class is the one most single-class cards share;
// a multi-class card counts toward it when it carries it, else toward its first
// class. Classes by copies (highest first), Neutral last.
function classSegments(entries) {
  const singleClassCounts = new Map();
  entries.forEach((entry) => {
    if (entry.classes.length === 1 && entry.classes[0] !== NEUTRAL) {
      singleClassCounts.set(entry.classes[0], (singleClassCounts.get(entry.classes[0]) ?? 0) + entry.quantity);
    }
  });
  const deckClasses = CLASS_ORDER.filter((value) => singleClassCounts.has(value)).sort(
    (left, right) => singleClassCounts.get(right) - singleClassCounts.get(left),
  );

  const counts = new Map();
  const refs = new Map();
  entries.forEach((entry) => {
    const key = deckClasses.find((value) => entry.classes.indexOf(value) !== -1) ?? entry.classes[0];
    counts.set(key, (counts.get(key) ?? 0) + entry.quantity);
    addRef(refs, key, entry.ref);
  });

  const rank = (key) => (key === NEUTRAL ? CLASS_ORDER.length : 0);
  const segments = [];
  counts.forEach((value, key) => {
    segments.push({ key, label: CLASS_LABELS[key] ?? key, value, color: "", cardRefs: refs.get(key) ?? [] });
  });

  return segments.sort(
    (left, right) =>
      rank(left.key) - rank(right.key) ||
      right.value - left.value ||
      CLASS_ORDER.indexOf(left.key) - CLASS_ORDER.indexOf(right.key),
  );
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}
js
const MANA_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+"];

// Card-type keys in display order, with English fallback labels.
const TYPE_LABELS = {
  champions: "Champion",
  followers: "Follower",
  spells: "Spell",
  landmarks: "Landmark",
  equipment: "Equipment",
};

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  // Cards missing from the catalog can't be classified, so they count nowhere.
  const entries = Object.keys(deck)
    .filter((cardId) => isRecord(catalog[cardId]))
    .map((cardId) => {
      const card = catalog[cardId];
      const game = cardGame(card);

      return { ref: cardId, card, game, quantity: deck[cardId], cost: cardCost(game), regionRefs: cardRegionRefs(game) };
    })
    .sort(compareDeckCards);
  const deckRegions = detectDeckRegions(entries);

  const manaBuckets = Array.from({ length: 11 }, () => 0);
  const typeCounts = { champions: 0, followers: 0, spells: 0, landmarks: 0, equipment: 0 };
  const rarityCounts = new Map();
  const regionCounts = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const manaRefs = new Map();
  const typeRefs = new Map();
  const rarityRefs = new Map();
  const regionCardRefs = new Map();

  let costTotal = 0;
  let cardTotal = 0;

  entries.forEach((entry) => {
    const game = entry.game;
    const quantity = entry.quantity;

    const manaIndex = Math.min(entry.cost, 10);
    manaBuckets[manaIndex] += quantity;
    addRef(manaRefs, manaIndex, entry.ref);
    costTotal += entry.cost * quantity;
    cardTotal += quantity;

    // Categorize by the canonical (English) type ref, falling back to the
    // localized value for catalogs published before the refs existed.
    const type = game.typeRef ?? game.type;
    const supertype = game.supertypeRef ?? game.supertype;

    let typeKey = null;
    if (type === "Unit") {
      typeKey = supertype === "Champion" ? "champions" : "followers";
    } else if (type === "Spell") {
      typeKey = "spells";
    } else if (type === "Landmark") {
      typeKey = "landmarks";
    } else if (type === "Equipment") {
      typeKey = "equipment";
    }
    if (typeKey !== null) {
      typeCounts[typeKey] += quantity;
      addRef(typeRefs, typeKey, entry.ref);
    }

    const rarityRef = typeof game.rarityRef === "string" ? game.rarityRef : "Unknown";
    rarityCounts.set(rarityRef, (rarityCounts.get(rarityRef) ?? 0) + quantity);
    addRef(rarityRefs, rarityRef, entry.ref);

    // A card counts toward the first deck region it carries, so counts sum to
    // the deck size even for multi-region cards; one fitting none is skipped.
    const region = deckRegions.find((candidate) => entry.regionRefs.indexOf(candidate) !== -1);
    if (region !== undefined) {
      regionCounts.set(region, (regionCounts.get(region) ?? 0) + quantity);
      addRef(regionCardRefs, region, entry.ref);
    }
  });

  // Regions keep deck-region order; empty ones drop out.
  const regionSegments = deckRegions
    .filter((region) => (regionCounts.get(region) ?? 0) > 0)
    .map((region) => ({ key: region, label: region, value: regionCounts.get(region), color: "", cardRefs: regionCardRefs.get(region) ?? [] }));

  const typeSegments = Object.keys(TYPE_LABELS)
    .filter((key) => typeCounts[key] > 0)
    .map((key) => ({ key, label: TYPE_LABELS[key], value: typeCounts[key], color: "", cardRefs: typeRefs.get(key) ?? [] }));

  // Most copies first; ties keep card order.
  const raritySegments = [];
  rarityCounts.forEach((value, key) => {
    if (value > 0) {
      raritySegments.push({ key, label: key, value, color: "", cardRefs: rarityRefs.get(key) ?? [] });
    }
  });
  raritySegments.sort((left, right) => right.value - left.value);

  // Mean mana cost across the deck, weighted by copies, to one decimal.
  const averageCost = cardTotal > 0 ? Math.round((costTotal / cardTotal) * 10) / 10 : 0;
  // Units (champions + followers) against spells, as a reduced pair.
  const unitCount = typeCounts.champions + typeCounts.followers;
  const spellCount = typeCounts.spells;

  // Like the deck page, a breakdown with nothing to show is left out.
  const widgets = [];

  if (regionSegments.length > 0) {
    widgets.push({ kind: "bars", label: "Regions", labelKey: "lor.regions", vocabulary: "lor.region", segments: regionSegments });
  }
  widgets.push({ kind: "histogram", label: "Mana Curve", labelKey: "lor.manaCurve", buckets: manaBuckets, labels: MANA_CURVE_LABELS, bucketCardRefs: bucketRefList(manaRefs, manaBuckets.length) });
  if (typeSegments.length > 0) {
    widgets.push({ kind: "donut", label: "Card Types", labelKey: "lor.cardTypes", vocabulary: "lor.cardType", segments: typeSegments });
  }
  if (raritySegments.length > 0) {
    widgets.push({ kind: "donut", label: "Rarity", labelKey: "lor.rarity", vocabulary: "lor.rarity", segments: raritySegments });
  }
  widgets.push({ kind: "stat", label: "Average Cost", labelKey: "lor.averageCost", value: averageCost });
  widgets.push({ kind: "ratio", label: "Units : Spells", labelKey: "lor.unitsToSpells", numerator: unitCount, denominator: spellCount, format: "ratio" });

  return { widgets };
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}

function cardName(card) {
  return isRecord(card) && typeof card.name === "string" ? card.name : "";
}

function cardCost(game) {
  return Number.isFinite(game.cost) ? Math.max(0, Math.floor(game.cost)) : 0;
}

function cardRegionRefs(game) {
  return Array.isArray(game.regionRefs)
    ? game.regionRefs.filter((ref) => typeof ref === "string" && ref.length > 0)
    : [];
}

// The deck page's card order: by cost, then by name.
function compareDeckCards(left, right) {
  return left.cost - right.cost || cardName(left.card).localeCompare(cardName(right.card));
}

// The deck's regions, as the deck page derives them: every single-region
// card's region in card order, then (only if some card still fits none) the
// other regions of those unaccounted cards, never a Runeterra champion's
// card-code ref.
function detectDeckRegions(entries) {
  const regions = [];

  entries.forEach((entry) => {
    if (entry.regionRefs.length === 1 && regions.indexOf(entry.regionRefs[0]) === -1) {
      regions.push(entry.regionRefs[0]);
    }
  });

  entries
    .filter((entry) => !entry.regionRefs.some((ref) => regions.indexOf(ref) !== -1))
    .forEach((entry) => {
      entry.regionRefs.forEach((ref) => {
        if (!/^\d/.test(ref) && regions.indexOf(ref) === -1) {
          regions.push(ref);
        }
      });
    });

  return regions;
}
js
const MANA_VALUE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7+"];

// WUBRG, the order pips and sources are charted in; "C" is colorless mana.
const COLORS = ["W", "U", "B", "R", "G"];
const MANA_ORDER = ["W", "U", "B", "R", "G", "C"];

// Each card counts once, toward the first of these on its type line, so the
// donut sums to the deck (an Artifact Creature is a creature, a creature-land a
// creature). Keys are the lowercase type names.
const TYPE_PRIORITY = ["Creature", "Planeswalker", "Battle", "Instant", "Sorcery", "Artifact", "Enchantment", "Land"];
const TYPE_LABELS = {
  creature: "Creatures",
  planeswalker: "Planeswalkers",
  battle: "Battles",
  instant: "Instants",
  sorcery: "Sorceries",
  artifact: "Artifacts",
  enchantment: "Enchantments",
  land: "Lands",
};

const COLOR_LABELS = { W: "White", U: "Blue", B: "Black", R: "Red", G: "Green", C: "Colorless" };

// The opening hand the land stats draw: 7 cards, split by exact land count.
const OPENING_HAND_SIZE = 7;
const OPENING_HAND_LAND_COUNTS = [0, 1, 2, 3, 4, 5];

// Karsten's target: castable on curve at least 90% of the time.
const MANA_CHECK_TARGET = 0.9;

// Basic land subtype -> the color a land carrying it taps for.
const LAND_SUBTYPE_COLORS = [
  [/\bPlains\b/, "W"],
  [/\bIsland\b/, "U"],
  [/\bSwamp\b/, "B"],
  [/\bMountain\b/, "R"],
  [/\bForest\b/, "G"],
];

const ANY_COLOR_PATTERN = /any (one )?colors?|any combination of colors|mana of any (one )?colors?/i;
const ADD_CLAUSE_PATTERN = /\badds?\b/i;

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  const manaValueBuckets = Array.from({ length: MANA_VALUE_LABELS.length }, () => 0);
  const pipCounts = new Map();
  const sourceCounts = new Map();
  const typeCounts = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const manaValueRefs = new Map();
  const pipRefs = new Map();
  const sourceRefs = new Map();
  const typeRefs = new Map();

  let total = 0;
  let lands = 0;
  let nonlands = 0;
  let nonlandManaValue = 0;

  // Mana-check inputs: each land's producible colors (fetches resolved after
  // the pass, once the deck's basics are known) and each colored spell.
  const landEntries = [];
  const spellEntries = new Map();

  Object.keys(deck).forEach((cardId) => {
    const quantity = deck[cardId];
    total += quantity;

    const card = catalog[cardId];
    if (!isRecord(card)) {
      return;
    }

    const types = cardTypes(card);

    if (types.indexOf("Land") === -1) {
      const value = Math.max(0, manaValue(card));
      const bucket = Math.min(Math.floor(value), MANA_VALUE_LABELS.length - 1);
      manaValueBuckets[bucket] += quantity;
      addRef(manaValueRefs, bucket, cardId);
      nonlands += quantity;
      nonlandManaValue += value * quantity;

      const pips = strictColorPips(manaCost(card));
      const name = textOf(card.name);
      if (Object.keys(pips).length > 0 && name && !spellEntries.has(name)) {
        spellEntries.set(name, { name, cost: manaCost(card), turn: Math.max(1, Math.round(value)), pips });
      }
    } else {
      lands += quantity;
      landEntries.push({ quantity, card, produced: producedMana(card) });
    }

    // Hybrid / Phyrexian pips ("G/W", "B/P") count toward each color they name.
    manaSymbols(manaCost(card)).forEach((symbol) => {
      symbol.split("/").forEach((part) => {
        const token = part.trim().toUpperCase();
        if (COLORS.indexOf(token) !== -1) {
          pipCounts.set(token, (pipCounts.get(token) ?? 0) + quantity);
          addRef(pipRefs, token, cardId);
        }
      });
    });

    producedMana(card).forEach((mana) => {
      sourceCounts.set(mana, (sourceCounts.get(mana) ?? 0) + quantity);
      addRef(sourceRefs, mana, cardId);
    });

    const primary = TYPE_PRIORITY.find((type) => types.indexOf(type) !== -1);
    if (primary) {
      const key = primary.toLowerCase();
      typeCounts.set(key, (typeCounts.get(key) ?? 0) + quantity);
      addRef(typeRefs, key, cardId);
    }
  });

  const typeOrder = TYPE_PRIORITY.map((type) => type.toLowerCase());

  // Mean mana value of the nonland cards (lands would drag it toward 0), and
  // the expected lands in the opening hand, each to two decimals.
  const averageManaValue = nonlands > 0 ? roundTo(nonlandManaValue / nonlands, 2) : 0;
  const openingHandLands = total > 0 ? roundTo((OPENING_HAND_SIZE * lands) / total, 2) : 0;

  const manaCheck = computeManaCheck(total, lands, landEntries, Array.from(spellEntries.values()));

  return {
    widgets: [
      { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total },
      { kind: "stat", label: "Lands", labelKey: "mtg.lands", value: lands },
      { kind: "stat", label: "Average mana value", labelKey: "mtg.averageManaValue", value: averageManaValue },
      { kind: "histogram", label: "Mana value", labelKey: "mtg.manaValue", buckets: manaValueBuckets, labels: MANA_VALUE_LABELS, bucketCardRefs: bucketRefList(manaValueRefs, manaValueBuckets.length) },
      { kind: "donut", label: "Color pips", labelKey: "mtg.colorPips", vocabulary: "mtg.color", segments: withCardRefs(orderedSegments(pipCounts, COLORS, COLOR_LABELS), pipRefs) },
      { kind: "bars", label: "Mana sources", labelKey: "mtg.manaSources", vocabulary: "mtg.color", segments: withCardRefs(orderedSegments(sourceCounts, MANA_ORDER, COLOR_LABELS), sourceRefs) },
      { kind: "donut", label: "Card types", labelKey: "cardTypes", vocabulary: "mtg.cardType", segments: withCardRefs(orderedSegments(typeCounts, typeOrder, TYPE_LABELS), typeRefs) },
      { kind: "stat", label: "Lands in opening hand", labelKey: "mtg.openingHandLands", value: openingHandLands },
      // P(at least one land in 7), plus the exact 0–5 land split.
      { kind: "hypergeometric", label: "Opening hand land odds", labelKey: "mtg.openingHandLandOdds", population: total, successCount: lands, draws: Math.min(OPENING_HAND_SIZE, total), exactCounts: OPENING_HAND_LAND_COUNTS },
    ].concat(manaCheck),
  };
}

// ---- Mana check (Frank Karsten's method) ------------------------------------
// A spell is "castable on curve" when, by the turn equal to its mana value, you
// hold enough sources of each color it needs. Like Karsten, the odds are
// conditioned on hitting your land drops (at least that many lands drawn), on
// the play: 7 cards plus one draw per turn after the first. Sources are lands
// only (the colors they tap for, plus the basic types a fetchland can find);
// the odds are exact multivariate hypergeometric, so any deck size works.
// Hybrid, Phyrexian and twobrid pips are left out (they have other payments).

function computeManaCheck(total, lands, landEntries, spells) {
  if (total === 0 || lands === 0 || spells.length === 0) {
    return [];
  }

  const basicColors = new Set();
  landEntries.forEach((entry) => {
    if (/\bBasic\b/.test(typeLineOf(entry.card))) {
      entry.produced.forEach((color) => basicColors.add(color));
    }
  });

  const sources = new Map();
  landEntries.forEach((entry) => {
    const colors = new Set(entry.produced);
    fetchedColors(entry.card, basicColors).forEach((color) => colors.add(color));
    colors.forEach((color) => {
      sources.set(color, (sources.get(color) ?? 0) + entry.quantity);
    });
  });

  const oddsFor = (spell, color, sourceCount) =>
    castOdds(total, lands, sourceCount, spell.pips[color], spell.turn);

  const cardRows = spells.map((spell) => {
    let odds = 1;
    Object.keys(spell.pips).forEach((color) => {
      odds = Math.min(odds, oddsFor(spell, color, sources.get(color) ?? 0));
    });
    return { spell, odds };
  });
  cardRows.sort((left, right) => left.odds - right.odds || (left.spell.name < right.spell.name ? -1 : 1));

  // Per color, the most demanding card: the one needing the most sources
  // (unreachable counts as most), ties broken by the lower on-curve odds.
  const colorRows = [];
  COLORS.forEach((color) => {
    let hardest = null;
    spells.forEach((spell) => {
      if (!spell.pips[color]) {
        return;
      }
      const needed = sourcesNeeded(total, lands, spell.pips[color], spell.turn);
      const demand = needed === null ? Infinity : needed;
      const odds = oddsFor(spell, color, sources.get(color) ?? 0);
      if (hardest === null || demand > hardest.demand || (demand === hardest.demand && odds < hardest.odds)) {
        hardest = { spell, needed, demand, odds };
      }
    });
    if (hardest === null) {
      return;
    }
    colorRows.push([
      COLOR_LABELS[color],
      hardest.spell.name + " " + hardest.spell.cost,
      sources.get(color) ?? 0,
      hardest.needed === null ? "> " + lands : hardest.needed,
      formatOdds(hardest.odds),
    ]);
  });

  return [
    {
      kind: "table",
      label: "Colored sources",
      labelKey: "mtg.coloredSources",
      columns: ["Color", "Hardest card", "Sources", "Needed (90%)", "On curve"],
      columnKeys: ["mtg.manaCheck.color", "mtg.manaCheck.hardestCard", "mtg.manaCheck.sources", "mtg.manaCheck.needed", "mtg.manaCheck.onCurve"],
      rows: colorRows,
    },
    {
      kind: "table",
      label: "Castable on curve",
      labelKey: "mtg.castableOnCurve",
      columns: ["Card", "Cost", "Turn", "Odds"],
      columnKeys: ["mtg.manaCheck.card", "mtg.manaCheck.cost", "mtg.manaCheck.turn", "mtg.manaCheck.odds"],
      rows: cardRows.map((row) => [row.spell.name, row.spell.cost, row.spell.turn, formatOdds(row.odds)]),
    },
  ];
}

// The single-color pips a cost demands: "{1}{R}{R}" -> { R: 2 }.
function strictColorPips(cost) {
  const pips = {};
  manaSymbols(cost).forEach((symbol) => {
    const token = symbol.trim().toUpperCase();
    if (COLORS.indexOf(token) !== -1) {
      pips[token] = (pips[token] ?? 0) + 1;
    }
  });
  return pips;
}

// P(at least `needed` of `sources` colored lands among the cards seen by
// `turn`, given at least `turn` lands among them), on the play. Colored
// sources are a subset of the lands.
function castOdds(total, lands, sources, needed, turn) {
  const draws = Math.min(total, OPENING_HAND_SIZE + turn - 1);
  const colored = Math.min(sources, lands);
  const otherLands = lands - colored;
  const spells = total - lands;
  let enoughLands = 0;
  let castable = 0;
  for (let s = 0; s <= Math.min(colored, draws); s += 1) {
    for (let o = 0; o <= Math.min(otherLands, draws - s); o += 1) {
      const rest = draws - s - o;
      if (rest > spells || s + o < Math.min(turn, lands)) {
        continue;
      }
      const weight = choose(colored, s) * choose(otherLands, o) * choose(spells, rest);
      enoughLands += weight;
      if (s >= needed) {
        castable += weight;
      }
    }
  }
  return enoughLands > 0 ? castable / enoughLands : 0;
}

// The fewest colored sources (holding the land count fixed) that reach the
// target, or null when even an all-color land base falls short.
function sourcesNeeded(total, lands, needed, turn) {
  for (let count = needed; count <= lands; count += 1) {
    if (castOdds(total, lands, count, needed, turn) >= MANA_CHECK_TARGET) {
      return count;
    }
  }
  return null;
}

function choose(n, k) {
  if (k < 0 || k > n) {
    return 0;
  }
  let result = 1;
  for (let i = 1; i <= Math.min(k, n - k); i += 1) {
    result = (result * (n - Math.min(k, n - k) + i)) / i;
  }
  return result;
}

function formatOdds(value) {
  return (Math.round(value * 1000) / 10).toFixed(1) + "%";
}

function typeLineOf(card) {
  const game = cardGame(card);
  return [textOf(game.typeLine)].concat(cardFaces(game).map((face) => textOf(face.typeLine))).join(" // ");
}

// Colors a fetchland can find: the basic land types its search names ("a
// Plains or Island card"), or every basic color in the deck for a "basic land
// card" search (Fabled Passage, Evolving Wilds).
function fetchedColors(card, basicColors) {
  const colors = new Set();
  trimmedTexts(cardGame(card), "oracleText").forEach((text) => {
    const match = /search your library for (an? |up to \w+ )?([^.]*?)cards?\b/i.exec(text);
    if (!match) {
      return;
    }
    const target = match[2];
    let named = false;
    LAND_SUBTYPE_COLORS.forEach(([pattern, color]) => {
      if (pattern.test(target)) {
        colors.add(color);
        named = true;
      }
    });
    if (!named && /\bbasic land\b/i.test(target)) {
      basicColors.forEach((color) => colors.add(color));
    }
  });
  return Array.from(colors);
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}

function cardFaces(game) {
  return Array.isArray(game.faces) ? game.faces.filter(isRecord) : [];
}

function textOf(value) {
  return typeof value === "string" ? value : "";
}

// The mana-symbol tokens in a cost string: "{2}{W/U}" -> ["2", "W/U"].
function manaSymbols(text) {
  return (textOf(text).match(/\{[^}]+\}/g) || []).map((token) => token.slice(1, -1));
}

function faceManaCost(game) {
  const face = cardFaces(game).find((entry) => textOf(entry.manaCost).length > 0);
  return face ? face.manaCost : "";
}

// The top-level cost, else the first face that carries one (transform/MDFC).
function manaCost(card) {
  const game = cardGame(card);
  return game.manaCost !== undefined && game.manaCost !== null ? textOf(game.manaCost) : faceManaCost(game);
}

// Mana value: the card's cmc, else computed from the top-level or front-face
// cost (generic pips add their number, X/Y/Z count 0, twobrid {2/W} counts 2).
function manaValue(card) {
  const game = cardGame(card);
  if (typeof game.cmc === "number" && Number.isFinite(game.cmc)) {
    return game.cmc;
  }
  const cost = textOf(game.manaCost) || faceManaCost(game);
  let total = 0;
  manaSymbols(cost).forEach((symbol) => {
    const head = symbol.split("/")[0] ?? "";
    const generic = Number(head);
    if (Number.isFinite(generic)) {
      total += generic;
    } else if (!/^[XYZ]$/i.test(head)) {
      total += 1;
    }
  });
  return total;
}

// The major card types on the type line (before each face's "—" subtypes).
function cardTypes(card) {
  const game = cardGame(card);
  const typeLine =
    game.typeLine !== undefined && game.typeLine !== null
      ? textOf(game.typeLine)
      : cardFaces(game).map((face) => textOf(face.typeLine)).join(" // ");
  if (!typeLine) {
    return [];
  }
  const words = new Set(
    typeLine
      .split("//")
      .map((facePart) => facePart.split("—")[0] ?? "")
      .join(" ")
      .split(/\s+/)
      .filter(Boolean),
  );
  return TYPE_PRIORITY.filter((type) => words.has(type));
}

function trimmedTexts(game, field) {
  return [textOf(game[field])]
    .concat(cardFaces(game).map((face) => textOf(face[field])))
    .map((text) => text.trim())
    .filter(Boolean);
}

// The mana a card can produce: basic land subtypes, unioned with explicit
// "Add …" clauses in its rules text (reminder text included).
function producedMana(card) {
  const game = cardGame(card);
  const produced = new Set();

  trimmedTexts(game, "typeLine").forEach((typeLine) => {
    const dashIndex = typeLine.indexOf("—");
    if (dashIndex === -1) {
      return;
    }
    const subtypes = typeLine.slice(dashIndex + 1);
    LAND_SUBTYPE_COLORS.forEach(([pattern, color]) => {
      if (pattern.test(subtypes)) {
        produced.add(color);
      }
    });
  });

  trimmedTexts(game, "oracleText").forEach((text) => {
    text.split(/[.\n]/).forEach((clause) => {
      if (!ADD_CLAUSE_PATTERN.test(clause)) {
        return;
      }
      if (ANY_COLOR_PATTERN.test(clause)) {
        COLORS.forEach((color) => produced.add(color));
        return;
      }
      manaSymbols(clause).forEach((symbol) => {
        symbol.split("/").forEach((part) => {
          const token = part.trim().toUpperCase();
          if (MANA_ORDER.indexOf(token) !== -1) {
            produced.add(token);
          }
        });
      });
    });
  });

  return MANA_ORDER.filter((mana) => produced.has(mana));
}
js
const COST_CURVE_LABELS = ["1", "2", "3", "4", "5", "6", "7", "8+"];

// The deck rule's cap on cards with the lucky icon (rules 6.1.1).
const LUCKY_LIMIT = 8;

// Display orders; unexpected keys trail by count.
const TYPE_ORDER = ["pal", "structure", "gear", "event"];
const COLOR_ORDER = ["red", "blue", "green", "purple", "colorless"];
const ELEMENT_ORDER = ["neutral", "fire", "water", "grass", "electric", "ground", "ice", "dark", "dragon"];
// The catalog's work kinds (PalworldWorkSuitability), in its order.
const WORK_ORDER = ["harvesting", "crafting", "collecting", "transporting", "kindling", "cooling", "farming", "electricity"];
const WORK_LABELS = {
  harvesting: "Harvesting", crafting: "Crafting", collecting: "Collecting", transporting: "Transporting",
  kindling: "Kindling", cooling: "Cooling", farming: "Farming", electricity: "Electricity",
};
// Marks a work kind a Structure in the deck needs (`kindling:needed`).
const NEEDED_SUFFIX = ":needed";

// Matches the catalog ladder (globals.rarities order).
const RARITY_ORDER = ["c", "u", "r", "rr", "td", "tdr", "sr", "tsr", "osr", "sp", "tsp", "ssp", "sss", "pr"];

// English fallbacks for the printed rarity codes (the web domain localizes).
const RARITY_LABELS = {
  c: "C", u: "U", r: "R", rr: "RR", sr: "SR", osr: "OSR", sp: "SP", ssp: "SSP", sss: "SSS",
  td: "TD", tdr: "TDR", tsr: "TSR", tsp: "TSP", pr: "PR",
};

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  const costBuckets = Array.from({ length: COST_CURVE_LABELS.length }, () => 0);
  const typeCounts = new Map();
  const colorCounts = new Map();
  const elementCounts = new Map();
  const rarityCounts = new Map();
  const strikeRows = new Map();

  const costRefs = new Map();
  const typeRefs = new Map();
  const colorRefs = new Map();
  const elementRefs = new Map();
  const rarityRefs = new Map();
  const luckyRefs = new Map();
  const workPals = new Map();
  const workRefs = new Map();
  const workStructures = new Map();

  const mainDeck = {};
  let total = 0;
  let luckyCount = 0;
  let palCount = 0;
  let powerTotal = 0;
  let powerCount = 0;
  let strikeTotal = 0;
  let strikeCount = 0;

  Object.keys(deck).forEach((cardId) => {
    const card = catalog[cardId];

    if (!isRecord(card)) {
      return;
    }

    const quantity = deck[cardId];
    const game = cardGame(card);
    const type = typeof game.cardType === "string" && game.cardType.length > 0 ? game.cardType : "unknown";

    // Souls are the resource deck, never part of the main deck.
    if (type === "soul") {
      return;
    }

    mainDeck[cardId] = quantity;

    total += quantity;
    typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity);
    addRef(typeRefs, type, cardId);

    // No card prints a cost below 1 today; one that did would fold into the
    // "1" bucket rather than drop off the curve.
    if (Number.isFinite(game.cost)) {
      const costIndex = Math.min(Math.max(Math.floor(game.cost), 1), COST_CURVE_LABELS.length) - 1;
      costBuckets[costIndex] += quantity;
      addRef(costRefs, costIndex, cardId);
    }

    if (typeof game.color === "string" && game.color.length > 0) {
      colorCounts.set(game.color, (colorCounts.get(game.color) ?? 0) + quantity);
      addRef(colorRefs, game.color, cardId);
    }

    if (game.isLucky === true) {
      luckyCount += quantity;
      addRef(luckyRefs, "lucky", cardId);
    }

    const rarity = printingRarity(card, cardId);
    if (rarity !== null) {
      rarityCounts.set(rarity, (rarityCounts.get(rarity) ?? 0) + quantity);
      addRef(rarityRefs, rarity, cardId);
    }

    const works = (Array.isArray(game.workSuitability) ? game.workSuitability : []).filter(
      (work, index, list) => WORK_ORDER.indexOf(work) !== -1 && list.indexOf(work) === index,
    );

    if (type === "structure") {
      works.forEach((work) => {
        workStructures.set(work, (workStructures.get(work) ?? 0) + quantity);
      });
    }

    if (type !== "pal") {
      return;
    }

    works.forEach((work) => {
      workPals.set(work, (workPals.get(work) ?? 0) + quantity);
      addRef(workRefs, work, cardId);
    });

    palCount += quantity;

    (Array.isArray(game.elements) ? game.elements : []).forEach((element) => {
      if (ELEMENT_ORDER.indexOf(element) !== -1) {
        elementCounts.set(element, (elementCounts.get(element) ?? 0) + quantity);
        addRef(elementRefs, element, cardId);
      }
    });

    const hasPower = Number.isFinite(game.power);
    if (hasPower) {
      powerTotal += game.power * quantity;
      powerCount += quantity;
    }

    if (Number.isFinite(game.strike)) {
      const strike = Math.max(0, Math.floor(game.strike));
      strikeTotal += strike * quantity;
      strikeCount += quantity;

      const row = strikeRows.get(strike) ?? { pals: 0, powerTotal: 0, powerCount: 0 };
      row.pals += quantity;
      if (hasPower) {
        row.powerTotal += game.power * quantity;
        row.powerCount += quantity;
      }
      strikeRows.set(strike, row);
    }
  });

  // One row per printed strike value, lowest first: [strike, Pals, average power].
  const strikeTableRows = Array.from(strikeRows.keys())
    .sort((left, right) => left - right)
    .map((strike) => {
      const row = strikeRows.get(strike);
      return [strike, row.pals, row.powerCount > 0 ? roundTo(row.powerTotal / row.powerCount, 1) : "-"];
    });

  const luckySegments = [
    { key: "lucky", label: "Lucky", value: luckyCount, color: "", cardRefs: luckyRefs.get("lucky") ?? [] },
    { key: "open", label: "Open", value: Math.max(0, LUCKY_LIMIT - luckyCount), color: "" },
  ];

  // Pals per work kind, in the catalog's order; a kind a Structure needs is
  // keyed `<kind>:needed` so the web vocabulary marks it.
  const workSegments = WORK_ORDER.filter((work) => (workPals.get(work) ?? 0) > 0).map((work) => {
    const needed = workStructures.has(work);
    return {
      key: needed ? work + NEEDED_SUFFIX : work,
      label: needed ? WORK_LABELS[work] + " ★" : WORK_LABELS[work],
      value: workPals.get(work),
      color: "",
      cardRefs: workRefs.get(work) ?? [],
    };
  });
  // One row per work kind the deck's Structures need: [work, Structures, Pals].
  // The work cell is the raw kind, which the column's vocabulary translates.
  const structureWorkRows = WORK_ORDER.filter((work) => workStructures.has(work)).map((work) => [
    work,
    workStructures.get(work),
    workPals.get(work) ?? 0,
  ]);

  const rarities = withCardRefs(orderedSegments(rarityCounts, RARITY_ORDER, RARITY_LABELS), rarityRefs);

  const widgets = [
    { kind: "stat", label: "Total cards", labelKey: "totalCards", value: total },
    { kind: "histogram", label: "Cost curve", labelKey: "palworld.costCurve", buckets: costBuckets, labels: COST_CURVE_LABELS, bucketCardRefs: bucketRefList(costRefs, costBuckets.length) },
    { kind: "donut", label: "Card types", labelKey: "palworld.cardTypes", vocabulary: "palworld.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) },
    { kind: "donut", label: "Colors", labelKey: "palworld.colors", vocabulary: "palworld.color", segments: withCardRefs(orderedSegments(colorCounts, COLOR_ORDER), colorRefs) },
    { kind: "gauge", label: "Lucky cards (max 8)", labelKey: "palworld.luckyCards", segments: luckySegments },
    { kind: "bars", label: "Pal elements", labelKey: "palworld.elements", vocabulary: "palworld.element", segments: withCardRefs(orderedSegments(elementCounts, ELEMENT_ORDER), elementRefs) },
    { kind: "stat", label: "Average Pal power", labelKey: "palworld.averagePower", value: powerCount > 0 ? roundTo(powerTotal / powerCount, 1) : 0 },
    { kind: "stat", label: "Average Pal strike", labelKey: "palworld.averageStrike", value: strikeCount > 0 ? roundTo(strikeTotal / strikeCount, 1) : 0 },
    {
      kind: "table",
      label: "Pals by strike",
      labelKey: "palworld.strikeTable",
      columns: ["Strike", "Pals", "Average power"],
      columnKeys: ["palworld.strikeColumns.strike", "palworld.strikeColumns.pals", "palworld.strikeColumns.averagePower"],
      rows: strikeTableRows,
    },
    ...(workSegments.length > 0
      ? [{ kind: "bars", label: "Work suitability (★ needed by a Structure)", labelKey: "palworld.workSuitability", vocabulary: "palworld.workSuitability", segments: workSegments }]
      : []),
    ...(structureWorkRows.length > 0
      ? [{
          kind: "table",
          label: "Structure work",
          labelKey: "palworld.structureWork",
          columns: ["Work", "Structures", "Pals"],
          columnKeys: ["palworld.structureWorkColumns.work", "palworld.structureWorkColumns.structures", "palworld.structureWorkColumns.pals"],
          columnVocabularies: ["palworld.workSuitability", "", ""],
          rows: structureWorkRows,
        }]
      : []),
    ...(rarities.length > 0
      ? [{ kind: "donut", label: "Rarity", labelKey: "palworld.rarity", vocabulary: "palworld.rarity", segments: rarities }]
      : []),
  ];

  {
    const pile = mainDeck;
    const chanceHand = 5;
    // Distinct-card table: one row per distinct card (keyed by name) in the
    // match set, with the configured metric columns. All combinatorics are
    // inline — the sandbox cannot import a helper.
    const containsValue = (haystack, needle) => {
      if (Array.isArray(haystack)) {
        return haystack.indexOf(needle) !== -1;
      }
      if (haystack === undefined || haystack === null) {
        return false;
      }
      return String(haystack).indexOf(String(needle)) !== -1;
    };
    const lineCopies = new Map();
    const linePrintings = new Map();
    const lineCards = new Map();
    const lineOrder = [];
    let deckSize = 0;
    let matchTotal = 0;
    Object.keys(pile).forEach((ref) => {
      const quantity = Number(pile[ref]) || 0;
      if (quantity <= 0) {
        return;
      }
      deckSize = deckSize + quantity;
      const card = cardsById[ref];
      const row = { quantity: quantity, card: card, ref: ref };
      if (!(true)) {
        return;
      }
      matchTotal = matchTotal + quantity;
      const key = String(row.card !== null && row.card !== undefined && typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref);
      if (!lineCopies.has(key)) {
        lineCopies.set(key, 0);
        linePrintings.set(key, 0);
        lineCards.set(key, row);
        lineOrder.push(key);
      }
      lineCopies.set(key, lineCopies.get(key) + quantity);
      linePrintings.set(key, linePrintings.get(key) + 1);
    });

    // P(the opening hand contains none of a pool of `excluded` cards), drawing
    // `drawCount` without replacement — a running product of draw ratios so a
    // 60-card deck never overflows a factorial. 0 when the pool leaves too few
    // safe cards to fill the hand.
    const probNoneOf = (excluded, drawCount) => {
      if (deckSize - excluded < drawCount) {
        return 0;
      }
      let probability = 1;
      for (let i = 0; i < drawCount; i = i + 1) {
        probability = (probability * (deckSize - excluded - i)) / (deckSize - i);
      }
      return probability;
    };

    // Clamp to [0,1] and render as a 2-decimal percentage string.
    const formatPercent = (value) => {
      const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
      return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
    };

    const entries = lineOrder.map((key) => {
      const copies = lineCopies.get(key);
      return {
        key: key,
        copies: copies,
        printings: linePrintings.get(key),
        row: lineCards.get(key),
        otherMatches: matchTotal - copies,
      };
    });

    // Highest copy count first (== highest possible-starter odds for fixed
    // draws); ties broken by key.
    entries.sort((left, right) => {
      if (right.copies !== left.copies) {
        return right.copies - left.copies;
      }
      return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
    });

    widgets.push({
      kind: "table",
      label: "Chance to see",
      columns: ["Card", "Hand", "+1 draw", "+3 draws"],
      rows: entries.map((entry) => {
        const row = entry.row;
        return [entry.key, (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 1, deckSize)))), (formatPercent(1 - probNoneOf(entry.copies, Math.min(chanceHand + 3, deckSize))))];
      }),
    });
    const chanceTable = widgets[widgets.length - 1];
    chanceTable.labelKey = "chanceToSee";
    chanceTable.columnKeys = [
      "chanceToSeeColumns.card",
      "chanceToSeeColumns.openingHand",
      "chanceToSeeColumns.afterOneDraw",
      "chanceToSeeColumns.afterThreeDraws",
    ];
  }

  return { widgets };
}

// The rarity of the printing the pile names (its `metadata.rarity`), else the
// default printing's `game.rarity` (an identity ref, or a printing without
// one); lower-cased to the catalog's rarity ids. Null when neither is known.
function printingRarity(card, ref) {
  const printings = Array.isArray(card.printings) ? card.printings : [];
  const printing = printings.find((entry) => isRecord(entry) && entry.id === ref);
  const metadata = printing && isRecord(printing.metadata) ? printing.metadata : {};
  const game = cardGame(card);
  const rarity = typeof metadata.rarity === "string" && metadata.rarity.length > 0 ? metadata.rarity : game.rarity;

  return typeof rarity === "string" && rarity.length > 0 ? rarity.toLowerCase() : null;
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}
js
// Canonical Pokémon energy types, matched against spelled-out energy names.
const POKEMON_ENERGY_TYPES = ["Grass", "Fire", "Water", "Lightning", "Psychic", "Fighting", "Darkness", "Metal", "Fairy", "Dragon", "Colorless"];

// PTCGO/Live single-letter energy glyph codes -> canonical type. Basic and typed
// Special Energy print a {X} token ("Basic {L} Energy") rather than the spelled
// type, so the element is read off the glyph: {R} is Fire, {N} is Dragon.
const POKEMON_ENERGY_GLYPH_TYPES = { G: "Grass", R: "Fire", W: "Water", L: "Lightning", P: "Psychic", F: "Fighting", D: "Darkness", M: "Metal", Y: "Fairy", N: "Dragon", C: "Colorless" };

const RETREAT_LABELS = ["0", "1", "2", "3", "4+"];

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  let pokemon = 0;
  let trainer = 0;
  let energy = 0;
  let total = 0;
  let basicPokemon = 0;

  const energyTypeCounts = new Map();
  const retreatBuckets = Array.from({ length: 5 }, () => 0);
  const regulationCounts = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const supertypeRefs = new Map();
  const energyTypeRefs = new Map();
  const retreatRefs = new Map();
  const regulationRefs = new Map();

  Object.keys(deck).forEach((cardId) => {
    const quantity = deck[cardId];
    const card = catalog[cardId];
    const game = cardGame(card);
    const supertype = typeof game.supertype === "string" ? game.supertype : "";
    const subtypes = Array.isArray(game.subtypes) ? game.subtypes : [];

    total += quantity;

    // The catalog ships the accented "Pokémon" token; tolerate the ASCII form.
    if (supertype === "Pokémon" || supertype === "Pokemon") {
      pokemon += quantity;
      addRef(supertypeRefs, "pokemon", cardId);

      if (subtypes.indexOf("Basic") !== -1) {
        basicPokemon += quantity;
      }

      const retreat = Number.isFinite(game.convertedRetreatCost)
        ? Math.max(0, Math.floor(game.convertedRetreatCost))
        : 0;
      const retreatIndex = Math.min(retreat, 4);
      retreatBuckets[retreatIndex] += quantity;
      addRef(retreatRefs, retreatIndex, cardId);
    } else if (supertype === "Trainer") {
      trainer += quantity;
      addRef(supertypeRefs, "trainer", cardId);
    } else if (supertype === "Energy") {
      energy += quantity;
      addRef(supertypeRefs, "energy", cardId);

      // Energy-type donut counts ONLY Energy-supertype cards, so Pokémon (which
      // carry their own game.types) never leak into the energy breakdown. A basic
      // Energy derives its element from its identity id (or name); a special
      // Energy that declares an element uses it, and one with no element falls
      // into a "Special" bucket so the donut still sums to the deck's energy count.
      const energyTypes = pokemonCardEnergyTypes(card);
      const elements = Array.isArray(energyTypes)
        ? energyTypes.filter((type) => typeof type === "string" && type.length > 0)
        : [];
      if (elements.length > 0) {
        elements.forEach((type) => {
          energyTypeCounts.set(type, (energyTypeCounts.get(type) ?? 0) + quantity);
          addRef(energyTypeRefs, type, cardId);
        });
      } else {
        energyTypeCounts.set("Special", (energyTypeCounts.get("Special") ?? 0) + quantity);
        addRef(energyTypeRefs, "Special", cardId);
      }
    }

    // Regulation mark (A–J), when the card carries one. Basic energy is
    // format-evergreen (not rotation-relevant), so exclude it from the gauge;
    // Pokémon, Trainers, and special (non-basic) energy still count.
    const isBasicEnergy = supertype === "Energy" && subtypes.indexOf("Basic") !== -1;
    const mark = typeof game.regulationMark === "string" ? game.regulationMark : "";
    if (mark.length > 0 && !isBasicEnergy) {
      regulationCounts.set(mark, (regulationCounts.get(mark) ?? 0) + quantity);
      addRef(regulationRefs, mark, cardId);
    }
  });

  const breakdown = [
    { key: "pokemon", label: "Pokémon", value: pokemon, color: "" },
    { key: "trainer", label: "Trainer", value: trainer, color: "" },
    { key: "energy", label: "Energy", value: energy, color: "" },
  ]
    .filter((segment) => segment.value > 0)
    .map((segment) => ({ ...segment, cardRefs: supertypeRefs.get(segment.key) ?? [] }));

  // Mulligan: P(no Basic Pokémon in the opening 7). Running product of draw
  // ratios (no factorial). 0 when a basic can't be avoided (too few non-basics).
  const handSize = 7;
  const drawCount = Math.min(handSize, total);
  let mulligan = 0;
  if (total > 0 && total - basicPokemon >= drawCount) {
    let probability = 1;
    for (let i = 0; i < drawCount; i = i + 1) {
      probability = (probability * (total - basicPokemon - i)) / (total - i);
    }
    mulligan = probability;
  }

  const widgets = [];

  widgets.push({ kind: "donut", label: "Deck breakdown", labelKey: "pokemon.deckBreakdown", vocabulary: "pokemon.supertype", segments: breakdown });
  widgets.push({ kind: "stat", label: "Total cards", labelKey: "pokemon.totalCards", value: total });
  widgets.push({ kind: "donut", label: "Energy types", labelKey: "pokemon.energyTypes", vocabulary: "pokemon.energyType", segments: withCardRefs(energyTypeSegments(energyTypeCounts), energyTypeRefs) });
  widgets.push({ kind: "stat", label: "Mulligan chance", labelKey: "pokemon.mulliganChance", value: formatPercentValue(mulligan) });

  {
    // Distinct-card table: one row per distinct card (keyed by name) in the
    // match set, with the configured metric columns. All combinatorics are
    // inline — the sandbox cannot import a helper.
    const containsValue = (haystack, needle) => {
      if (Array.isArray(haystack)) {
        return haystack.indexOf(needle) !== -1;
      }
      if (haystack === undefined || haystack === null) {
        return false;
      }
      return String(haystack).indexOf(String(needle)) !== -1;
    };
    const lineCopies = new Map();
    const linePrintings = new Map();
    const lineCards = new Map();
    const lineOrder = [];
    let deckSize = 0;
    let matchTotal = 0;
    Object.keys(pile).forEach((ref) => {
      const quantity = Number(pile[ref]) || 0;
      if (quantity <= 0) {
        return;
      }
      deckSize = deckSize + quantity;
      const card = cardsById[ref];
      const row = { quantity: quantity, card: card, ref: ref };
      if (!(["Pokémon", "Pokemon"].indexOf(row.card?.game?.supertype) !== -1 && containsValue(row.card?.game?.subtypes, "Basic"))) {
        return;
      }
      matchTotal = matchTotal + quantity;
      const key = String(row.card !== null && row.card !== undefined && typeof row.card.name === "string" && row.card.name.length > 0 ? row.card.name : row.ref);
      if (!lineCopies.has(key)) {
        lineCopies.set(key, 0);
        linePrintings.set(key, 0);
        lineCards.set(key, row);
        lineOrder.push(key);
      }
      lineCopies.set(key, lineCopies.get(key) + quantity);
      linePrintings.set(key, linePrintings.get(key) + 1);
    });

    // P(the opening hand contains none of a pool of `excluded` cards), drawing
    // `drawCount` without replacement — a running product of draw ratios so a
    // 60-card deck never overflows a factorial. 0 when the pool leaves too few
    // safe cards to fill the hand.
    const probNoneOf = (excluded, drawCount) => {
      if (deckSize - excluded < drawCount) {
        return 0;
      }
      let probability = 1;
      for (let i = 0; i < drawCount; i = i + 1) {
        probability = (probability * (deckSize - excluded - i)) / (deckSize - i);
      }
      return probability;
    };

    // Clamp to [0,1] and render as a 2-decimal percentage string.
    const formatPercent = (value) => {
      const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
      return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
    };

    const entries = lineOrder.map((key) => {
      const copies = lineCopies.get(key);
      return {
        key: key,
        copies: copies,
        printings: linePrintings.get(key),
        row: lineCards.get(key),
        otherMatches: matchTotal - copies,
      };
    });

    // Highest copy count first (== highest possible-starter odds for fixed
    // draws); ties broken by key.
    entries.sort((left, right) => {
      if (right.copies !== left.copies) {
        return right.copies - left.copies;
      }
      return left.key < right.key ? -1 : left.key > right.key ? 1 : 0;
    });

    widgets.push({
      kind: "table",
      label: "Opening Hand Starters",
      columns: ["Pokémon", "Possible Starter", "Forced Starter"],
      rows: entries.map((entry) => {
        const row = entry.row;
        return [entry.key, formatPercent(1 - probNoneOf(entry.copies, Math.min(7, deckSize))), formatPercent(probNoneOf(entry.otherMatches, Math.min(7, deckSize)) - probNoneOf(entry.otherMatches + entry.copies, Math.min(7, deckSize)))];
      }),
    });
    const starterTable = widgets[widgets.length - 1];
    starterTable.labelKey = "pokemon.openingHandStarters";
    starterTable.columnKeys = [
      "pokemon.starterTable.pokemon",
      "pokemon.starterTable.possibleStarter",
      "pokemon.starterTable.forcedStarter",
    ];
  }

  widgets.push({ kind: "histogram", label: "Retreat cost", labelKey: "pokemon.retreatCost", buckets: retreatBuckets, labels: RETREAT_LABELS, bucketCardRefs: bucketRefList(retreatRefs, retreatBuckets.length) });
  widgets.push({ kind: "gauge", label: "Regulation marks", labelKey: "pokemon.regulationMarks", segments: withCardRefs(regulationSegments(regulationCounts), regulationRefs) });

  return { widgets: widgets };
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}

// Energy-type donut segments (canonical English type keys, or "Special"),
// highest count first.
function energyTypeSegments(counts) {
  const entries = [];
  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key: key, value: value });
    }
  });
  return entries
    .sort((left, right) => right.value - left.value)
    .map((entry) => ({ key: entry.key, label: entry.key, value: entry.value, color: "" }));
}

// Regulation-mark gauge segments, in alphabetical (A–J) mark order. Colors are
// left empty; the renderer fills them from its fallback palette.
function regulationSegments(counts) {
  const entries = [];
  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key: key, value: value });
    }
  });
  return entries
    .sort((left, right) => (left.key < right.key ? -1 : left.key > right.key ? 1 : 0))
    .map((entry) => ({ key: entry.key, label: entry.key, value: entry.value, color: "" }));
}

// The energy element an Energy card provides, read from its identity id. The
// catalog slugs every identity from its canonical English name in every locale
// ("basic-d-energy--935d278dfee1", "bubbly-w-energy--6fce5d2069c1"), while
// card.name is localized ("基本悪エネルギー" under /ja/), so the id is the
// locale-independent source.
function pokemonEnergyTypesFromId(id) {
  const slug = String(id === undefined || id === null ? "" : id).split("--")[0].toLowerCase();

  const glyph = slug.match(/(?:^|-)([a-z])-energy$/);
  if (glyph) {
    const type = POKEMON_ENERGY_GLYPH_TYPES[glyph[1].toUpperCase()];
    return type ? [type] : [];
  }

  const base = slug.replace(/^basic-/, "").replace(/-energy$/, "");
  return POKEMON_ENERGY_TYPES.filter((type) => type.toLowerCase() === base);
}

// The energy element(s) an Energy card provides, read from its NAME ("Fire
// Energy" -> Fire; "Basic {L} Energy" -> Lightning) — the fallback for ids that
// carry no element (printing-keyed or JP-only identities, multi-glyph names).
// {X} glyph tokens win; failing that, a spelled-out Basic Energy name is
// matched against the canonical types.
function pokemonEnergyTypesFromName(name) {
  const text = String(name === undefined || name === null ? "" : name);

  const glyphTypes = [];
  const glyphTokens = text.match(/\{[A-Za-z]\}/g) || [];
  glyphTokens.forEach((token) => {
    const type = POKEMON_ENERGY_GLYPH_TYPES[token.slice(1, 2).toUpperCase()];
    if (type && glyphTypes.indexOf(type) === -1) {
      glyphTypes.push(type);
    }
  });
  if (glyphTypes.length > 0) {
    return glyphTypes;
  }

  const base = text.replace(/^basic\s+/i, "").replace(/\s+energy$/i, "").trim().toLowerCase();
  return POKEMON_ENERGY_TYPES.filter((type) => type.toLowerCase() === base);
}

// The energy type(s) to group a card by. A Pokémon carries a declared game.types
// array, used as-is. An Energy card carries none, so its element is derived from
// its identity id, then its name. Any other card keeps its raw game.types
// (undefined for Trainers).
function pokemonCardEnergyTypes(card) {
  const game = cardGame(card);
  const declared = game.types;
  if (Array.isArray(declared) && declared.length > 0) {
    return declared;
  }
  if (game.supertype === "Energy") {
    const fromId = pokemonEnergyTypesFromId(isRecord(card) ? card.id : "");
    return fromId.length > 0 ? fromId : pokemonEnergyTypesFromName(isRecord(card) ? card.name : "");
  }
  return declared;
}
js
const ENERGY_CURVE_LABELS = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "+"];

// Might shares the 0–9 + overflow bucket shape of the energy curve.
const MIGHT_LABELS = ENERGY_CURVE_LABELS;

// Card types that sit in a separate zone, not the main deck; excluded from the
// energy curve, domain pips, and card-type breakdown. Runes are handled first
// (their own domain split) before this main-deck exclusion.
const EXCLUDED_ZONE_TYPES = ["legend", "rune", "battlefield"];

// Main-deck card types that are Units (Champions are Units) — the population of
// the Might distribution.
const UNIT_TYPES = ["unit", "champion"];

// Known domains in display order; unknown domain refs are not charted.
const DOMAIN_ORDER = ["body", "calm", "chaos", "fury", "mind", "order", "colorless", "neutral"];

// Card-type display order; unexpected types trail by count.
const TYPE_ORDER = ["champion", "unit", "spell", "gear"];

export default function compute(pile, cardsById) {
  const deck = normalizePile(pile);
  const catalog = isRecord(cardsById) ? cardsById : {};

  const energyBuckets = Array.from({ length: 11 }, () => 0);
  const mightBuckets = Array.from({ length: 11 }, () => 0);
  const domainCounts = new Map();
  const runeDomainCounts = new Map();
  const typeCounts = new Map();

  // The cards behind each bar and segment, so the deck page can highlight them.
  const energyRefs = new Map();
  const mightRefs = new Map();
  const domainRefs = new Map();
  const runeDomainRefs = new Map();
  const typeRefs = new Map();

  let energyTotal = 0;
  let mainCount = 0;

  Object.keys(deck).forEach((cardId) => {
    if (!isRecord(catalog[cardId])) {
      return;
    }

    const quantity = deck[cardId];
    const game = cardGame(catalog[cardId]);

    const type = typeof game.type === "string" && game.type.length > 0 ? game.type : "unknown";

    // The Rune deck has its own domain split (the mana base — 6/6 vs 8/4), read
    // off the rune zone alone and kept out of the main-deck counts.
    if (type === "rune") {
      addDomains(runeDomainCounts, runeDomainRefs, game.domains, quantity, cardId);
      return;
    }

    // Legend / battlefield cards are separate zones, not the main deck.
    if (EXCLUDED_ZONE_TYPES.indexOf(type) !== -1) {
      return;
    }

    // Riftbound uses energy as its cost.
    const energy = Number.isFinite(game.energy) ? Math.max(0, Math.floor(game.energy)) : 0;
    const energyIndex = Math.min(energy, 10);
    energyBuckets[energyIndex] += quantity;
    addRef(energyRefs, energyIndex, cardId);
    energyTotal += energy * quantity;
    mainCount += quantity;

    typeCounts.set(type, (typeCounts.get(type) ?? 0) + quantity);
    addRef(typeRefs, type, cardId);

    // Might distribution over Units (Champions are Units). Units with no numeric
    // might are skipped so missing data never piles into the 0 bucket.
    if (UNIT_TYPES.indexOf(type) !== -1 && Number.isFinite(game.might)) {
      const might = Math.max(0, Math.floor(game.might));
      const mightIndex = Math.min(might, 10);
      mightBuckets[mightIndex] += quantity;
      addRef(mightRefs, mightIndex, cardId);
    }

    addDomains(domainCounts, domainRefs, game.domains, quantity, cardId);
  });

  // Mean energy over the main deck (zone-excluded), to one decimal.
  const averageEnergy = mainCount > 0 ? Math.round((energyTotal / mainCount) * 10) / 10 : 0;

  // The balance of the three main card types. A ratio widget holds only two
  // values, so the three-way split renders as a small donut.
  const typeBalance = ["unit", "spell", "gear"].map((key) => ({
    key,
    label: titleCase(key),
    value: typeCounts.get(key) ?? 0,
    color: "",
    cardRefs: typeRefs.get(key) ?? [],
  }));

  const runeDomains = withCardRefs(orderedSegments(runeDomainCounts, DOMAIN_ORDER), runeDomainRefs);
  const hasMight = mightBuckets.some((count) => count > 0);

  // Like the panel, the rune split and Might chart only appear when they have data.
  return {
    widgets: [
      { kind: "bars", label: "Domains", labelKey: "riftbound.domains", vocabulary: "riftbound.domain", segments: withCardRefs(orderedSegments(domainCounts, DOMAIN_ORDER), domainRefs) },
      ...(runeDomains.length > 0
        ? [{ kind: "bars", label: "Rune domains", labelKey: "riftbound.runeDomains", vocabulary: "riftbound.domain", segments: runeDomains }]
        : []),
      { kind: "histogram", label: "Energy curve", labelKey: "riftbound.energyCurve", buckets: energyBuckets, labels: ENERGY_CURVE_LABELS, bucketCardRefs: bucketRefList(energyRefs, energyBuckets.length) },
      ...(hasMight
        ? [{ kind: "histogram", label: "Might", labelKey: "riftbound.might", buckets: mightBuckets, labels: MIGHT_LABELS, bucketCardRefs: bucketRefList(mightRefs, mightBuckets.length) }]
        : []),
      { kind: "donut", label: "Card types", labelKey: "riftbound.cardTypes", vocabulary: "riftbound.cardType", segments: withCardRefs(orderedSegments(typeCounts, TYPE_ORDER), typeRefs) },
      { kind: "stat", label: "Average energy", labelKey: "riftbound.averageEnergy", value: averageEnergy },
      { kind: "donut", label: "Unit / Spell / Gear", labelKey: "riftbound.typeBalance", vocabulary: "riftbound.cardType", segments: typeBalance },
    ],
  };
}

function normalizePile(pile) {
  if (!isRecord(pile)) {
    return {};
  }

  return Object.entries(pile).reduce((result, [cardId, quantity]) => {
    const normalizedQuantity = normalizeQuantity(quantity);

    if (normalizedQuantity > 0) {
      result[cardId] = normalizedQuantity;
    }

    return result;
  }, {});
}

function normalizeQuantity(value) {
  return Number.isFinite(value) ? Math.max(0, Math.floor(value)) : 0;
}

function cardGame(card) {
  return isRecord(card) && isRecord(card.game) ? card.game : {};
}

function isRecord(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}

function roundTo(value, digits) {
  const factor = Math.pow(10, digits);
  return Math.round(value * factor) / factor;
}

function titleCase(value) {
  return value.length > 0 ? value.slice(0, 1).toUpperCase() + value.slice(1) : value;
}

// Clamp to [0,1] and render as a 2-decimal percentage string.
function formatPercentValue(value) {
  const clamped = value < 0 ? 0 : value > 1 ? 1 : value;
  return (Math.round(clamped * 10000) / 100).toFixed(2) + "%";
}

// Segments in a fixed display order, then any unlisted key by count (highest
// first). Labels are English fallbacks (labels[key] when a labels map is
// given, else the title-cased key): the widget's vocabulary lets the web
// domain supply the localized label and the palette color.
function orderedSegments(counts, order, labels) {
  const rank = (key) => {
    const index = order.indexOf(key);
    return index === -1 ? order.length : index;
  };
  const entries = [];

  counts.forEach((value, key) => {
    if (value > 0) {
      entries.push({ key, value });
    }
  });

  return entries
    .sort((left, right) => rank(left.key) - rank(right.key) || right.value - left.value)
    .map((entry) => ({
      key: entry.key,
      label: labels ? (labels[entry.key] ?? entry.key) : titleCase(entry.key),
      value: entry.value,
      color: "",
    }));
}

// Remember a card's pile ref under a segment key or a bar index (each card
// once), so the deck page can highlight the cards a chart segment counts.
function addRef(refsByKey, key, ref) {
  const refs = refsByKey.get(key);
  if (refs === undefined) {
    refsByKey.set(key, [ref]);
  } else if (refs.indexOf(ref) === -1) {
    refs.push(ref);
  }
}

// Each segment with its card refs (collected with addRef by segment key).
function withCardRefs(segments, refsByKey) {
  return segments.map((segment) => ({ ...segment, cardRefs: refsByKey.get(segment.key) ?? [] }));
}

// A histogram's card refs per bar (collected with addRef by bar index),
// parallel to its buckets.
function bucketRefList(refsByIndex, length) {
  return Array.from({ length }, (_, index) => refsByIndex.get(index) ?? []);
}

function addDomains(counts, refsByDomain, domains, quantity, ref) {
  (Array.isArray(domains) ? domains : []).forEach((domain) => {
    if (DOMAIN_ORDER.indexOf(domain) !== -1) {
      counts.set(domain, (counts.get(domain) ?? 0) + quantity);
      addRef(refsByDomain, domain, ref);
    }
  });
}

Turny.gg documentation