Files

1424 lines
83 KiB
HTML
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!doctype html>
<html lang="en" data-theme="dark">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>Card Collection</title>
<meta name="theme-color" content="#100e1a">
<meta name="color-scheme" content="dark">
<link rel="manifest" href="manifest.json">
<link rel="apple-touch-icon" href="apple-touch-icon.png">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<style>
:root {
color-scheme: dark;
--bg: #100e1a; --surface: #1a1727; --surface-2: #231f33; --border: #2e2943;
--ink: #eeecf6; --ink-2: #b4afc6; --ink-3: #7e7894;
--accent: #8c7ff5; --accent-ink: #120f22; --accent-soft: #2b2550;
--bar: #8c7ff5; --bar-track: #2a253c; --gain: #4cc47e; --loss: #ef6b6b;
--shadow: 0 1px 2px rgba(0,0,0,.3), 0 4px 14px rgba(0,0,0,.25);
}
html { background: var(--bg); }
* { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0; background: var(--bg); color: var(--ink);
font: 15px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
padding-bottom: env(safe-area-inset-bottom);
}
button, input, select { font: inherit; color: inherit; }
.wrap { max-width: 1200px; margin: 0 auto; padding: 0 16px; }
header { padding: calc(18px + env(safe-area-inset-top)) 0 8px; }
.top { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; flex-wrap: wrap; }
h1 { font-size: 24px; margin: 0; letter-spacing: -.01em; }
.updated { color: var(--ink-3); font-size: 13px; }
.updated a { color: var(--accent); text-decoration: none; margin-left: 6px; }
.linkbtn { background: none; border: 0; padding: 0; margin-left: 8px; color: var(--accent); cursor: pointer; font-weight: 600; font-size: inherit; }
.syncst { margin-left: 8px; display: inline-flex; align-items: center; gap: 6px; }
.syncst.ok { color: var(--gain); } .syncst.err { color: var(--loss); }
.syncst a { margin-left: 2px; }
.spin { width: 12px; height: 12px; border: 2px solid var(--accent-soft); border-top-color: var(--accent); border-radius: 50%; animation: spin .8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
.steps { margin: 0 0 12px; padding-left: 20px; color: var(--ink-2); font-size: 14px; display: grid; gap: 6px; }
.steps a { color: var(--accent); }
.dlg input.tok { width: 100%; background: var(--bg); border: 1px solid var(--border); border-radius: 10px; padding: 9px 10px; margin-bottom: 4px; }
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 10px; margin: 14px 0 6px; }
.stat { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px; }
.stat .v { font-size: 22px; font-weight: 700; font-variant-numeric: tabular-nums; }
.stat .l { color: var(--ink-3); font-size: 12px; text-transform: uppercase; letter-spacing: .05em; }
.stat .d { font-size: 12px; font-variant-numeric: tabular-nums; }
.stat .d.up { color: var(--gain); } .stat .d.down { color: var(--loss); }
@media (max-width: 640px) { .stats { grid-template-columns: repeat(2, 1fr); } .stat .v { font-size: 19px; } }
.chips { display: flex; gap: 8px; overflow-x: auto; padding: 8px 0; scrollbar-width: none; }
.chips::-webkit-scrollbar { display: none; }
.chip {
flex: none; border: 1px solid var(--border); background: var(--surface); border-radius: 999px;
padding: 6px 12px; cursor: pointer; font-size: 14px; white-space: nowrap;
}
.chip .n { color: var(--ink-3); margin-left: 4px; font-variant-numeric: tabular-nums; }
.chip[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); border-color: var(--accent); }
.chip[aria-pressed="true"] .n { color: inherit; opacity: .75; }
nav.tabs { display: flex; gap: 4px; border-bottom: 1px solid var(--border); margin-top: 6px;
position: sticky; top: 0; background: var(--bg); z-index: 5; }
nav.tabs button {
background: none; border: 0; padding: 10px 14px; cursor: pointer; color: var(--ink-2);
border-bottom: 2px solid transparent; margin-bottom: -1px; font-weight: 600;
}
nav.tabs button[aria-selected="true"] { color: var(--ink); border-color: var(--accent); }
.controls { display: flex; gap: 8px; flex-wrap: wrap; margin: 14px 0; align-items: center; }
.controls input[type=search] { flex: 1 1 220px; min-width: 0; }
.controls input[type=search], .controls select {
background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 8px 10px;
}
.controls select { flex: 0 1 auto; max-width: 100%; }
.controls select option { background: var(--surface); color: var(--ink); }
.toggle input { accent-color: var(--accent); }
.toggle { display: inline-flex; gap: 6px; align-items: center; color: var(--ink-2); font-size: 14px; cursor: pointer; }
.count { color: var(--ink-3); font-size: 13px; margin-left: auto; }
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: 14px; }
@media (max-width: 420px) { .grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; } }
.card {
background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 8px;
cursor: pointer; text-align: left; display: flex; flex-direction: column; gap: 6px; box-shadow: var(--shadow); min-width: 0;
transition: transform .12s ease;
}
.card:hover { transform: translateY(-2px); }
.card .img { aspect-ratio: 63/88; border-radius: 7px; background: var(--surface-2); overflow: hidden; position: relative; }
.card img { width: 100%; height: 100%; object-fit: cover; display: block; }
.card .qty {
position: absolute; top: 6px; right: 6px; background: rgba(10,8,20,.78); color: #fff; font-size: 12px;
font-weight: 700; padding: 2px 7px; border-radius: 999px;
}
.card .nm { font-weight: 600; font-size: 14px; line-height: 1.25; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card .meta { color: var(--ink-3); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.card .pr { display: flex; justify-content: space-between; font-size: 13px; font-variant-numeric: tabular-nums; }
.card .pr b { font-weight: 700; }
.card .pr span { color: var(--ink-3); }
.ph { display: grid; place-items: center; height: 100%; color: var(--ink-3); font-size: 12px; padding: 8px; text-align: center; }
.sets { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 12px; margin-top: 14px; }
.set {
background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px;
cursor: pointer; text-align: left; display: grid; gap: 8px;
}
.set .hd { display: flex; align-items: center; gap: 10px; }
.set .hd img { width: 26px; height: 26px; object-fit: contain; }
.set .t { font-weight: 700; }
.set .s { color: var(--ink-3); font-size: 12px; }
.set .row { display: flex; justify-content: space-between; font-size: 13px; color: var(--ink-2); font-variant-numeric: tabular-nums; }
.bar { height: 8px; border-radius: 4px; background: var(--bar-track); overflow: hidden; }
.bar i { display: block; height: 100%; background: var(--bar); border-radius: 4px; }
.panels { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 14px; }
@media (max-width: 820px) { .panels { grid-template-columns: 1fr; } }
.panel { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 16px; min-width: 0; }
.panel.wide { grid-column: 1 / -1; }
.panel h2 { font-size: 15px; margin: 0 0 2px; }
.panel .sub { color: var(--ink-3); font-size: 13px; margin: 0 0 12px; }
.list { display: grid; gap: 2px; }
.li { display: grid; grid-template-columns: 36px 1fr auto; gap: 10px; align-items: center; padding: 6px; border-radius: 8px; cursor: pointer; }
.li:hover { background: var(--surface-2); }
.li img { width: 36px; height: 50px; object-fit: cover; border-radius: 4px; background: var(--surface-2); }
.li .a { min-width: 0; }
.li .a div { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.li .a .m { color: var(--ink-3); font-size: 12px; }
.li .p { font-variant-numeric: tabular-nums; font-weight: 600; text-align: right; }
.li .p small { display: block; color: var(--ink-3); font-weight: 400; }
.hbars { display: grid; gap: 10px; }
.hb { display: grid; grid-template-columns: minmax(90px, 160px) 1fr 64px; gap: 10px; align-items: center; font-size: 13px; position: relative; }
.hb .lbl { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--ink-2); }
.hb .track { height: 14px; position: relative; }
.hb .track i { position: absolute; left: 0; top: 0; bottom: 0; background: var(--bar); border-radius: 0 4px 4px 0; min-width: 2px; }
.hb .val { text-align: right; font-variant-numeric: tabular-nums; }
.hb:hover .track i { filter: brightness(1.12); }
.tip {
position: fixed; pointer-events: none; z-index: 50; background: var(--ink); color: var(--bg);
padding: 6px 9px; border-radius: 8px; font-size: 12px; line-height: 1.35; opacity: 0; transition: opacity .1s;
font-variant-numeric: tabular-nums; max-width: 240px;
}
.tip.on { opacity: 1; }
.chart svg { width: 100%; height: 200px; display: block; overflow: visible; }
.chart .grid-l { stroke: var(--border); stroke-width: 1; }
.chart .axis { fill: var(--ink-3); font-size: 11px; }
.chart .line { fill: none; stroke: var(--bar); stroke-width: 2; stroke-linejoin: round; stroke-linecap: round; }
.chart .area { fill: var(--bar); opacity: .12; }
.chart .dot { fill: var(--bar); stroke: var(--surface); stroke-width: 2; }
.chart .xh { stroke: var(--ink-3); stroke-width: 1; stroke-dasharray: 3 3; }
.empty { color: var(--ink-3); font-size: 14px; padding: 28px 8px; text-align: center; }
dialog {
border: 0; border-radius: 16px; padding: 0; background: var(--surface); color: var(--ink);
width: min(720px, calc(100vw - 32px)); max-height: calc(100dvh - 32px); box-shadow: 0 20px 60px rgba(0,0,0,.4);
}
dialog::backdrop { background: rgba(8,6,16,.6); backdrop-filter: blur(3px); }
.dlg { display: grid; grid-template-columns: minmax(0, 300px) 1fr; gap: 20px; padding: 20px; }
@media (max-width: 600px) { .dlg { grid-template-columns: 1fr; } .dlg .big { max-width: 260px; margin: 0 auto; } }
.dlg .big { width: 100%; aspect-ratio: 63/88; border-radius: 12px; overflow: hidden; background: var(--surface-2); }
.dlg .big img { width: 100%; height: 100%; object-fit: cover; }
.dlg h3 { margin: 0 0 4px; font-size: 20px; }
.dlg dl { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 14px 0; font-size: 14px; }
.dlg dt { color: var(--ink-3); }
.dlg dd { margin: 0; font-variant-numeric: tabular-nums; }
.btn {
display: inline-block; background: var(--accent); color: var(--accent-ink); border: 0; border-radius: 10px;
padding: 9px 14px; text-decoration: none; font-weight: 600; cursor: pointer;
}
.btn.ghost { background: var(--surface-2); color: var(--ink); }
.dlg .actions { display: flex; gap: 8px; flex-wrap: wrap; }
.loading { padding: 60px 0; text-align: center; color: var(--ink-3); }
.card.missing .img img { filter: grayscale(.85); opacity: .5; }
.card.missing .nm { color: var(--ink-2); }
.card .need {
position: absolute; top: 6px; left: 6px; background: var(--accent); color: var(--accent-ink); font-size: 11px;
font-weight: 700; padding: 2px 7px; border-radius: 999px;
}
.back { background: none; border: 0; color: var(--accent); cursor: pointer; padding: 14px 0 4px; font-weight: 600; }
.sethead { display: flex; align-items: center; gap: 12px; margin: 6px 0 14px; flex-wrap: wrap; }
.sethead img { height: 40px; max-width: 140px; object-fit: contain; }
.sethead h2 { margin: 0; font-size: 20px; }
.sethead .s { color: var(--ink-3); font-size: 13px; }
.setstats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }
@media (max-width: 760px) { .setstats { grid-template-columns: 1fr; } }
.setstats .stat .row { display: flex; justify-content: space-between; font-size: 13px; color: var(--ink-2); margin: 6px 0; font-variant-numeric: tabular-nums; }
.need-rar { display: flex; gap: 8px; flex-wrap: wrap; margin-top: 12px; }
.need-rar span { background: var(--surface); border: 1px solid var(--border); border-radius: 8px; padding: 5px 9px; font-size: 13px; color: var(--ink-2); font-variant-numeric: tabular-nums; }
.need-rar b { color: var(--ink); font-weight: 600; }
.seg { display: inline-flex; background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 2px; }
.seg button { background: none; border: 0; padding: 6px 12px; border-radius: 8px; cursor: pointer; color: var(--ink-2); font-size: 14px; }
.seg button[aria-pressed="true"] { background: var(--accent); color: var(--accent-ink); font-weight: 600; }
.up { color: var(--gain); } .down { color: var(--loss); }
.movers { display: grid; grid-template-columns: 1fr 1fr; gap: 18px; }
@media (max-width: 820px) { .movers { grid-template-columns: 1fr; } }
.movers h3 { font-size: 13px; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-3); margin: 0 0 6px; }
.panel .hrow { display: flex; justify-content: space-between; align-items: flex-start; gap: 12px; flex-wrap: wrap; }
/* ---------- decks ---------- */
.decks { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
.deck {
background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 14px;
cursor: pointer; text-align: left; display: grid; gap: 6px; min-width: 0;
}
.deck .cover { display: flex; height: 112px; margin-bottom: 4px; }
.deck .cover img { height: 112px; aspect-ratio: 63/88; object-fit: cover; border-radius: 6px; box-shadow: var(--shadow); background: var(--surface-2); }
.deck .cover img + img { margin-left: -46px; }
.deck .t { font-weight: 700; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.deck .s { color: var(--ink-3); font-size: 13px; font-variant-numeric: tabular-nums; }
.badge { display: inline-flex; align-items: center; gap: 5px; font-size: 12px; font-weight: 600; padding: 2px 8px; border-radius: 999px; width: fit-content; }
.badge.ok { background: rgba(76,196,126,.15); color: var(--gain); }
.badge.warn { background: rgba(242,190,80,.15); color: #f2be50; }
.badge.err { background: rgba(239,107,107,.15); color: var(--loss); }
.dhead { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin: 6px 0 12px; }
.dhead .dname {
flex: 1 1 240px; min-width: 0; font-size: 20px; font-weight: 700; background: transparent; border: 1px solid transparent;
border-radius: 10px; padding: 4px 8px; margin-left: -8px;
}
.dhead .dname:hover, .dhead .dname:focus { border-color: var(--border); background: var(--surface); outline: none; }
.dhead select { background: var(--surface); border: 1px solid var(--border); border-radius: 10px; padding: 8px 10px; }
.btn.danger { color: var(--loss); }
.btn:disabled { opacity: .5; cursor: default; }
.dsum { position: sticky; top: 41px; z-index: 4; background: var(--bg); padding: 8px 0; display: grid; gap: 8px; }
.dsum .row1 { display: flex; align-items: baseline; gap: 14px; flex-wrap: wrap; font-variant-numeric: tabular-nums; }
.dsum .big { font-size: 22px; font-weight: 700; }
.dsum .big.full { color: var(--gain); }
.dsum .big.over { color: var(--loss); }
.dsum .parts { color: var(--ink-2); font-size: 14px; }
.dsum .val { margin-left: auto; color: var(--ink-2); font-size: 14px; }
.dsum .bar { height: 6px; }
.dsum .bar i.full { background: var(--gain); }
.dsum .bar i.over { background: var(--loss); }
@media (max-width: 600px) { .dsum .val { display: none; } .dsum .big { font-size: 19px; } .dsum .parts { font-size: 13px; } }
.checks { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 12px; }
.dbuild { display: grid; grid-template-columns: minmax(300px, 380px) 1fr; gap: 16px; align-items: start; }
.dpane-seg { display: none; margin-bottom: 10px; }
@media (max-width: 860px) {
.dbuild { grid-template-columns: 1fr; }
.dpane-seg { display: inline-flex; }
.dbuild[data-pane="deck"] .dpick, .dbuild[data-pane="add"] .dlist { display: none; }
}
.dlist { background: var(--surface); border: 1px solid var(--border); border-radius: 12px; padding: 10px; position: sticky; top: 112px; max-height: calc(100dvh - 128px); overflow: auto; }
@media (max-width: 860px) { .dlist { position: static; max-height: none; } }
.dlist h3 { font-size: 12px; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-3); margin: 10px 6px 4px; display: flex; justify-content: space-between; }
.dlist h3:first-child { margin-top: 2px; }
.drow { display: grid; grid-template-columns: 32px 1fr auto; gap: 10px; align-items: center; padding: 4px 6px; border-radius: 8px; }
.drow:hover { background: var(--surface-2); }
.drow .th { width: 32px; height: 45px; border-radius: 4px; overflow: hidden; background: var(--surface-2); cursor: pointer; }
.drow .th img { width: 100%; height: 100%; object-fit: cover; display: block; }
.drow.ghost .th img { filter: grayscale(.85); opacity: .5; }
.drow .a { min-width: 0; }
.drow .a div { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 14px; }
.drow .a .m { color: var(--ink-3); font-size: 12px; }
.drow .a .m .needs { color: #f2be50; }
.drow .a .m .bad { color: var(--loss); }
.qc { display: inline-flex; align-items: center; gap: 2px; font-variant-numeric: tabular-nums; }
.qc b { min-width: 22px; text-align: center; }
.qc button {
width: 28px; height: 28px; border-radius: 8px; border: 1px solid var(--border); background: var(--surface-2);
cursor: pointer; display: grid; place-items: center; font-size: 16px; line-height: 1; padding: 0;
}
.qc button:disabled { opacity: .35; cursor: default; }
.pips { display: inline-flex; gap: 3px; vertical-align: -1px; }
.pip { width: 11px; height: 11px; border-radius: 50%; display: inline-block; box-shadow: inset 0 0 0 1px rgba(0,0,0,.25); }
.dpick .controls { margin-top: 0; }
.dpick .grid { grid-template-columns: repeat(auto-fill, minmax(118px, 1fr)); gap: 10px; }
@media (max-width: 420px) { .dpick .grid { grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px; } }
.card.pick { padding: 6px; gap: 4px; }
.card.pick .nm { font-size: 13px; }
.card.pick .meta { font-size: 11px; }
.card.pick.out .img img { filter: grayscale(.8); opacity: .45; }
.card.pick.out { cursor: default; }
.card.pick.out:hover { transform: none; }
.card .indeck {
position: absolute; bottom: 6px; left: 6px; background: var(--accent); color: var(--accent-ink); font-size: 12px;
font-weight: 700; padding: 2px 7px; border-radius: 999px;
}
.dlg textarea {
width: 100%; min-height: 260px; background: var(--bg); border: 1px solid var(--border); border-radius: 10px;
padding: 10px; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical;
}
.dlg.one { grid-template-columns: 1fr; }
.dlg p { color: var(--ink-2); margin: 6px 0 12px; font-size: 14px; }
.attacks { display: grid; gap: 4px; }
.attacks div { display: flex; gap: 8px; align-items: center; }
.attacks .dmg { margin-left: auto; font-weight: 700; }
</style>
</head>
<body>
<div class="wrap">
<header>
<div class="top">
<h1>Card Collection</h1>
<div class="updated" id="updated"></div>
</div>
<div class="stats" id="stats"></div>
<div class="chips" id="brands" role="group" aria-label="Brand"></div>
</header>
<nav class="tabs" role="tablist">
<button role="tab" data-tab="cards" aria-selected="true">Cards</button>
<button role="tab" data-tab="sets" aria-selected="false">Sets</button>
<button role="tab" data-tab="insights" aria-selected="false">Insights</button>
<button role="tab" data-tab="decks" aria-selected="false">Decks</button>
</nav>
<main id="main"><div class="loading">Loading collection…</div></main>
</div>
<dialog id="dlg"></dialog>
<div class="tip" id="tip"></div>
<script>
const REPO = "krburchel/card-collection";
const $ = (s, el = document) => el.querySelector(s);
const esc = s => String(s ?? "").replace(/[&<>"']/g, c => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
const money = n => n == null ? "—" : "$" + n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
const moneyShort = n => n >= 1000 ? "$" + (n / 1000).toFixed(n >= 10000 ? 0 : 1) + "k" : "$" + Math.round(n);
const num = n => n.toLocaleString();
const owned = c => (c.price || 0) * c.qty;
// Prefer our backed-up copy in images/cards/; fall back to Rare Candy's image host if it's missing
function cardImg(c, large, attrs = "") {
const local = large ? (c.imgLargeFile || c.imgFile) : c.imgFile;
const remote = large ? (c.imgLarge || c.img) : c.img;
const src = local || remote;
if (!src) return "";
const fb = local && remote ? ` onerror="this.onerror=null;this.src='${esc(remote)}'"` : "";
return `<img src="${esc(src)}"${fb} ${attrs}>`;
}
const cardNo = c => parseInt(String(c.number).replace(/^\D+/, ""), 10) || 0;
const store = {
get(k, d) { try { return JSON.parse(localStorage.getItem("cc:" + k)) ?? d; } catch { return d; } },
set(k, v) { try { localStorage.setItem("cc:" + k, JSON.stringify(v)); } catch {} },
};
const state = {
all: [], history: [], prices: {}, updatedAt: null,
setDetail: null, setCache: {}, setShow: "missing", setSort: "number", setQ: "",
moverDays: store.get("moverDays", 7),
brand: store.get("brand", "all"),
tab: store.get("tab", "cards"),
q: "", set: "", rarity: "", sort: store.get("sort", "owned"), dupes: false,
info: {}, tcgSets: {}, pool: [], poolById: new Map(),
decks: store.get("decks", []), deckId: store.get("deckId", null),
deckPane: "deck", dq: "", dsuper: "all", dtype: "", dlegal: true,
};
async function load() {
const bust = "?t=" + Date.now();
const get = p => fetch(p + bust, { cache: "no-store" }).then(r => r.ok ? r.json() : null).catch(() => null);
const [rc, manual, hist, prices, info, tcgSets] = await Promise.all([get("data/rarecandy.json"), get("data/manual.json"),
get("data/history.json"), get("data/prices.json"), get("data/cardinfo.json"), get("data/tcgsets.json")]);
state.prices = prices || {};
state.info = info || {};
state.tcgSets = tcgSets || {};
state.setCache = {};
state.all = [...(rc?.cards || []), ...(manual?.cards || [])];
state.history = hist || [];
state.updatedAt = rc?.updatedAt;
buildPool();
if (state.brand !== "all" && !state.all.some(c => c.brand === state.brand)) state.brand = "all";
render();
}
function inBrand() { return state.brand === "all" ? state.all : state.all.filter(c => c.brand === state.brand); }
function groupSets(cards) {
const m = new Map();
for (const c of cards) {
const k = c.brand + "|" + c.set;
if (!m.has(k)) m.set(k, { key: k, setId: c.setId || "", logo: c.setLogo, name: c.set || "No set", brand: c.brand, release: c.setRelease || "", total: c.setTotal, symbol: c.setSymbol, numbers: new Set(), value: 0, copies: 0, unique: 0 });
const s = m.get(k);
if (c.category !== "SEALED") s.numbers.add(c.number || c.id);
s.value += owned(c); s.copies += c.qty; s.unique++;
}
return [...m.values()];
}
/* ---------- price history ----------
prices.json stores change points per card: [[date, price], ...]. The price
on a day is the latest point on or before it; before the first point it's unknown. */
const isoDay = d => d.toISOString().slice(0, 10);
const daysAgo = n => isoDay(new Date(Date.now() - n * 864e5));
function priceOn(id, day) {
const pts = state.prices[id];
if (!pts) return null;
let p = null;
for (const [d, v] of pts) { if (d <= day) p = v; else break; }
return p;
}
function priceChange(c, days) {
const base = priceOn(c.id, daysAgo(days));
if (base == null || c.price == null) return null;
return { base, delta: c.price - base, pct: base ? (c.price - base) / base * 100 : null };
}
function trackingSince() {
let first = null;
for (const pts of Object.values(state.prices)) if (pts[0] && (!first || pts[0][0] < first)) first = pts[0][0];
return first;
}
const signed = n => (n > 0 ? "+" : n < 0 ? "−" : "") + money(Math.abs(n));
const pctStr = p => p == null ? "" : (p > 0 ? "+" : p < 0 ? "−" : "") + Math.abs(p).toFixed(Math.abs(p) < 10 ? 1 : 0) + "%";
/* ---------- header ---------- */
function renderHeader() {
const cards = inBrand();
const value = cards.reduce((a, c) => a + owned(c), 0);
const copies = cards.reduce((a, c) => a + c.qty, 0);
const sets = groupSets(cards).length;
let delta = "";
const h = state.history;
if (state.brand === "all" && h.length >= 2) {
const prev = h[h.length - 2], d = h[h.length - 1].value - prev.value;
if (Math.abs(d) >= 0.01) delta = `<div class="d ${d > 0 ? "up" : "down"}">${d > 0 ? "▲" : "▼"} ${money(Math.abs(d))} since ${fmtDate(prev.date)}</div>`;
}
$("#stats").innerHTML = `
<div class="stat"><div class="l">Value</div><div class="v">${money(value)}</div>${delta}</div>
<div class="stat"><div class="l">Unique cards</div><div class="v">${num(cards.length)}</div></div>
<div class="stat"><div class="l">Total copies</div><div class="v">${num(copies)}</div></div>
<div class="stat"><div class="l">Sets</div><div class="v">${num(sets)}</div></div>`;
const counts = {};
for (const c of state.all) counts[c.brand] = (counts[c.brand] || 0) + 1;
const brands = Object.keys(counts).sort((a, b) => counts[b] - counts[a]);
$("#brands").innerHTML = [["all", "All", state.all.length], ...brands.map(b => [b, b, counts[b]])]
.map(([k, label, n]) => `<button class="chip" data-brand="${esc(k)}" aria-pressed="${state.brand === k}">${esc(label)}<span class="n">${n}</span></button>`).join("");
$("#brands").style.display = brands.length > 1 ? "" : "none";
$("#updated").innerHTML = (state.updatedAt ? `Synced from Rare Candy ${timeAgo(state.updatedAt)}` : "") + `<span id="syncst"></span>`;
drawSync();
}
function fmtDate(iso) { return new Date(iso + "T12:00:00").toLocaleDateString(undefined, { month: "short", day: "numeric" }); }
function timeAgo(iso) {
const s = (Date.now() - new Date(iso)) / 1000;
if (s < 90) return "just now";
if (s < 3600) return Math.round(s / 60) + " min ago";
if (s < 86400) return Math.round(s / 3600) + " hr ago";
return new Date(iso).toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
/* ---------- cards tab ---------- */
const SORTS = {
owned: ["Owned value (high→low)", (a, b) => owned(b) - owned(a)],
price: ["Card price (high→low)", (a, b) => (b.price || 0) - (a.price || 0)],
qty: ["Quantity (most)", (a, b) => b.qty - a.qty || (b.price || 0) - (a.price || 0)],
set: ["Set & number", (a, b) => (b.setRelease || "").localeCompare(a.setRelease || "") || a.set.localeCompare(b.set) || cardNo(a) - cardNo(b)],
name: ["Name (A→Z)", (a, b) => a.name.localeCompare(b.name)],
};
function renderCards() {
const base = inBrand();
const sets = [...new Set(base.map(c => c.set))].sort();
const rarities = [...new Set(base.map(c => c.rarity).filter(Boolean))].sort();
if (state.set && !sets.includes(state.set)) state.set = "";
if (state.rarity && !rarities.includes(state.rarity)) state.rarity = "";
$("#main").innerHTML = `
<div class="controls">
<input type="search" id="q" placeholder="Search name, set, number…" value="${esc(state.q)}" autocomplete="off">
<select id="fset" aria-label="Set"><option value="">All sets</option>${sets.map(s => `<option ${s === state.set ? "selected" : ""}>${esc(s)}</option>`).join("")}</select>
<select id="frar" aria-label="Rarity"><option value="">All rarities</option>${rarities.map(s => `<option ${s === state.rarity ? "selected" : ""}>${esc(s)}</option>`).join("")}</select>
<select id="fsort" aria-label="Sort">${Object.entries(SORTS).map(([k, [l]]) => `<option value="${k}" ${k === state.sort ? "selected" : ""}>${l}</option>`).join("")}</select>
<label class="toggle"><input type="checkbox" id="fdup" ${state.dupes ? "checked" : ""}> Duplicates only</label>
<span class="count" id="count"></span>
</div>
<div class="grid" id="grid"></div>`;
$("#q").addEventListener("input", e => { state.q = e.target.value; drawGrid(); });
$("#fset").addEventListener("change", e => { state.set = e.target.value; drawGrid(); });
$("#frar").addEventListener("change", e => { state.rarity = e.target.value; drawGrid(); });
$("#fsort").addEventListener("change", e => { state.sort = e.target.value; store.set("sort", state.sort); drawGrid(); });
$("#fdup").addEventListener("change", e => { state.dupes = e.target.checked; drawGrid(); });
drawGrid();
}
function drawGrid() {
const terms = state.q.toLowerCase().split(/\s+/).filter(Boolean);
const list = inBrand().filter(c => {
if (state.set && c.set !== state.set) return false;
if (state.rarity && c.rarity !== state.rarity) return false;
if (state.dupes && c.qty < 2) return false;
if (terms.length) {
const hay = `${c.name} ${c.set} ${c.number} ${c.rarity} ${c.brand}`.toLowerCase();
return terms.every(t => hay.includes(t));
}
return true;
}).sort(SORTS[state.sort][1]);
const copies = list.reduce((a, c) => a + c.qty, 0), value = list.reduce((a, c) => a + owned(c), 0);
$("#count").textContent = `${num(list.length)} cards · ${num(copies)} copies · ${money(value)}`;
$("#grid").innerHTML = list.length ? list.map(cardTile).join("") : `<div class="empty" style="grid-column:1/-1">No cards match.</div>`;
}
function cardTile(c) {
const img = cardImg(c, false, `alt="" loading="lazy" decoding="async"`) || `<div class="ph">${esc(c.name)}</div>`;
return `<button class="card" data-id="${esc(c.id)}">
<div class="img">${img}${c.qty > 1 ? `<span class="qty">×${c.qty}</span>` : ""}</div>
<div class="nm" title="${esc(c.name)}">${esc(c.name)}</div>
<div class="meta">${esc(c.set)}${c.number ? " · #" + esc(c.number) : ""}</div>
<div class="pr"><b>${money(c.price)}</b>${c.qty > 1 ? `<span>${money(owned(c))}</span>` : ""}</div>
</button>`;
}
/* ---------- sets tab ---------- */
function renderSets() {
if (state.setDetail) return renderSetDetail(state.setDetail);
const sets = groupSets(inBrand()).sort((a, b) => b.release.localeCompare(a.release) || a.name.localeCompare(b.name));
$("#main").innerHTML = `<div class="sets">${sets.map(s => {
const have = s.numbers.size, pct = s.total ? Math.min(100, have / s.total * 100) : null;
return `<button class="set" data-set="${esc(s.name)}" data-setid="${esc(s.setId)}" data-brand="${esc(s.brand)}">
<div class="hd">${s.symbol ? `<img src="${esc(s.symbol)}" alt="" loading="lazy">` : ""}
<div><div class="t">${esc(s.name)}</div><div class="s">${esc(s.brand)}${s.release ? " · " + s.release.slice(0, 4) : ""}</div></div></div>
${pct != null ? `<div class="row"><span>${have} / ${s.total} cards</span><b>${pct.toFixed(pct < 10 ? 1 : 0)}%</b></div>
<div class="bar" role="progressbar" aria-valuenow="${Math.round(pct)}" aria-valuemin="0" aria-valuemax="100"><i style="width:${pct}%"></i></div>`
: `<div class="row"><span>${s.unique} cards</span></div>`}
<div class="row"><span>${num(s.copies)} copies</span><span>${money(s.value)}</span></div>
</button>`;
}).join("")}</div>`;
}
// "199/165" -> {n: 199, printed: 165}; secret rares are numbered past the printed total
function parseNo(number) {
const m = String(number).match(/(\d+)\s*\/\s*(\d+)/);
return m ? { n: +m[1], printed: +m[2] } : { n: parseInt(String(number).replace(/^\D+/, ""), 10) || 0, printed: null };
}
async function loadSet(setId) {
if (!state.setCache[setId]) {
state.setCache[setId] = fetch(`data/sets/${encodeURIComponent(setId)}.json?t=${Date.now()}`, { cache: "no-store" })
.then(r => r.ok ? r.json() : null).catch(() => null);
}
return state.setCache[setId];
}
async function renderSetDetail(setId) {
const mine = state.all.filter(c => c.setId === setId);
const meta = mine[0] || {};
$("#main").innerHTML = `<button class="back" data-back>← All sets</button><div class="loading">Loading set…</div>`;
const data = await loadSet(setId);
if (state.tab !== "sets" || state.setDetail !== setId) return;
if (!data) {
$("#main").innerHTML = `<button class="back" data-back>← All sets</button><div class="empty">This set's card list hasn't synced yet. It refreshes once a day.</div>`;
return;
}
const ownedById = new Map(mine.map(c => [c.id, c]));
const list = data.cards.map(c => ({
...c, set: data.name, setId, brand: meta.brand || "", qty: ownedById.get(c.id)?.qty || 0,
imgFile: ownedById.get(c.id)?.imgFile, imgLargeFile: ownedById.get(c.id)?.imgLargeFile,
...parseNo(c.number),
}));
const printed = list.find(c => c.printed)?.printed;
const isBase = c => !printed || c.n <= printed;
const summarize = cards => {
const miss = cards.filter(c => !c.qty);
return { total: cards.length, have: cards.length - miss.length, missing: miss.length,
cost: miss.reduce((a, c) => a + (c.price || 0), 0), priced: miss.every(c => c.price != null) };
};
const all = summarize(list), base = summarize(list.filter(isBase)), secret = summarize(list.filter(c => !isBase(c)));
const missRar = {};
for (const c of list) if (!c.qty) { const r = c.rarity || "—"; (missRar[r] ||= { n: 0, v: 0 }); missRar[r].n++; missRar[r].v += c.price || 0; }
const statBox = (label, s, note) => {
const pct = s.total ? s.have / s.total * 100 : 0;
return `<div class="stat"><div class="l">${label}</div>
<div class="v">${s.have} / ${s.total}</div>
<div class="bar" style="margin:8px 0"><i style="width:${pct}%"></i></div>
<div class="row"><span>${s.missing ? `${s.missing} missing` : "Complete!"}</span><b>${s.missing ? (s.priced ? "" : "~") + money(s.cost) + " to finish" : "🎉"}</b></div>
${note ? `<div class="row" style="color:var(--ink-3)">${note}</div>` : ""}</div>`;
};
$("#main").innerHTML = `<button class="back" data-back>← All sets</button>
<div class="sethead">
${meta.setLogo ? `<img src="${esc(meta.setLogo)}" alt="">` : ""}
<div><h2>${esc(data.name)}</h2><div class="s">${esc(meta.brand || "")}${meta.setRelease ? " · " + esc(meta.setRelease) : ""} · prices refreshed ${esc(fmtDate(data.fetchedOn))}</div></div>
</div>
<div class="setstats">
${statBox("Full set", all)}
${printed && secret.total ? statBox(`Main set (#1–${printed})`, base) + statBox(`Secret rares (#${printed + 1}+)`, secret) : ""}
</div>
${all.missing ? `<div class="need-rar">${Object.entries(missRar).sort((a, b) => b[1].v - a[1].v)
.map(([r, v]) => `<span><b>${v.n}</b> ${esc(r)} · ${money(v.v)}</span>`).join("")}</div>` : ""}
<div class="controls">
<div class="seg" role="group" aria-label="Show">
${[["missing", `Missing (${all.missing})`], ["owned", `Owned (${all.have})`], ["all", "All"]]
.map(([k, l]) => `<button data-setshow="${k}" aria-pressed="${state.setShow === k}">${l}</button>`).join("")}
</div>
<input type="search" id="sq" placeholder="Search this set…" value="${esc(state.setQ)}" autocomplete="off">
<select id="ssort" aria-label="Sort">
<option value="number" ${state.setSort === "number" ? "selected" : ""}>Card number</option>
<option value="price" ${state.setSort === "price" ? "selected" : ""}>Price (high→low)</option>
<option value="priceAsc" ${state.setSort === "priceAsc" ? "selected" : ""}>Price (low→high)</option>
</select>
<span class="count" id="scount"></span>
</div>
<div class="grid" id="sgrid"></div>`;
const draw = () => {
const terms = state.setQ.toLowerCase().split(/\s+/).filter(Boolean);
const shown = list.filter(c =>
(state.setShow === "all" || (state.setShow === "missing" ? !c.qty : c.qty)) &&
terms.every(t => `${c.name} ${c.number} ${c.rarity}`.toLowerCase().includes(t)))
.sort({ number: (a, b) => a.n - b.n, price: (a, b) => (b.price || 0) - (a.price || 0), priceAsc: (a, b) => (a.price || 0) - (b.price || 0) }[state.setSort]);
state.setShown = list;
$("#scount").textContent = `${shown.length} cards · ${money(shown.reduce((a, c) => a + (c.price || 0), 0))}`;
$("#sgrid").innerHTML = shown.length ? shown.map(c => c.qty ? cardTile(c) : `<button class="card missing" data-id="${esc(c.id)}">
<div class="img">${cardImg(c, false, `alt="" loading="lazy" decoding="async"`) || `<div class="ph">${esc(c.name)}</div>`}<span class="need">Need</span></div>
<div class="nm" title="${esc(c.name)}">${esc(c.name)}</div>
<div class="meta">#${esc(c.number)} · ${esc(c.rarity)}</div>
<div class="pr"><b>${money(c.price)}</b></div></button>`).join("")
: `<div class="empty" style="grid-column:1/-1">${state.setShow === "missing" && !all.missing ? "You have every card in this set!" : "No cards match."}</div>`;
};
$("#sq").addEventListener("input", e => { state.setQ = e.target.value; draw(); });
$("#ssort").addEventListener("change", e => { state.setSort = e.target.value; draw(); });
draw();
}
/* ---------- insights tab ---------- */
function renderInsights() {
const cards = inBrand();
const top = [...cards].sort((a, b) => (b.price || 0) - (a.price || 0)).slice(0, 10);
const dupes = cards.filter(c => c.qty > 1).map(c => ({ c, extra: c.qty - 1, val: (c.qty - 1) * (c.price || 0) }))
.sort((a, b) => b.val - a.val);
const extraCopies = dupes.reduce((a, d) => a + d.extra, 0), extraVal = dupes.reduce((a, d) => a + d.val, 0);
const sets = groupSets(cards).sort((a, b) => b.value - a.value);
const maxV = Math.max(...sets.map(s => s.value), 1);
const rar = {};
for (const c of cards) { const r = c.rarity || "—"; (rar[r] ||= { n: 0, v: 0 }); rar[r].n += c.qty; rar[r].v += owned(c); }
const rarList = Object.entries(rar).sort((a, b) => b[1].v - a[1].v);
const maxR = Math.max(...rarList.map(([, r]) => r.v), 1);
const li = (c, right) => `<div class="li" data-id="${esc(c.id)}">
${cardImg(c, false, `alt="" loading="lazy"`) || `<img alt="">`}
<div class="a"><div>${esc(c.name)}</div><div class="m">${esc(c.set)}${c.number ? " · #" + esc(c.number) : ""} · ${esc(c.rarity)}</div></div>
<div class="p">${right}</div></div>`;
$("#main").innerHTML = `<div class="panels">
<section class="panel wide">
<h2>Collection value over time</h2>
<p class="sub">${state.brand === "all" ? "Rare Candy collection value, one point per day." : "Shown for All brands only."}</p>
<div class="chart" id="hist"></div>
</section>
<section class="panel wide" id="movers"></section>
<section class="panel">
<h2>Most valuable cards</h2><p class="sub">By single-card market price</p>
<div class="list">${top.map(c => li(c, `${money(c.price)}${c.qty > 1 ? `<small>×${c.qty}</small>` : ""}`)).join("") || `<div class="empty">No cards yet.</div>`}</div>
</section>
<section class="panel">
<h2>Value by set</h2><p class="sub">Owned value (price × quantity)</p>
<div class="hbars">${sets.map(s => `<div class="hb" data-tip="${esc(s.name)}<br>${money(s.value)} · ${num(s.copies)} copies">
<span class="lbl">${esc(s.name)}</span><span class="track"><i style="width:${s.value / maxV * 100}%"></i></span><span class="val">${moneyShort(s.value)}</span></div>`).join("")}</div>
<h2 style="margin-top:22px">Value by rarity</h2><p class="sub">Owned value and copies per rarity</p>
<div class="hbars">${rarList.map(([r, v]) => `<div class="hb" data-tip="${esc(r)}<br>${money(v.v)} · ${num(v.n)} copies">
<span class="lbl">${esc(r)}</span><span class="track"><i style="width:${v.v / maxR * 100}%"></i></span><span class="val">${moneyShort(v.v)}</span></div>`).join("")}</div>
</section>
<section class="panel wide">
<h2>Duplicates & trade bait</h2>
<p class="sub">${num(extraCopies)} extra copies worth ${money(extraVal)} beyond one of each</p>
<div class="list" style="grid-template-columns:repeat(auto-fill,minmax(280px,1fr));display:grid">
${dupes.slice(0, 30).map(d => li(d.c, `+${d.extra}<small>${money(d.val)}</small>`)).join("") || `<div class="empty">No duplicates.</div>`}
</div>
</section>
</div>`;
drawHistory();
drawMovers(cards, li);
}
function drawMovers(cards, li) {
const days = state.moverDays, since = trackingSince();
const moves = cards.map(c => ({ c, ch: priceChange(c, days) })).filter(m => m.ch);
const changed = moves.filter(m => Math.abs(m.ch.delta) >= 0.01);
const impact = changed.reduce((a, m) => a + m.ch.delta * m.c.qty, 0);
const up = changed.filter(m => m.ch.delta > 0).sort((a, b) => b.ch.delta - a.ch.delta).slice(0, 8);
const down = changed.filter(m => m.ch.delta < 0).sort((a, b) => a.ch.delta - b.ch.delta).slice(0, 8);
const row = m => li(m.c, `<span class="${m.ch.delta > 0 ? "up" : "down"}">${signed(m.ch.delta)}</span>
<small>${money(m.ch.base)} → ${money(m.c.price)} · ${pctStr(m.ch.pct)}${m.c.qty > 1 ? ` · ×${m.c.qty}` : ""}</small>`);
let body;
if (!moves.length) {
const ready = since ? new Date(Date.parse(since + "T00:00:00Z") + days * 864e5) : null;
body = `<div class="empty">Price tracking started ${since ? fmtDate(since) : "today"}.
${ready ? `${days}-day changes show up around ${ready.toLocaleDateString(undefined, { month: "short", day: "numeric", timeZone: "UTC" })}.` : ""}</div>`;
} else if (!changed.length) {
body = `<div class="empty">No price changes in the last ${days === 1 ? "day" : days + " days"}.</div>`;
} else {
body = `<div class="movers">
<div><h3>Gainers</h3><div class="list">${up.map(row).join("") || `<div class="empty">None</div>`}</div></div>
<div><h3>Decliners</h3><div class="list">${down.map(row).join("") || `<div class="empty">None</div>`}</div></div></div>`;
}
$("#movers").innerHTML = `<div class="hrow">
<div><h2>Price movers</h2><p class="sub">${changed.length
? `${changed.length} cards moved · price changes ${impact >= 0 ? "added" : "cost"} <b class="${impact >= 0 ? "up" : "down"}">${money(Math.abs(impact))}</b> over the last ${days === 1 ? "day" : days + " days"}`
: "Change in market price per card"}</p></div>
<div class="seg" role="group" aria-label="Period">${[[1, "1D"], [7, "7D"], [30, "30D"]]
.map(([d, l]) => `<button data-movers="${d}" aria-pressed="${days === d}">${l}</button>`).join("")}</div>
</div>${body}`;
}
function drawHistory() {
const el = $("#hist");
const h = state.brand === "all" ? state.history : [];
if (h.length < 2) {
el.innerHTML = `<div class="empty">${h.length ? `${money(h[0].value)} on ${fmtDate(h[0].date)}. The trend line appears once there are two days of data.` : "No history yet."}</div>`;
return;
}
const W = el.clientWidth || 600, H = 200, P = { l: 46, r: 10, t: 10, b: 24 };
const vals = h.map(p => p.value);
let lo = Math.min(...vals), hi = Math.max(...vals);
const pad = (hi - lo) * 0.15 || hi * 0.05 || 1; lo = Math.max(0, lo - pad); hi += pad;
const x = i => P.l + i / (h.length - 1) * (W - P.l - P.r);
const y = v => P.t + (1 - (v - lo) / (hi - lo)) * (H - P.t - P.b);
const ticks = [0, 0.5, 1].map(f => lo + f * (hi - lo));
const pts = h.map((p, i) => `${x(i).toFixed(1)},${y(p.value).toFixed(1)}`);
const xIdx = [...new Set([0, Math.floor((h.length - 1) / 2), h.length - 1])];
el.innerHTML = `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Collection value over time">
${ticks.map(t => `<line class="grid-l" x1="${P.l}" x2="${W - P.r}" y1="${y(t)}" y2="${y(t)}"/><text class="axis" x="${P.l - 6}" y="${y(t) + 4}" text-anchor="end">${moneyShort(t)}</text>`).join("")}
${xIdx.map(i => `<text class="axis" x="${x(i)}" y="${H - 6}" text-anchor="${i === 0 ? "start" : i === h.length - 1 ? "end" : "middle"}">${fmtDate(h[i].date)}</text>`).join("")}
<path class="area" d="M${pts[0]} L${pts.join(" L")} L${x(h.length - 1)},${H - P.b} L${x(0)},${H - P.b} Z"/>
<polyline class="line" points="${pts.join(" ")}"/>
<line class="xh" id="xh" y1="${P.t}" y2="${H - P.b}" style="display:none"/>
<circle class="dot" id="hd" r="5" style="display:none"/>
<circle class="dot" r="4" cx="${x(h.length - 1)}" cy="${y(vals[vals.length - 1])}"/>
<rect x="${P.l}" y="0" width="${W - P.l - P.r}" height="${H}" fill="transparent" id="hz"/>
</svg>`;
const svg = $("svg", el), hz = $("#hz", el), xh = $("#xh", el), hd = $("#hd", el);
const move = e => {
const r = svg.getBoundingClientRect(), px = (e.clientX - r.left) * (W / r.width);
const i = Math.max(0, Math.min(h.length - 1, Math.round((px - P.l) / (W - P.l - P.r) * (h.length - 1))));
xh.setAttribute("x1", x(i)); xh.setAttribute("x2", x(i)); xh.style.display = "";
hd.setAttribute("cx", x(i)); hd.setAttribute("cy", y(h[i].value)); hd.style.display = "";
showTip(e, `<b>${fmtDate(h[i].date)}</b><br>${money(h[i].value)}<br>${num(h[i].unique)} cards · ${num(h[i].copies)} copies`);
};
hz.addEventListener("pointermove", move);
hz.addEventListener("pointerleave", () => { xh.style.display = hd.style.display = "none"; hideTip(); });
}
/* ---------- decks ----------
Decks live in this browser's localStorage. Each entry is one printing:
{id, name, code, no, super, n}. `id` points at an owned card (or "e:Fire" for
basic Energy, which nobody tracks); entries without a matching owned card, or
with more copies than owned, show as cards you still need. */
const TYPES = ["Grass", "Fire", "Water", "Lightning", "Psychic", "Fighting", "Darkness", "Metal", "Dragon", "Colorless"];
const TYPE_COLOR = { Grass: "#5fb85a", Fire: "#ef6b4a", Water: "#4ea3e8", Lightning: "#f2c94c", Psychic: "#b072d8",
Fighting: "#c9774a", Darkness: "#3f4a5a", Metal: "#9aa3ad", Dragon: "#b39b3c", Colorless: "#d8d3c8" };
const TYPE_SYM = { G: "Grass", R: "Fire", W: "Water", L: "Lightning", P: "Psychic", F: "Fighting", D: "Darkness", M: "Metal" };
const SUPERS = ["Pokémon", "Trainer", "Energy"];
const FORMATS = { casual: "Casual", standard: "Standard", expanded: "Expanded" };
const DECK_SIZE = 60, MAX_COPIES = 4;
// Standard is regulation mark H and later; G rotated out on Mar 26 (PTCG Live) / Apr 10, 2026
const STANDARD_FROM = "H";
const BASIC_ENERGY = TYPES.slice(0, 8).map((t, i) => ({
id: "e:" + t, name: `Basic ${t} Energy`, set: "Basic Energy", number: String(i + 1), qty: Infinity, price: null, virtual: true,
img: `https://images.scrydex.com/pokemon/sve-${i + 1}/small`, imgLarge: `https://images.scrydex.com/pokemon/sve-${i + 1}/large`,
info: { super: "Energy", sub: ["Basic"], types: [t], code: "SVE", no: String(i + 1), expanded: true },
}));
function buildPool() {
state.pool = [
...state.all.filter(c => state.info[c.id]?.super).map(c => ({ ...c, info: state.info[c.id] })),
...BASIC_ENERGY,
];
state.poolById = new Map(state.pool.map(c => [c.id, c]));
}
const isBasicEnergy = i => i?.super === "Energy" && i.sub?.includes("Basic");
const isBasicPokemon = i => i?.super === "Pokémon" && i.sub?.includes("Basic");
const nameKey = s => String(s).toLowerCase().replace(/\s+/g, " ").trim();
// true / false, or null when the regulation mark is unknown
function legalIn(info, format) {
if (format === "casual" || isBasicEnergy(info)) return true;
if (!info) return null;
if (format === "standard") return info.mark ? info.mark >= STANDARD_FROM : null;
return !!info.expanded;
}
function stageOf(i) {
if (!i) return "";
if (i.super !== "Pokémon") return i.sub?.filter(s => !["Future", "Ancient"].includes(s)).join(" · ") || i.super;
return i.sub.find(s => /^(Basic|Stage \d)$/.test(s)) || i.sub[0] || "";
}
const pips = types => `<span class="pips">${(types || []).map(t => `<i class="pip" style="background:${TYPE_COLOR[t] || "#888"}" title="${esc(t)}"></i>`).join("")}</span>`;
const scrydexImg = (code, no, size = "small") => {
const s = code && state.tcgSets[code];
return s && no ? `https://images.scrydex.com/pokemon/${s.id}-${no}/${size}` : null;
};
function saveDecks() { store.set("decks", state.decks); }
const currentDeck = () => state.decks.find(d => d.id === state.deckId);
function entryFor(c) {
return { id: c.id, name: c.name, code: c.info.code || null, no: c.info.no || null, super: c.info.super, n: 0 };
}
// Rows for display: each deck entry split into the copies you own and the ones you'd still need
function resolveDeck(deck) {
return deck.cards.filter(e => e.n > 0).map((e, idx) => {
const c = e.id ? state.poolById.get(e.id) : null;
const have = c ? Math.min(e.n, c.qty) : 0;
const info = c?.info || null;
const card = c || { id: null, name: e.name, set: state.tcgSets[e.code]?.name || e.code || "", number: e.no || "",
img: scrydexImg(e.code, e.no), imgLarge: scrydexImg(e.code, e.no, "large"), price: null };
return { e, idx: deck.cards.indexOf(e), c: card, info, owned: !!c, n: e.n, have, need: e.n - have,
super: info?.super || e.super || "Other" };
});
}
function nameCount(deck, name) {
const k = nameKey(name);
return deck.cards.reduce((a, e) => a + (nameKey(e.name) === k ? e.n : 0), 0);
}
// How many copies of each owned card the other decks use
function usageElsewhere(deck) {
const m = new Map();
for (const d of state.decks) if (d !== deck) for (const e of d.cards) if (e.id) m.set(e.id, (m.get(e.id) || 0) + e.n);
return m;
}
function deckSummary(deck) {
const rows = resolveDeck(deck);
const total = rows.reduce((a, r) => a + r.n, 0);
const by = { "Pokémon": 0, Trainer: 0, Energy: 0, Other: 0 };
for (const r of rows) by[SUPERS.includes(r.super) ? r.super : "Other"] += r.n;
const need = rows.reduce((a, r) => a + r.need, 0);
const value = rows.reduce((a, r) => a + r.have * (r.c.price || 0), 0);
const issues = [];
if (total !== DECK_SIZE) issues.push({ lvl: total > DECK_SIZE ? "err" : "warn", t: total > DECK_SIZE ? `${total - DECK_SIZE} too many cards` : `${DECK_SIZE - total} more cards to reach ${DECK_SIZE}` });
if (total && !rows.some(r => isBasicPokemon(r.info) || (!r.info && r.super === "Pokémon"))) issues.push({ lvl: "err", t: "Needs at least one Basic Pokémon" });
const names = new Map();
for (const r of rows) if (!isBasicEnergy(r.info) && !/^basic \w+ energy$/i.test(r.e.name)) {
const k = nameKey(r.e.name);
names.set(k, { name: r.e.name, n: (names.get(k)?.n || 0) + r.n });
}
for (const { name, n } of names.values()) if (n > MAX_COPIES) issues.push({ lvl: "err", t: `${n}× ${name} (max ${MAX_COPIES})` });
const ace = rows.filter(r => r.info?.sub?.includes("ACE SPEC")).reduce((a, r) => a + r.n, 0);
if (ace > 1) issues.push({ lvl: "err", t: `${ace} ACE SPEC cards (max 1)` });
const radiant = rows.filter(r => r.info?.sub?.includes("Radiant")).reduce((a, r) => a + r.n, 0);
if (radiant > 1) issues.push({ lvl: "err", t: `${radiant} Radiant Pokémon (max 1)` });
if (deck.format !== "casual") {
const bad = rows.filter(r => r.info && legalIn(r.info, deck.format) === false);
if (bad.length) issues.push({ lvl: "err", t: `${bad.reduce((a, r) => a + r.n, 0)} not ${FORMATS[deck.format]}-legal: ${[...new Set(bad.map(r => r.c.name))].slice(0, 3).join(", ")}${bad.length > 3 ? "…" : ""}`, rows: bad });
const unk = rows.filter(r => r.info && legalIn(r.info, deck.format) == null);
if (unk.length) issues.push({ lvl: "warn", t: `Couldn't check legality of ${unk.map(r => r.c.name).join(", ")}` });
}
// Evolutions need what they evolve from (Rare Candy lets a Stage 2 skip its Stage 1)
const pokeNames = new Set(rows.filter(r => r.super === "Pokémon").map(r => nameKey(r.c.name)));
const hasRareCandy = rows.some(r => nameKey(r.c.name) === "rare candy");
const orphans = rows.filter(r => r.info?.from && !pokeNames.has(nameKey(r.info.from)) && !(hasRareCandy && r.info.sub.includes("Stage 2")));
for (const r of orphans) issues.push({ lvl: "warn", t: `${r.c.name} evolves from ${r.info.from}, which isn't in the deck` });
if (need) issues.push({ lvl: "warn", t: `${need} card${need > 1 ? "s" : ""} you don't own yet` });
const other = usageElsewhere(deck);
const shared = rows.filter(r => r.owned && r.c.qty !== Infinity && r.have + (other.get(r.c.id) || 0) > r.c.qty);
if (shared.length) issues.push({ lvl: "warn", t: `Shares copies with other decks: ${shared.map(r => r.c.name).slice(0, 3).join(", ")}${shared.length > 3 ? "…" : ""}` });
const ready = total === DECK_SIZE && !issues.some(i => i.lvl === "err") && !need;
return { rows, total, by, need, value, issues, ready };
}
function statusBadge(s) {
if (!s.total) return `<span class="badge warn">Empty</span>`;
if (s.ready) return `<span class="badge ok">✓ Ready to play</span>`;
const errs = s.issues.filter(i => i.lvl === "err").length;
if (errs) return `<span class="badge err">${errs} problem${errs > 1 ? "s" : ""}</span>`;
if (s.total !== DECK_SIZE) return `<span class="badge warn">${s.total} / ${DECK_SIZE}</span>`;
if (s.need) return `<span class="badge warn">Need ${s.need} card${s.need > 1 ? "s" : ""}</span>`;
return `<span class="badge warn">Check warnings</span>`;
}
function newDeck(name = "New deck", cards = [], format = "casual") {
const d = { id: Math.random().toString(36).slice(2, 10), name, format, cards, created: Date.now(), updated: Date.now() };
state.decks.unshift(d); saveDecks();
openDeck(d.id);
return d;
}
function openDeck(id) { state.deckId = id; store.set("deckId", id); state.deckPane = id ? "deck" : state.deckPane; render(); scrollTo({ top: 0 }); }
function touch(deck) { deck.updated = Date.now(); saveDecks(); }
function renderDecks() {
if (state.deckId && !currentDeck()) { state.deckId = null; store.set("deckId", null); }
if (state.deckId) return renderDeckEditor(currentDeck());
const noInfo = state.pool.length <= BASIC_ENERGY.length;
const decks = [...state.decks].sort((a, b) => b.updated - a.updated);
$("#main").innerHTML = `
<div class="controls">
<button class="btn" data-newdeck>+ New deck</button>
<button class="btn ghost" data-importdeck>Import deck list</button>
<span class="count">${decks.length ? `${decks.length} deck${decks.length > 1 ? "s" : ""} · saved in this browser` : ""}</span>
</div>
${noInfo ? `<div class="empty">Card types (Pokémon / Trainer / Energy) haven't synced yet. Run the sync and they'll show up here.</div>` : ""}
${decks.length ? `<div class="decks">${decks.map(deckTile).join("")}</div>` : `<div class="empty">
Build a 60-card deck from the cards you own. It keeps track of the 4-copy rule, Basic Pokémon,
evolution lines and Standard / Expanded legality.<br><br>
Or paste a deck list (from Pokémon TCG Live or Limitless) to see how much of it you already own.</div>`}`;
}
function deckTile(d) {
const s = deckSummary(d);
const covers = [...s.rows].filter(r => r.super === "Pokémon")
.sort((a, b) => (!!b.info?.sub?.includes("ex") - !!a.info?.sub?.includes("ex")) || (b.c.price || 0) - (a.c.price || 0)).slice(0, 3);
const types = [...new Set(s.rows.filter(r => r.super === "Pokémon").flatMap(r => r.info?.types || []))].slice(0, 4);
return `<button class="deck" data-deck="${esc(d.id)}">
<div class="cover">${covers.map(r => cardImg(r.c, false, `alt="" loading="lazy"`)).join("") || `<img alt="">`}</div>
<div class="t">${esc(d.name)}</div>
<div class="s">${FORMATS[d.format]} · ${s.total} cards · ${money(s.value)} ${pips(types)}</div>
${statusBadge(s)}
</button>`;
}
function renderDeckEditor(deck) {
$("#main").innerHTML = `<button class="back" data-deckback>← All decks</button>
<div class="dhead">
<input class="dname" id="dname" value="${esc(deck.name)}" aria-label="Deck name" autocomplete="off">
<select id="dformat" aria-label="Format">${Object.entries(FORMATS).map(([k, l]) => `<option value="${k}" ${deck.format === k ? "selected" : ""}>${l}</option>`).join("")}</select>
<button class="btn ghost" data-deckexport>Copy list</button>
<button class="btn ghost" data-deckdup>Duplicate</button>
<button class="btn ghost danger" data-deckdel>Delete</button>
</div>
<div class="dsum" id="dsum"></div>
<div class="checks" id="dchecks"></div>
<div class="seg dpane-seg" role="group" aria-label="Show" id="dpaneseg"></div>
<div class="dbuild" data-pane="${state.deckPane}">
<section class="dlist" id="dlist"></section>
<section class="dpick">
<div class="controls">
<input type="search" id="dq" placeholder="Search your cards, attacks…" value="${esc(state.dq)}" autocomplete="off">
<div class="seg" role="group" aria-label="Card type">${["all", ...SUPERS].map(k =>
`<button data-dsuper="${k}" aria-pressed="${state.dsuper === k}">${k === "all" ? "All" : k}</button>`).join("")}</div>
<select id="dtype" aria-label="Energy type"><option value="">All types</option>${TYPES.map(t => `<option ${state.dtype === t ? "selected" : ""}>${t}</option>`).join("")}</select>
<label class="toggle" id="dlegalwrap"><input type="checkbox" id="dlegal" ${state.dlegal ? "checked" : ""}> Legal only</label>
<span class="count" id="dcount"></span>
</div>
<div class="grid" id="dgrid"></div>
</section>
</div>`;
$("#dname").addEventListener("input", e => { deck.name = e.target.value || "Untitled deck"; touch(deck); });
$("#dformat").addEventListener("change", e => { deck.format = e.target.value; touch(deck); refreshDeck(); });
$("#dq").addEventListener("input", e => { state.dq = e.target.value; drawPicker(deck); });
$("#dtype").addEventListener("change", e => { state.dtype = e.target.value; drawPicker(deck); });
$("#dlegal").addEventListener("change", e => { state.dlegal = e.target.checked; drawPicker(deck); });
refreshDeck();
}
function refreshDeck() {
const deck = currentDeck();
if (!deck || state.tab !== "decks" || !$("#dlist")) return;
const s = deckSummary(deck);
const cls = s.total === DECK_SIZE ? "full" : s.total > DECK_SIZE ? "over" : "";
$("#dsum").innerHTML = `<div class="row1">
<span class="big ${cls}">${s.total} / ${DECK_SIZE}</span>
<span class="parts">${SUPERS.map(k => `${k} ${s.by[k]}`).join(" · ")}${s.by.Other ? ` · Unknown ${s.by.Other}` : ""}</span>
<span class="val">${money(s.value)} owned${s.need ? ` · ${s.need} needed` : ""}</span>
</div>
<div class="bar"><i class="${cls}" style="width:${Math.min(100, s.total / DECK_SIZE * 100)}%"></i></div>`;
$("#dchecks").innerHTML = s.ready ? `<span class="badge ok">✓ Ready to play${deck.format !== "casual" ? ` in ${FORMATS[deck.format]}` : ""}</span>`
: s.issues.map(i => `<span class="badge ${i.lvl}">${esc(i.t)}</span>`).join("");
$("#dpaneseg").innerHTML = [["deck", `Deck (${s.total})`], ["add", "Add cards"]]
.map(([k, l]) => `<button data-dpane="${k}" aria-pressed="${state.deckPane === k}">${l}</button>`).join("");
$("#dlegalwrap").style.display = deck.format === "casual" ? "none" : "";
drawDeckList(deck, s);
drawPicker(deck);
}
// Keep evolution lines together: sort Pokémon by the Basic they start from, then by stage
function evoSort(rows) {
const from = new Map(rows.filter(r => r.info?.from).map(r => [nameKey(r.c.name), nameKey(r.info.from)]));
const root = n => { const seen = new Set(); while (from.has(n) && !seen.has(n)) { seen.add(n); n = from.get(n); } return n; };
const depth = n => { let d = 0; const seen = new Set(); while (from.has(n) && !seen.has(n)) { seen.add(n); n = from.get(n); d++; } return d; };
return rows.sort((a, b) => root(nameKey(a.c.name)).localeCompare(root(nameKey(b.c.name)))
|| depth(nameKey(a.c.name)) - depth(nameKey(b.c.name)) || a.c.name.localeCompare(b.c.name));
}
const TRAINER_ORDER = ["Supporter", "Item", "Pokémon Tool", "Stadium"];
const trainerRank = i => { const k = TRAINER_ORDER.findIndex(t => i?.sub?.includes(t)); return k < 0 ? 9 : k; };
function drawDeckList(deck, s) {
if (!s.rows.length) {
$("#dlist").innerHTML = `<div class="empty">No cards yet. ${matchMedia("(max-width: 860px)").matches ? "Tap <b>Add cards</b>" : "Click cards on the right"} to add them.</div>`;
return;
}
const groups = [...SUPERS, "Other"].map(k => {
let rows = s.rows.filter(r => (SUPERS.includes(r.super) ? r.super : "Other") === k);
if (k === "Pokémon") rows = evoSort(rows);
else if (k === "Trainer") rows.sort((a, b) => trainerRank(a.info) - trainerRank(b.info) || b.n - a.n || a.c.name.localeCompare(b.c.name));
else rows.sort((a, b) => b.n - a.n || a.c.name.localeCompare(b.c.name));
return [k, rows];
}).filter(([, rows]) => rows.length);
const other = usageElsewhere(deck);
$("#dlist").innerHTML = groups.map(([k, rows]) => `<h3><span>${k === "Other" ? "Not in your collection" : k}</span><span>${rows.reduce((a, r) => a + r.n, 0)}</span></h3>
${rows.map(r => {
const can = canAdd(deck, r);
const meta = [r.e.code && r.e.no ? `${r.e.code} ${r.e.no}` : r.c.set, r.info ? stageOf(r.info) : ""].filter(Boolean).join(" · ");
const shared = r.owned && r.c.qty !== Infinity && r.have + (other.get(r.c.id) || 0) > r.c.qty;
const illegal = deck.format !== "casual" && r.info && legalIn(r.info, deck.format) === false;
return `<div class="drow ${r.need ? "ghost" : ""}">
<div class="th" ${r.owned && !r.c.virtual ? `data-id="${esc(r.c.id)}"` : ""}>${cardImg(r.c, false, `alt="" loading="lazy"`)}</div>
<div class="a"><div title="${esc(r.c.name)}">${r.info?.types?.length ? pips(r.info.types) + " " : ""}${esc(r.c.name)}</div>
<div class="m">${esc(meta)}${r.need ? ` · <span class="needs">need ${r.need}</span>` : ""}${shared ? ` · <span class="needs">shared</span>` : ""}${illegal ? ` · <span class="bad">not ${FORMATS[deck.format]}</span>` : ""}</div></div>
<div class="qc"><button data-ddec="${r.idx}" aria-label="Remove one">−</button><b>${r.n}</b>
<button data-dinc="${r.idx}" aria-label="Add one" ${can.ok ? "" : `disabled title="${esc(can.why)}"`}>+</button></div>
</div>`;
}).join("")}`).join("");
}
// Can one more copy go in? Owned entries are capped at the copies you own.
function canAdd(deck, r) {
const basicE = isBasicEnergy(r.info) || /^basic \w+ energy$/i.test(r.e?.name || r.c.name);
if (!basicE && nameCount(deck, r.c.name) >= MAX_COPIES) return { ok: false, why: `Max ${MAX_COPIES} cards named ${r.c.name}` };
if (r.owned && r.n >= r.c.qty) return { ok: false, why: `You own ${r.c.qty}` };
return { ok: true };
}
function addCard(deck, c) {
let e = deck.cards.find(x => x.id === c.id);
const r = { owned: true, c, info: c.info, n: e?.n || 0, e };
if (!canAdd(deck, r).ok) return;
// Adding an owned copy fills a matching "need" slot from an imported list first
const same = x => !x.id && nameKey(x.name) === nameKey(c.name) && (c.info.super !== "Pokémon" || !x.code || x.code === c.info.code);
const ghost = deck.cards.find(x => same(x) && x.n > 0);
if (ghost) ghost.n--;
if (!e) { e = entryFor(c); deck.cards.push(e); }
e.n++;
deck.cards = deck.cards.filter(x => x.n > 0);
touch(deck); refreshDeck();
}
function drawPicker(deck) {
const terms = state.dq.toLowerCase().split(/\s+/).filter(Boolean);
const inDeck = new Map(deck.cards.filter(e => e.id).map(e => [e.id, e.n]));
let hidden = 0;
const list = state.pool.filter(c => {
const i = c.info;
if (state.dsuper !== "all" && i.super !== state.dsuper) return false;
if (state.dtype && !(i.types || []).includes(state.dtype)) return false;
if (terms.length) {
const hay = `${c.name} ${c.set} ${i.super} ${(i.sub || []).join(" ")} ${(i.types || []).join(" ")} ${(i.attacks || []).map(a => a.n).join(" ")} ${(i.abilities || []).join(" ")} ${i.from || ""}`.toLowerCase();
if (!terms.every(t => hay.includes(t))) return false;
}
if (state.dlegal && deck.format !== "casual" && legalIn(i, deck.format) === false) { hidden++; return false; }
return true;
}).sort((a, b) => SUPERS.indexOf(a.info.super) - SUPERS.indexOf(b.info.super)
|| (a.info.super === "Pokémon" ? TYPES.indexOf(a.info.types?.[0]) - TYPES.indexOf(b.info.types?.[0]) : 0)
|| (a.info.super === "Trainer" ? trainerRank(a.info) - trainerRank(b.info) : 0)
|| (!!a.virtual - !!b.virtual) || a.name.localeCompare(b.name) || cardNo(a) - cardNo(b));
$("#dcount").textContent = `${list.length} cards${hidden ? ` · ${hidden} hidden (not ${FORMATS[deck.format]}-legal)` : ""}`;
$("#dgrid").innerHTML = list.length ? list.map(c => {
const n = inDeck.get(c.id) || 0;
const can = canAdd(deck, { owned: true, c, info: c.info, n });
const left = c.qty === Infinity ? "" : `<span class="qty">${c.qty - n} left</span>`;
const i = c.info;
const meta = i.super === "Pokémon" ? `${stageOf(i)}${i.hp ? " · " + i.hp + " HP" : ""}` : stageOf(i);
const illegal = deck.format !== "casual" && legalIn(i, deck.format) === false;
return `<button class="card pick ${can.ok ? "" : "out"}" data-dadd="${esc(c.id)}" title="${esc(can.ok ? (illegal ? `Not ${FORMATS[deck.format]}-legal` : "Add to deck") : can.why)}">
<div class="img">${cardImg(c, false, `alt="" loading="lazy" decoding="async"`) || `<div class="ph">${esc(c.name)}</div>`}${left}${n ? `<span class="indeck">×${n}</span>` : ""}</div>
<div class="nm" title="${esc(c.name)}">${i.types?.length ? pips(i.types) + " " : ""}${esc(c.name)}</div>
<div class="meta">${esc(meta)}${illegal ? " · ⚠" : ""}</div>
</button>`;
}).join("") : `<div class="empty" style="grid-column:1/-1">No cards match.</div>`;
}
/* ----- deck lists in Pokémon TCG Live format ----- */
function exportDeck(deck) {
const s = deckSummary(deck);
const sections = [...SUPERS, "Other"].map(k => [k, s.rows.filter(r => (SUPERS.includes(r.super) ? r.super : "Other") === k)]).filter(([, r]) => r.length);
// Owned and still-needed copies of one printing go on one line
const lines = rows => {
const m = new Map();
for (const r of rows) {
const t = `${r.e.name}${r.e.code && r.e.no ? ` ${r.e.code} ${r.e.no}` : ""}`;
m.set(t, (m.get(t) || 0) + r.n);
}
return [...m].map(([t, n]) => `${n} ${t}`).join("\n");
};
return sections.map(([k, rows]) => `${k}: ${rows.reduce((a, r) => a + r.n, 0)}\n${lines(rows)}`).join("\n\n")
+ `\n\nTotal Cards: ${s.total}\n`;
}
function parseDeckList(text) {
let section = null;
const out = [];
for (let raw of text.split(/\r?\n/)) {
const line = raw.trim().replace(/^[*•\-]\s*/, "");
if (!line || /^total cards/i.test(line)) continue;
const sec = line.match(/^(pok[eé]mon|trainers?|energy)\b[^0-9]*\d*\)?\s*$/i);
if (sec) { section = /^pok/i.test(sec[1]) ? "Pokémon" : /^t/i.test(sec[1]) ? "Trainer" : "Energy"; continue; }
const m = line.match(/^(\d+)x?\s+(.+?)(?:\s+([A-Z][A-Z0-9-]{1,6})\s+([A-Z]{0,4}\d+[a-z]?))?$/);
if (m) out.push({ n: +m[1], name: m[2].trim(), code: m[3] === "PR-SV" ? "SVP" : m[3] || null, no: m[4] || null, super: section });
}
return out;
}
// Match a pasted list against the collection. Exact printing first; then any
// printing with the same name (for Pokémon only within the same set, since
// different printings usually have different attacks). The rest is "need".
function importDeck(text) {
const wanted = parseDeckList(text);
if (!wanted.length) return null;
const cards = [], used = new Map();
const take = (c, n) => {
const free = c.qty === Infinity ? n : Math.max(0, c.qty - (used.get(c.id) || 0));
const k = Math.min(n, free);
if (!k) return 0;
used.set(c.id, (used.get(c.id) || 0) + k);
const e = cards.find(x => x.id === c.id);
if (e) e.n += k; else cards.push({ ...entryFor(c), n: k });
return k;
};
for (const w of wanted) {
let left = w.n;
const energy = w.name.match(/^(?:basic\s+)?(?:\{([GRWLPFDM])\}|(grass|fire|water|lightning|psychic|fighting|darkness|metal))\s+energy$/i);
if (energy) {
const t = TYPE_SYM[energy[1]?.toUpperCase()] || energy[2][0].toUpperCase() + energy[2].slice(1).toLowerCase();
take(state.poolById.get("e:" + t), left);
continue;
}
const k = nameKey(w.name);
const named = state.pool.filter(c => !c.virtual && nameKey(c.name) === k);
const exact = named.filter(c => w.code && c.info.code === w.code && String(c.info.no) === String(w.no).replace(/^0+/, ""));
for (const c of exact) left -= take(c, left);
const superOf = w.super || named[0]?.info.super;
const alts = named.filter(c => !exact.includes(c) && (superOf !== "Pokémon" || !w.code || c.info.code === w.code))
.sort((a, b) => (legalIn(b.info, "standard") === true) - (legalIn(a.info, "standard") === true));
for (const c of alts) left -= take(c, left);
if (left > 0) cards.push({ id: null, name: w.name, code: w.code, no: w.no, super: superOf || null, n: left });
}
return cards;
}
function showDialog(html) {
const dlg = $("#dlg");
dlg.innerHTML = `<div class="dlg one">${html}</div>`;
dlg.showModal();
dlg.querySelectorAll("[data-close]").forEach(b => b.onclick = () => dlg.close());
return dlg;
}
function openImport() {
const dlg = showDialog(`<div><h3>Import a deck list</h3>
<p>Paste a list from Pokémon TCG Live, Limitless or a deck site. Cards you own are filled in from your collection; the rest show as cards you need.</p>
<input id="impname" placeholder="Deck name" style="width:100%;margin-bottom:8px;background:var(--bg);border:1px solid var(--border);border-radius:10px;padding:8px 10px">
<textarea id="imptext" placeholder="Pokémon: 12&#10;4 Charmander MEW 4&#10;…"></textarea>
<p id="imperr" style="color:var(--loss)"></p>
<div class="actions"><button class="btn" id="impgo">Import</button><button class="btn ghost" data-close>Cancel</button></div></div>`);
$("#impgo").onclick = () => {
const cards = importDeck($("#imptext").value);
if (!cards) { $("#imperr").textContent = "Couldn't find any cards. Lines should look like “4 Charmander MEW 4”."; return; }
dlg.close();
newDeck($("#impname").value.trim() || "Imported deck", cards, "standard");
};
$("#imptext").focus();
}
function openExport(deck) {
const text = exportDeck(deck);
showDialog(`<div><h3>${esc(deck.name)}</h3>
<p id="exmsg">In Pokémon TCG Live: Decks → New deck → Import, then paste.</p>
<textarea id="extext" readonly>${esc(text)}</textarea>
<div class="actions" style="margin-top:10px"><button class="btn" id="excopy">Copy</button><button class="btn ghost" data-close>Close</button></div></div>`);
const copy = () => navigator.clipboard?.writeText(text).then(() => { $("#exmsg").textContent = "Copied! In Pokémon TCG Live: Decks → New deck → Import, then paste."; }).catch(() => $("#extext").select());
$("#excopy").onclick = copy;
copy();
}
function confirmDelete(deck) {
const dlg = showDialog(`<div><h3>Delete “${esc(deck.name)}”?</h3><p>This can't be undone. Your cards stay in your collection.</p>
<div class="actions"><button class="btn" style="background:var(--loss)" id="delgo">Delete deck</button><button class="btn ghost" data-close>Cancel</button></div></div>`);
$("#delgo").onclick = () => {
state.decks = state.decks.filter(d => d !== deck); saveDecks();
dlg.close(); openDeck(null);
};
}
/* ---------- one-tap sync ----------
Starts the sync workflow through the Gitea API (git.kburchtree.cloud) with
the card-sync account's token saved on this device (that account can only
write card-collection), follows the run, then reloads once the site is
serving the new data. */
const API = `https://git.kburchtree.cloud/api/v1/repos/${REPO}`;
const WORKFLOW_URL = `https://git.kburchtree.cloud/${REPO}/actions?workflow=sync.yml`;
const sync = { state: "idle", msg: "", runUrl: null };
const sleep = ms => new Promise(r => setTimeout(r, ms));
const gh = (path, token, opts = {}) => fetch(API + path, { ...opts, headers: {
Authorization: `token ${token}`, Accept: "application/json", "Content-Type": "application/json" } });
class TokenError extends Error {}
function drawSync() {
const el = $("#syncst");
if (!el) return;
const btn = `<button class="linkbtn" data-sync title="Pull the latest cards from Rare Candy">Sync now</button>`;
const run = sync.runUrl ? ` <a href="${esc(sync.runUrl)}" target="_blank" rel="noopener">details ↗</a>` : "";
el.innerHTML = sync.state === "busy" ? `<span class="syncst"><i class="spin"></i>${esc(sync.msg)}</span>`
: sync.state === "done" ? `<span class="syncst ok">${esc(sync.msg)}</span>`
: sync.state === "error" ? `<span class="syncst err">${esc(sync.msg)}${run}</span>${btn}`
: btn;
}
let syncClear;
function setSync(st, msg) {
sync.state = st; sync.msg = msg; drawSync();
clearTimeout(syncClear);
if (st === "done") syncClear = setTimeout(() => setSync("idle", ""), 10000);
}
async function runSync() {
const token = store.get("syncToken", null);
if (!token) return openSyncSetup();
if (sync.state === "busy") return;
const since = new Date(Date.now() - 10000); // a little slack for clock differences
const before = state.updatedAt;
sync.runUrl = null;
setSync("busy", "Starting sync…");
try {
const r = await gh("/actions/workflows/sync.yml/dispatches", token, { method: "POST", body: JSON.stringify({ ref: "main" }) });
if ([401, 403, 404].includes(r.status)) throw new TokenError(r.status === 401
? "Gitea didn't accept the saved token. It may have been revoked."
: "The saved token isn't allowed to run the sync. Use the card-sync account's token.");
if (!r.ok) throw new Error(`Gitea answered ${r.status}`);
// The dispatch call doesn't say which run it started; find the newest manual run since we asked
let run = null;
for (let i = 0; i < 40 && !run; i++) {
await sleep(3000);
const j = await gh("/actions/workflows/sync.yml/runs?event=workflow_dispatch&limit=5", token).then(r => r.json());
run = (j.workflow_runs || []).find(x => new Date(x.created_at) >= since);
}
if (!run) throw new Error("Gitea never started the sync");
sync.runUrl = run.html_url;
const t0 = Date.now();
while (run.status !== "completed") {
const secs = Math.round((Date.now() - t0) / 1000);
setSync("busy", ["queued", "waiting", "pending", "requested"].includes(run.status) ? "Waiting for the runner…" : `Syncing… ${secs}s`);
await sleep(4000);
run = await gh(`/actions/runs/${run.id}`, token).then(r => r.json());
}
if (run.conclusion !== "success") throw new Error("Sync failed");
// The sync only commits when something changed on Rare Candy
const commits = await fetch(`${API}/commits?path=data/rarecandy.json&since=${since.toISOString()}&limit=1&stat=false&verification=false&files=false`).then(r => r.json()).catch(() => null);
if (Array.isArray(commits) && !commits.length) { setSync("done", "Already up to date ✓"); return; }
setSync("busy", "Publishing…");
for (let i = 0; i < 60; i++) { // the site updates a few seconds after the sync pushes
const rc = await fetch(`data/rarecandy.json?t=${Date.now()}`, { cache: "no-store" }).then(r => r.ok ? r.json() : null).catch(() => null);
if (rc?.updatedAt && rc.updatedAt !== before) { await load(); setSync("done", "Synced ✓"); return; }
await sleep(5000);
}
setSync("done", "Synced. Refresh in a minute to see it.");
} catch (e) {
if (e instanceof TokenError) { setSync("idle", ""); openSyncSetup(e.message); return; }
setSync("error", e.message || "Sync failed");
}
}
function openSyncSetup(problem = "") {
const has = !!store.get("syncToken", null);
const dlg = showDialog(`<div><h3>One-tap sync</h3>
${problem ? `<p style="color:var(--loss)">${esc(problem)}</p>` : ""}
<p>To start the sync from here, this device needs the sync token. It belongs to the <b>card-sync</b> account, which can only work on this site's repo. You only set it up once per device.</p>
<ol class="steps">
<li>On your Mac, open Keychain Access and find <b>Card Collection Sync token (Gitea)</b>.</li>
<li>Copy the password and paste it here:</li>
</ol>
<input class="tok" id="tok" type="password" placeholder="Gitea token" autocomplete="off" spellcheck="false">
<p id="tokmsg" style="color:var(--loss);min-height:1em"></p>
<div class="actions">
<button class="btn" id="toksave">Save &amp; sync</button>
<a class="btn ghost" href="${WORKFLOW_URL}" target="_blank" rel="noopener">Run it on Gitea instead ↗</a>
<button class="btn ghost" data-close>Cancel</button>
</div>
${has ? `<p style="margin-top:14px"><button class="linkbtn" style="margin:0" id="tokforget">Remove the saved token from this device</button></p>` : ""}
</div>`);
$("#toksave").onclick = async () => {
const tok = $("#tok").value.trim();
if (!tok) { $("#tokmsg").textContent = "Paste the token first."; return; }
$("#tokmsg").textContent = "";
$("#toksave").disabled = true;
// Check it can see this repo's workflows before saving
const r = await gh("/actions/workflows/sync.yml", tok).catch(() => null);
$("#toksave").disabled = false;
if (!r?.ok) {
$("#tokmsg").textContent = r?.status === 401 ? "Gitea didn't accept that token. Check you copied all of it."
: r ? "That token can't see card-collection's sync. Use the card-sync token."
: "Couldn't reach git.kburchtree.cloud. Check your connection.";
return;
}
store.set("syncToken", tok);
dlg.close();
runSync();
};
$("#tokforget")?.addEventListener("click", () => { localStorage.removeItem("cc:syncToken"); dlg.close(); });
$("#tok").focus();
}
/* ---------- tooltip & dialog ---------- */
const tip = $("#tip");
function showTip(e, html) {
tip.innerHTML = html; tip.classList.add("on");
const w = tip.offsetWidth, hgt = tip.offsetHeight;
let lx = e.clientX + 14, ly = e.clientY - hgt - 10;
if (lx + w > innerWidth - 8) lx = e.clientX - w - 14;
if (ly < 8) ly = e.clientY + 16;
tip.style.left = lx + "px"; tip.style.top = ly + "px";
}
function hideTip() { tip.classList.remove("on"); }
document.addEventListener("pointerover", e => { const t = e.target.closest("[data-tip]"); if (t) showTip(e, t.dataset.tip); });
document.addEventListener("pointermove", e => { const t = e.target.closest("[data-tip]"); if (t) showTip(e, t.dataset.tip); });
document.addEventListener("pointerout", e => { if (e.target.closest("[data-tip]") && !e.relatedTarget?.closest?.("[data-tip]")) hideTip(); });
function gameInfo(i) {
if (!i?.super) return "";
const legal = { standard: legalIn(i, "standard"), expanded: legalIn(i, "expanded") };
const yn = v => v == null ? "?" : v ? "✓" : "✗";
return `<dt>Card type</dt><dd>${i.types?.length ? pips(i.types) + " " : ""}${esc([i.super, stageOf(i)].filter((v, k, a) => v && a.indexOf(v) === k).join(" · "))}${i.hp ? ` · ${esc(i.hp)} HP` : ""}</dd>
${i.from ? `<dt>Evolves from</dt><dd>${esc(i.from)}</dd>` : ""}
${i.abilities ? `<dt>Ability</dt><dd>${i.abilities.map(esc).join(", ")}</dd>` : ""}
${i.attacks ? `<dt>Attacks</dt><dd class="attacks">${i.attacks.map(a => `<div>${pips(a.c)} ${esc(a.n)}<span class="dmg">${esc(a.d)}</span></div>`).join("")}</dd>` : ""}
<dt>Legal</dt><dd>${i.mark ? `Mark ${esc(i.mark)} · ` : ""}Standard ${yn(legal.standard)} · Expanded ${yn(legal.expanded)}</dd>`;
}
function openCard(id) {
const c = state.all.find(x => x.id === id) || (state.setShown || []).find(x => x.id === id);
if (!c) return;
const dlg = $("#dlg");
dlg.innerHTML = `<div class="dlg">
<div class="big" ${c.imgFile || c.img ? `style="background:url('${esc(c.imgFile || c.img)}') center/cover"` : ""}>${cardImg(c, true, `alt="${esc(c.name)}"`) || `<div class="ph">${esc(c.name)}</div>`}</div>
<div>
<h3>${esc(c.name)}</h3>
<div style="color:var(--ink-3)">${esc(c.set)}${c.number ? " · #" + esc(c.number) : ""}</div>
<dl>
<dt>Price</dt><dd>${money(c.price)}</dd>
${[7, 30].map(d => { const ch = priceChange(c, d); return ch ? `<dt>${d}-day change</dt><dd class="${ch.delta > 0 ? "up" : ch.delta < 0 ? "down" : ""}">${signed(ch.delta)} ${pctStr(ch.pct)}</dd>` : ""; }).join("")}
<dt>Quantity</dt><dd>${c.qty || "Not owned"}</dd>
${c.qty ? `<dt>Owned value</dt><dd>${money(owned(c))}</dd>` : ""}
${gameInfo(state.info[c.id])}
<dt>Rarity</dt><dd>${esc(c.rarity || "—")}</dd>
${c.brand ? `<dt>Brand</dt><dd>${esc(c.brand)}</dd>` : ""}
${c.setRelease ? `<dt>Released</dt><dd>${esc(c.setRelease)}</dd>` : ""}
${c.lang ? `<dt>Language</dt><dd>${esc(c.lang)}</dd>` : ""}
</dl>
<div class="actions">
${c.url ? `<a class="btn" href="${esc(c.url)}" target="_blank" rel="noopener">View on Rare Candy ↗</a>` : ""}
<button class="btn ghost" id="dlgclose">Close</button>
</div>
</div></div>`;
dlg.showModal();
$("#dlgclose").onclick = () => dlg.close();
}
$("#dlg").addEventListener("click", e => { if (e.target.id === "dlg") e.target.close(); });
/* ---------- wiring ---------- */
function render() {
hideTip();
renderHeader();
document.querySelectorAll("nav.tabs button").forEach(b => b.setAttribute("aria-selected", b.dataset.tab === state.tab));
({ cards: renderCards, sets: renderSets, insights: renderInsights, decks: renderDecks })[state.tab]();
}
document.addEventListener("click", e => {
const tab = e.target.closest("nav.tabs button");
if (tab) { state.tab = tab.dataset.tab; state.setDetail = null; store.set("tab", state.tab); render(); scrollTo({ top: 0 }); return; }
if (e.target.closest("[data-back]")) { state.setDetail = null; render(); scrollTo({ top: 0 }); return; }
const show = e.target.closest("[data-setshow]");
if (show) { state.setShow = show.dataset.setshow; render(); return; }
const mv = e.target.closest("[data-movers]");
if (mv) { state.moverDays = +mv.dataset.movers; store.set("moverDays", state.moverDays); render(); return; }
const chip = e.target.closest(".chip[data-brand]");
if (chip) { state.brand = chip.dataset.brand; state.setDetail = null; store.set("brand", state.brand); render(); return; }
const set = e.target.closest(".set[data-set]");
if (set && set.dataset.setid) { state.setDetail = set.dataset.setid; state.setQ = ""; render(); scrollTo({ top: 0 }); return; }
if (set) { state.set = set.dataset.set; state.tab = "cards"; state.sort = "set"; state.q = ""; state.rarity = ""; render(); scrollTo({ top: 0 }); return; }
if (e.target.closest("[data-sync]")) { runSync(); return; }
if (handleDeckClick(e)) return;
const card = e.target.closest("[data-id]");
if (card) openCard(card.dataset.id);
});
function handleDeckClick(e) {
const t = sel => e.target.closest(sel);
const deck = currentDeck();
let el;
if (t("[data-newdeck]")) { newDeck(); return true; }
if (t("[data-importdeck]")) { openImport(); return true; }
if ((el = t("[data-deck]"))) { openDeck(el.dataset.deck); return true; }
if (t("[data-deckback]")) { openDeck(null); return true; }
if (!deck) return false;
if ((el = t("[data-dadd]"))) { const c = state.poolById.get(el.dataset.dadd); if (c) addCard(deck, c); return true; }
if ((el = t("[data-dinc]:not(:disabled)"))) { deck.cards[+el.dataset.dinc].n++; touch(deck); refreshDeck(); return true; }
if ((el = t("[data-ddec]"))) {
const i = +el.dataset.ddec;
if (--deck.cards[i].n <= 0) deck.cards.splice(i, 1);
touch(deck); refreshDeck(); return true;
}
if ((el = t("[data-dsuper]"))) {
state.dsuper = el.dataset.dsuper;
document.querySelectorAll("[data-dsuper]").forEach(b => b.setAttribute("aria-pressed", b === el));
drawPicker(deck); return true;
}
if ((el = t("[data-dpane]"))) { state.deckPane = el.dataset.dpane; $(".dbuild").dataset.pane = state.deckPane; refreshDeck(); return true; }
if (t("[data-deckexport]")) { openExport(deck); return true; }
if (t("[data-deckdup]")) {
newDeck(deck.name + " (copy)", deck.cards.map(e => ({ ...e })), deck.format); return true;
}
if (t("[data-deckdel]")) { confirmDelete(deck); return true; }
return false;
}
addEventListener("scroll", hideTip, { passive: true });
let rz;
addEventListener("resize", () => { clearTimeout(rz); rz = setTimeout(() => state.tab === "insights" && drawHistory(), 150); });
document.addEventListener("visibilitychange", () => { if (document.visibilityState === "visible") load(); });
load();
if ("serviceWorker" in navigator) navigator.serviceWorker.register("sw.js").catch(() => {});
</script>
</body>
</html>