// ==UserScript== // @name Steam Trading Card Helper // @name:zh-CN Steam 卡牌助手 // @namespace https://github.com/SpaceSyt/Steam-Trading-Card-Helper // @version 2.6.2 // @description Scan card prices and trends, estimate badge costs, streamline purchases, craft badges, and process surplus items // @description:zh-CN 扫描卡牌价格与走势、估算徽章成本、辅助批量购买、自动合成徽章,并检测和处理多余卡牌/背景/表情 // @author SpaceSyt // @homepageURL https://github.com/SpaceSyt/Steam-Trading-Card-Helper // @supportURL https://github.com/SpaceSyt/Steam-Trading-Card-Helper/issues // @downloadURL https://raw.githubusercontent.com/SpaceSyt/Steam-Trading-Card-Helper/master/steam-trading-card-helper.user.js // @updateURL https://raw.githubusercontent.com/SpaceSyt/Steam-Trading-Card-Helper/master/steam-trading-card-helper.user.js // @match https://steamcommunity.com/id/*/badges* // @match https://steamcommunity.com/profiles/*/badges* // @match https://steamcommunity.com/id/*/inventory* // @match https://steamcommunity.com/profiles/*/inventory* // @match https://steamcommunity.com/market/multibuy* // @grant GM_addStyle // @grant GM_setValue // @grant GM_getValue // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect steamcommunity.com // @license MIT // ==/UserScript== "use strict";(()=>{var Pa='.stch-btn-entry{display:inline-block;padding:6px 12px;margin-left:10px;background:#4389b3d9;color:#fff;border-radius:3px;cursor:pointer;font-size:13px}.stch-btn-entry:hover{background:#579dc7}.inventory_rightnav .stch-btn-entry.stch-inventory-entry{margin:0 12px 0 0;padding:0 12px;height:30px;line-height:30px;vertical-align:top}#stch-sidebar{position:fixed;left:0;top:122px;width:304px;max-height:calc(100vh - 170px);min-height:360px;transform:translate(-272px);transition:transform .16s ease;z-index:10002;color:#c7d5e0;font-family:Motiva Sans,Arial,sans-serif;font-size:13px;filter:drop-shadow(0 8px 18px rgba(0,0,0,.45))}#stch-sidebar:hover,#stch-sidebar.pinned{transform:translate(0)}.stch-sidebar-panel{width:272px;min-height:360px;max-height:calc(100vh - 170px);overflow:hidden;background:#172435;border:1px solid #31445b;border-left:0;border-radius:0 4px 4px 0;display:flex;flex-direction:column}.stch-sidebar-handle{position:absolute;top:0;right:0;width:32px;height:100%;background:linear-gradient(180deg,#25445d,#1a2d40);border:1px solid #3f617b;border-left:0;border-radius:0 5px 5px 0;color:#66c0f4;cursor:pointer;writing-mode:vertical-rl;text-orientation:mixed;display:flex;align-items:center;justify-content:center;letter-spacing:0;user-select:none;font-weight:700}.stch-sidebar-head{display:flex;align-items:center;gap:10px;padding:12px;background:#202f43;border-bottom:1px solid #31445b}.stch-sidebar-avatar{width:46px;height:46px;object-fit:cover;border:1px solid #66c0f4;background:#0b141f;flex-shrink:0}.stch-sidebar-title{min-width:0;flex:1;display:flex;align-items:center;justify-content:center}.stch-sidebar-name{color:#fff;font-size:15px;font-weight:700;line-height:1.25;text-align:center;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-sidebar-pin{margin-left:auto;background:#0e1621;border:1px solid #45556b;color:#c7d5e0;border-radius:2px;padding:4px 7px;cursor:pointer;font-size:12px;flex-shrink:0}.stch-sidebar-pin:hover,#stch-sidebar.pinned .stch-sidebar-pin{color:#fff;border-color:#66c0f4}.stch-sidebar-body{padding:10px 12px 12px;overflow-y:auto;min-height:0}.stch-sidebar-row{display:flex;justify-content:space-between;gap:10px;padding:7px 0;border-bottom:1px solid rgba(69,85,107,.55)}.stch-sidebar-row:last-child{border-bottom:0}.stch-sidebar-key{color:#8f98a0;white-space:nowrap}.stch-sidebar-value{color:#fff;text-align:right;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}#stch-sidebar-gem-price{font-size:12px}.stch-sidebar-price-rise{color:#d85c5c}.stch-sidebar-price-fall{color:#68b86b}.stch-sidebar-price-flat{color:#8f98a0}.stch-sidebar-progress{height:6px;background:#0e1621;border-radius:6px;overflow:hidden;margin-top:4px;border:1px solid #31445b}.stch-sidebar-progress-bar{height:100%;width:0;background:linear-gradient(90deg,#75b022,#66c0f4)}.stch-sidebar-status{color:#8f98a0;font-size:12px;margin-top:9px;line-height:1.4}.stch-sidebar-actions{display:flex;justify-content:flex-end;margin-top:10px}.stch-sidebar-refresh{background:linear-gradient(to bottom,#67c1f5 5%,#417a9b 95%);color:#fff;border:0;border-radius:2px;cursor:pointer;padding:5px 10px;font-size:12px}.stch-sidebar-refresh:disabled{opacity:.55;cursor:not-allowed}#stch-backdrop{position:fixed;inset:0;background:#0009;z-index:10000;display:none}#stch-modal{position:fixed;left:50%;top:20px;transform:translate(-50%);width:1060px;max-width:95vw;height:92vh;background:#1b2838;color:#c6d4df;z-index:10001;border-radius:4px;overflow:hidden;display:flex;flex-direction:column;font-family:Motiva Sans,Arial,sans-serif;font-size:14px;box-shadow:0 0 30px #0009}#stch-modal .stch-header{padding:10px 16px;border-bottom:1px solid #45556b;display:flex;align-items:center;background:#171a21}#stch-modal .stch-header h2{margin:0;font-size:20px;flex:1;color:#fff}#stch-modal .stch-close{cursor:pointer;font-size:22px;color:#8f98a0}#stch-modal .stch-close:hover{color:#fff}#stch-modal .stch-body{flex:1;overflow-y:hidden;padding:12px 16px;display:flex;flex-direction:column;min-height:0}#stch-modal .stch-footer{padding:10px 16px;background:#171a21;border-top:1px solid #45556b;display:flex;gap:10px;align-items:center;flex-wrap:wrap;font-size:13px}.stch-settings-page-actions{margin-top:20px;padding-top:12px;border-top:1px solid #45556b;display:flex;flex-wrap:wrap;align-items:center;justify-content:flex-end;gap:6px}.stch-settings-page-actions .stch-footer-status{margin-right:auto}.stch-settings-page-actions .stch-advanced-toggle{margin-right:8px;white-space:nowrap}.stch-settings-page-actions .stch-btn{padding:6px 11px;font-size:13px}.stch-footer-status{color:#8db7d7;min-height:16px}#stch-tab-settings{overflow:hidden}.stch-settings-layout{display:flex;flex:1;min-height:0;gap:16px}.stch-settings-nav{flex:0 0 104px;display:flex;flex-direction:column;gap:4px;padding-right:12px;border-right:1px solid #45556b}.stch-settings-nav-item{appearance:none;width:100%;padding:8px 10px;border:1px solid transparent;border-radius:3px;background:transparent;color:#8f98a0;font:inherit;text-align:left;cursor:pointer}.stch-settings-nav-item:hover{color:#fff;background:#67c1f514}.stch-settings-nav-item.active{color:#fff;border-color:#45556b;background:#202f43}.stch-settings-main{flex:1;min-width:0;overflow-y:auto;padding-right:4px}.stch-settings-panel{display:none}.stch-settings-panel.active{display:block}.stch-settings-section-title{color:#fff;font-weight:700;font-size:16px;margin-bottom:4px}.stch-settings-section-rule{border-bottom:1px solid #45556b;margin-bottom:16px}.stch-tab-color-settings{display:flex;flex-direction:column;gap:12px}.stch-tab-color-field{min-width:0;display:flex;align-items:center;gap:12px;color:#c6d4df;font-size:13px}.stch-tab-color-field span{width:68px}.stch-tab-color-input{width:100%;max-width:112px;text-transform:uppercase}.stch-tab-color-input.invalid{border-color:#d85c5c;color:#e06b65}.stch-tab-color-help{margin-top:14px;color:#697887;font-size:12px}#stch-tab-settings:not(.stch-show-advanced) .stch-advanced-setting{display:none!important}.stch-auto-strategy-settings{display:grid;gap:7px}.stch-auto-strategy-row{display:grid;grid-template-columns:48px auto auto auto;align-items:center;justify-content:start;gap:10px}.stch-auto-strategy-row label{display:flex;align-items:center;gap:6px;white-space:nowrap}.stch-auto-strategy-name{color:#fff;font-weight:700}.stch-auto-wall-anchor{width:104px}.stch-auto-offset{width:64px}.stch-auto-strategy-hint{color:#697887;font-size:12px;line-height:1.45;margin-top:2px}.stch-input{background:#0e1621;color:#fff;border:1px solid #45556b;padding:5px 8px;border-radius:2px;width:80px;font-size:14px}.stch-input:focus{border-color:#66c0f4;outline:none}.stch-label{font-size:14px;color:#8f98a0}.stch-btn{padding:8px 16px;background:linear-gradient(to bottom,#75b022 5%,#588a1b 95%);color:#fff;border-radius:2px;cursor:pointer;font-size:15px;font-family:inherit;line-height:normal;border:0;user-select:none}.stch-btn:hover{background:linear-gradient(to bottom,#8ed629 5%,#6aa621 95%)}.stch-btn.disabled{background:#2a3f5a;color:#667;cursor:not-allowed;opacity:.6}.stch-btn.alt{background:linear-gradient(to bottom,#67c1f5 5%,#417a9b 95%)}.stch-btn.alt:hover{background:linear-gradient(to bottom,#8ed8ff 5%,#5297b7 95%)}.stch-btn.stch-btn-danger{background:linear-gradient(to bottom,#c04040 5%,#8b2020 95%)}.stch-btn.stch-btn-danger:hover{background:linear-gradient(to bottom,#e05050 5%,#a03030 95%)}.stch-game-list{max-height:30vh;overflow-y:auto;border:1px solid #2a3f5a;border-radius:3px;background:#0003}#stch-tab-scan.stch-foil-mode{background:linear-gradient(180deg,#461f5275,#1b2838fa 260px);box-shadow:inset 0 0 0 1px #c15bc43d;border-radius:3px}#stch-tab-scan.stch-foil-mode .stch-game-list{border-color:#c15bc46b;background:#140b1b57}#stch-tab-scan.stch-foil-mode #stch-log{background:#120d1b;border:1px solid rgba(193,91,196,.22)}#stch-tab-scan.stch-foil-mode .stch-progress-bar{background:linear-gradient(to right,#8f55c2,#cf73c9)}#stch-tab-scan.stch-foil-mode .stch-cost,#stch-tab-scan.stch-foil-mode .stch-appid{color:#d78be8}.stch-game-row{padding:6px 14px;border-bottom:1px solid rgba(69,85,107,.4);display:flex;align-items:center;gap:12px;font-size:14px;line-height:1.4}.stch-row-header{color:#8f98a0;font-size:11px;font-weight:700;border-bottom:2px solid #45556b;padding-bottom:6px;margin-bottom:2px}#stch-modal .stch-row-header>*{font-size:11px;font-family:inherit}.stch-game-row:hover{background:#67c1f514}.stch-game-row .stch-appid{width:56px;flex-shrink:0;color:#66c0f4;font-family:monospace;font-size:12px;text-align:center}.stch-game-row .stch-name{flex:1;color:#e2e2e2;font-size:13px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-game-row .stch-level{width:42px;flex-shrink:0;color:#a1b053;font-size:12px;text-align:center}.stch-game-row .stch-cards{width:36px;flex-shrink:0;color:#c6d4df;font-size:12px;text-align:center}.stch-game-row .stch-cost{width:68px;flex-shrink:0;color:#75b022;font-weight:700;font-size:13px;text-align:center}.stch-game-row .stch-full{width:68px;flex-shrink:0;color:#ffc902;font-size:12px;text-align:center}.stch-game-row .stch-lv5{width:84px;flex-shrink:0;color:#e74c3c;font-size:12px;text-align:center}.stch-game-row .stch-drops{width:36px;flex-shrink:0;color:#8db7d7;font-size:12px;text-align:center}.stch-game-row .stch-order-cache-age{width:38px;flex-shrink:0;color:#8f98a0;font-size:12px;text-align:center}.stch-game-row .stch-buy{width:60px;flex-shrink:0;text-align:center}.stch-game-row .stch-check{width:24px;flex-shrink:0;text-align:center;position:relative;align-self:stretch;display:flex;align-items:center;justify-content:center;overflow:visible}.stch-game-list:not(.stch-show-drops) .stch-drops{display:none}.stch-game-list:not(.stch-show-completion) .stch-cost{display:none}.stch-game-list:not(.stch-show-sell-set) .stch-full{display:none}.stch-result-cb{margin:0;cursor:pointer;accent-color:#75b022}.stch-check-hit{position:absolute;left:50%;top:50%;width:36px;height:32px;transform:translate(-50%,-50%);display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:1}.stch-check-hit .stch-result-cb{position:relative;z-index:2}.stch-craft-list{flex:1;min-height:0;max-height:none}.stch-order-page-list{flex:1;min-height:0;max-height:none;width:100%;box-sizing:border-box}.stch-craft-row .stch-craft-available{width:64px;flex-shrink:0;text-align:center;color:#ffc902;font-size:12px}.stch-craft-row .stch-craft-count{width:74px;flex-shrink:0;text-align:center}.stch-craft-row .stch-craft-count input{width:48px;box-sizing:border-box;text-align:center;padding:4px}.stch-craft-row .stch-craft-target{width:54px;flex-shrink:0;text-align:center;color:#a1b053;font-size:12px}.stch-craft-row .stch-craft-status{width:72px;flex-shrink:0;text-align:center;color:#8f98a0;font-size:12px}.stch-craft-row .stch-craft-status.ok{color:#75b022}.stch-craft-row .stch-craft-status.warn{color:#ffc902}.stch-craft-row .stch-craft-status.err{color:#c04040}.stch-craft-actions{display:flex;align-items:center;gap:10px;margin-left:auto}.stch-surplus-list{flex:1;min-height:0;max-height:none}.stch-surplus-main-toolbar{gap:12px;flex-wrap:nowrap}.stch-surplus-action-row{gap:12px;flex-wrap:wrap;align-items:center}.stch-surplus-action-spacer{flex:1 1 auto;min-width:16px}.stch-surplus-action-buttons{display:flex;align-items:center;gap:8px}.stch-surplus-action-buttons .stch-btn{padding:7px 12px;font-size:13px;min-width:56px;text-align:center;box-sizing:border-box}.stch-collection-actions{align-items:center}.stch-collection-list{flex:1;min-height:0;overflow-y:auto}.stch-collection-tile .stch-inv-badge-left{background:#66c0f4e6;color:#0e1621}.stch-surplus-mode-panel{display:none;flex-direction:column;flex:1;min-height:0}.stch-surplus-mode-panel.active{display:flex}.stch-inventory-grid{display:grid;grid-template-columns:repeat(auto-fill,88px);grid-auto-rows:88px;gap:4px;padding:4px;align-content:start;justify-content:start;box-sizing:border-box}.stch-inventory-empty{grid-column:1 / -1;min-height:120px;display:flex;align-items:center;justify-content:center;color:#8f98a0;font-size:13px}.stch-inv-tile{position:relative;aspect-ratio:1 / 1;min-width:0;background:#20252d;border:1px solid #3a3a3a;cursor:pointer;overflow:hidden;display:flex;align-items:center;justify-content:center;box-shadow:inset 0 0 12px #00000052;user-select:none}.stch-inv-tile:hover{border-color:#66c0f4;box-shadow:inset 0 0 14px #66c0f438,0 0 0 1px #66c0f438}.stch-inv-tile.selected{border-color:#9ee7ff!important;box-shadow:inset 0 0 22px #66c0f4b8,0 0 0 2px #66c0f4,0 0 12px #66c0f4e6;background:#23384a}.stch-inv-tile.selected:before{content:"✓";position:absolute;inset:0;z-index:6;box-sizing:border-box;padding:3px 6px;border:4px solid #66c0f4;background:#2376aa2e;color:#fff;font-size:22px;font-weight:700;line-height:1;text-align:right;text-shadow:0 1px 3px #000;pointer-events:none}.stch-inv-tile.stch-volume-zero:after{content:"";position:absolute;inset:0;z-index:1;pointer-events:none;background:#d9a61847;box-shadow:inset 0 0 0 2px #ffc902ad}.stch-inv-tile img{width:100%;height:100%;object-fit:contain;display:block;pointer-events:none}.stch-inv-placeholder{padding:8px;color:#c7d5e0;font-size:12px;line-height:1.3;text-align:center;word-break:break-word}.stch-inv-badge{position:absolute;right:0;top:0;max-width:calc(100% - 8px);padding:2px 5px;background:#347aa6eb;color:#fff;font-size:12px;line-height:1.25;font-weight:700;text-shadow:0 1px 1px #000;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;z-index:2}.stch-inv-badge-left{left:0;right:auto;background:#141b23db;color:#8db7d7}.stch-inv-badge-left.ok{color:#75b022}.stch-inv-badge-left.warn{color:#ffc902}.stch-inv-badge-left.info{color:#66c0f4}.stch-inv-gems{position:absolute;left:0;right:0;bottom:20px;color:#c7d5e0;background:#0000006b;font-size:11px;line-height:17px;text-align:center;text-shadow:0 1px 1px #000;z-index:2}.stch-inv-name{position:absolute;left:0;right:0;bottom:0;height:20px;padding:2px 4px;box-sizing:border-box;color:#dfe3e6;background:linear-gradient(180deg,#0a0e1433,#0a0e14e0);font-size:11px;line-height:16px;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-shadow:0 1px 1px #000;z-index:2}.stch-grind-list{flex:1;min-height:0;max-height:none}.stch-scan-actions{display:flex;align-items:center;gap:10px;margin-bottom:8px}.stch-bulk-actions{display:flex;align-items:center;gap:10px;margin-left:auto}.stch-selected-count{color:#8f98a0;margin-left:auto;width:24px;margin-right:14px;flex-shrink:0;display:flex;justify-content:center;white-space:nowrap}.stch-sortable{cursor:pointer;user-select:none}.stch-sortable:hover{color:#fff}.stch-sort-arrow{font-size:10px}.stch-toolbar{display:flex;gap:14px;align-items:center;margin-bottom:8px;flex-wrap:wrap;font-size:14px;color:#8f98a0}.stch-toolbar label{display:flex;align-items:center;gap:4px;cursor:pointer}.stch-settings-hint{color:#697887;font-size:12px}.stch-checkbox-dragging,.stch-checkbox-dragging *{user-select:none!important;cursor:default!important}.stch-settings-hint:before{content:"* "}.stch-primary-label{color:#fff!important;font-weight:700}.stch-auto-pricing-toggle{color:#d6b45a;font-weight:700}.stch-auto-pricing-toggle input{accent-color:#d6b45a}.stch-primary-label.stch-auto-pricing-active,.stch-auto-pricing-active .stch-input,.stch-foil-mode-label{color:#d9a4e8;font-weight:700}.stch-foil-mode-label input{accent-color:#b75ac7}.stch-foil-mode-label.active{color:#f0c4f7;text-shadow:0 0 10px rgba(207,115,201,.35)}.stch-control-disabled{color:#687682!important;font-weight:400!important}.stch-control-disabled .stch-input,.stch-input:disabled{color:#687682;background:#111a25;border-color:#2f3f51;cursor:not-allowed;opacity:.75}.stch-foil-mode-label.disabled{color:#7d6685;text-shadow:none;cursor:not-allowed}.stch-status-text{color:#8db7d7;font-size:13px;padding:6px 0;min-height:20px}.stch-tabs{display:flex;gap:2px;margin-bottom:10px;border-bottom:1px solid #45556b;overflow-x:auto}.stch-tab{padding:6px 16px;background:#0000004d;color:#8f98a0;cursor:grab;border-radius:3px 3px 0 0;font-size:14px;user-select:none;flex:0 0 auto}.stch-tab:hover{color:#fff;background:#67c1f51a}.stch-tab.active{color:#fff;background:#1b2838;border:1px solid #45556b;border-bottom-color:#1b2838}.stch-tab.stch-tab-custom-color,.stch-tab.stch-tab-custom-color:hover,.stch-tab.stch-tab-custom-color.active{color:var(--stch-tab-label-color)}.stch-tab.stch-tab-dragging{opacity:.55;cursor:grabbing}.stch-tabs.stch-tabs-dragging{cursor:grabbing}.stch-tab-right{margin-left:auto}.stch-tab-content{display:none;position:relative}.stch-tab-content.active{display:flex;flex-direction:column;flex:1;min-height:0}.stch-active-orders-toolbar{flex-wrap:nowrap}#stch-active-orders-game{width:260px}.stch-active-orders-summary-row{justify-content:space-between;min-width:0}.stch-active-orders-summary-row .stch-summary-text{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-active-orders-summary-row .stch-selected-count{flex:0 0 auto;white-space:nowrap}#stch-active-orders-status.ok{color:#75b022}#stch-active-orders-status.warn{color:#ffc902}#stch-active-orders-status.err{color:#d85c5c}.stch-active-orders-list{flex:1;min-height:0;overflow-y:auto;border:1px solid #2a3f5a;border-radius:3px;background:#0003}.stch-active-orders-empty{padding:24px;color:#8f98a0;text-align:center}.stch-active-orders-log{flex:0 0 auto;max-height:96px;overflow-y:auto;margin-top:8px;padding:7px 9px;border-radius:3px;background:#0e1621;color:#8f98a0;font:11px/1.45 Courier New,monospace}.stch-active-orders-log .ok{color:#75b022}.stch-active-orders-log .err{color:#d85c5c}.stch-active-order-header,.stch-active-order-row{display:grid;grid-template-columns:minmax(230px,1fr) 80px 82px 48px 82px minmax(118px,145px) 36px;gap:8px;align-items:center;box-sizing:border-box}.stch-active-order-header{position:sticky;top:0;z-index:3;min-height:29px;padding:5px 8px;background:#172435;color:#8f98a0;border-bottom:1px solid #45556b;font-size:11px;font-weight:700}.stch-active-order-header span:not(:first-child){text-align:center}.stch-active-order-select-all-wrap{display:flex;align-items:center;justify-content:center;cursor:pointer}.stch-active-order-select-all{cursor:pointer;accent-color:#75b022}.stch-active-order-game-separator{position:sticky;top:29px;z-index:2;padding:4px 10px;background:#202f43;color:#8db7d7;border-bottom:1px solid #31445b;font-size:11px}.stch-active-order-row{min-height:52px;padding:6px 8px;border-bottom:1px solid rgba(69,85,107,.4);transition:background .1s ease,box-shadow .1s ease}.stch-active-order-row:hover{background:#67c1f514}.stch-active-order-row.selected{background:#75b02238;box-shadow:inset 4px 0 #8ed629,inset 0 0 0 1px #8ed62973}.stch-active-order-select{align-self:stretch;display:flex;align-items:center;justify-content:center;cursor:pointer}.stch-active-order-cb{cursor:pointer;accent-color:#75b022}.stch-active-order-item{min-width:0;display:flex;align-items:center;gap:9px;color:#c7d5e0;text-decoration:none}.stch-active-order-item:hover .stch-active-order-name{color:#fff}.stch-active-order-image{width:40px;height:40px;object-fit:contain;flex:0 0 40px;background:#0e1621}.stch-active-order-names{min-width:0;display:flex;flex-direction:column;gap:3px}.stch-active-order-name,.stch-active-order-game{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-active-order-name{color:#66c0f4;font-size:13px}.stch-active-order-game{color:#8f98a0;font-size:11px}.stch-active-order-metric{min-width:0;text-align:center}.stch-active-order-value{color:#fff;font-size:13px;white-space:nowrap}.stch-active-order-smart{font-size:11px;line-height:1.35;text-align:center}.stch-active-order-smart.matched{color:#75b022}.stch-active-order-smart.unavailable{color:#697887}.stch-active-order-smart.high{color:#d85c5c}.stch-active-order-smart.low{color:#ffc902}.stch-active-order-lowest{text-align:center}.stch-active-order-lowest.loading{color:#8db7d7}.stch-active-order-lowest.missing,.stch-active-order-lowest.failed{color:#8f98a0}@media(max-width:760px){.stch-active-orders-toolbar{flex-wrap:wrap}#stch-active-orders-game{width:220px;max-width:70vw}.stch-active-order-header,.stch-active-order-row{grid-template-columns:minmax(180px,1fr) 72px 72px 44px 72px 32px}.stch-active-order-header span:nth-child(6),.stch-active-order-smart{display:none}}@media(max-width:580px){.stch-active-order-header,.stch-active-order-row{grid-template-columns:minmax(145px,1fr) 60px 60px 38px 60px 28px;gap:6px}}.stch-history-toolbar{flex-wrap:wrap}.stch-history-source{width:132px}.stch-history-card,.stch-history-manual{width:330px;max-width:32vw}.stch-history-hidden{display:none!important}.stch-history-toolbar-spacer{flex:1 1 auto}.stch-history-count{color:#8f98a0;font-size:12px;white-space:nowrap}.stch-history-range{gap:6px;flex-wrap:wrap}.stch-history-range .stch-btn{padding:5px 10px;font-size:12px}.stch-history-range .stch-btn.active{color:#fff;background:linear-gradient(to bottom,#75b022 5%,#588a1b 95%);box-shadow:inset 0 0 0 1px #beee7a66}#stch-history-status.err{color:#e06b65}#stch-history-status.warn{color:#d9a51d}.stch-history-list{flex:1 1 auto;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:6px;padding:1px 3px 4px 0}.stch-history-list-empty{min-height:180px;flex:1 1 auto;display:flex;align-items:center;justify-content:center;padding:30px;color:#8f98a0;font-size:13px;line-height:1.6;text-align:center;border:1px dashed #2a3f5a;background:#00000029}.stch-history-list-empty.error{color:#e06b65}.stch-history-row{position:relative;display:grid;grid-template-columns:minmax(230px,1.1fr) minmax(190px,1fr) minmax(390px,1.45fr);align-items:center;gap:14px;min-height:84px;padding:8px 38px 8px 8px;border:1px solid #2a3f5a;border-radius:3px;background:linear-gradient(90deg,#162230f0,#0d1620eb);transition:border-color .12s ease,background .12s ease}.stch-history-row:hover,.stch-history-row:focus-within{border-color:#4c708c;background:linear-gradient(90deg,#1d2f41fa,#111d29f5)}.stch-history-item-link{min-width:0;display:flex;align-items:center;gap:10px;color:inherit;text-decoration:none}.stch-history-item-link:hover b{color:#66c0f4}.stch-history-thumb{position:relative;width:64px;height:64px;flex:0 0 64px;display:flex;align-items:center;justify-content:center;overflow:hidden;border:1px solid #30465e;border-radius:3px;background:radial-gradient(circle at 50% 35%,#30445a,#15202d 72%);box-shadow:inset 0 0 8px #00000073}.stch-history-thumb img{position:relative;z-index:1;width:100%;height:100%;object-fit:contain}.stch-history-thumb-placeholder{position:absolute;color:#60758a;font-size:26px}.stch-history-item-names{min-width:0;display:flex;flex-direction:column;gap:5px}.stch-history-item-names b,.stch-history-item-names small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-history-item-names b{color:#d6d7d8;font-size:14px;transition:color .12s ease}.stch-history-item-names small{color:#6f8294;font-size:11px}.stch-history-spark-wrap{position:relative;min-width:0;height:64px;border-left:1px solid rgba(102,192,244,.12);border-right:1px solid rgba(102,192,244,.12)}.stch-history-spark{display:block;width:100%;height:100%}.stch-history-spark-empty{position:absolute;inset:0;display:flex;align-items:center;justify-content:center;color:#5f7183;font-size:11px;pointer-events:none}.stch-history-row-stats{min-width:0;display:grid;grid-template-columns:minmax(55px,.7fr) minmax(86px,1fr) minmax(62px,.75fr) minmax(126px,1.45fr);gap:8px}.stch-history-row-metric{min-width:0;display:flex;flex-direction:column;gap:4px}.stch-history-row-metric span{color:#7f91a3;font-size:11px;white-space:nowrap}.stch-history-row-metric b{color:#e5e5e5;font-size:13px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-history-row-metric:last-child b{font-size:12px}.stch-history-row-metric.up b{color:#75b022}.stch-history-row-metric.down b{color:#e06b65}.stch-history-row-metric.flat b{color:#8f98a0}.stch-history-remove{position:absolute;top:5px;right:7px;padding:2px 3px;border:0;background:transparent;color:#d85b55;font:inherit;font-size:11px;cursor:pointer;opacity:0;visibility:hidden;pointer-events:none;transition:opacity .1s ease}.stch-history-row:hover .stch-history-remove,.stch-history-row:focus-within .stch-history-remove,.stch-history-remove:focus{opacity:.8;visibility:visible;pointer-events:auto}.stch-history-remove:hover{opacity:1!important;text-decoration:underline}@media(max-width:1000px){.stch-history-row{grid-template-columns:minmax(220px,1.1fr) minmax(150px,.8fr) minmax(230px,1fr)}.stch-history-row-stats{grid-template-columns:repeat(2,minmax(80px,1fr))}}@media(max-width:760px){.stch-history-card,.stch-history-manual{width:58vw;max-width:58vw}.stch-history-row{grid-template-columns:minmax(0,1fr);gap:8px}.stch-history-spark-wrap{height:54px}.stch-history-row-stats{grid-template-columns:repeat(4,minmax(62px,1fr))}}@media(max-width:420px){.stch-history-row-stats{grid-template-columns:repeat(2,minmax(80px,1fr))}}@media(hover:none){.stch-history-remove{opacity:.65;visibility:visible;pointer-events:auto}}.stch-onboarding{position:absolute;inset:0;z-index:10;display:flex;flex-direction:column;overflow-y:auto;background:#1b2838;padding:24px 28px}.stch-onboarding h3{margin:0 0 8px;color:#fff;font-size:22px}.stch-onboarding-intro{margin:0 0 20px;color:#8db7d7;line-height:1.7}.stch-onboarding-step{padding:12px 0;border-top:1px solid #2a3f5a;line-height:1.65}.stch-onboarding-step b{display:block;margin-bottom:2px;color:#fff;font-size:15px}.stch-onboarding-note{margin-top:8px;padding:10px 12px;border-left:3px solid #ffc902;background:#0003;color:#c6d4df;line-height:1.6}.stch-onboarding-actions{display:flex;justify-content:flex-end;margin-top:auto;padding-top:20px}.stch-bl-form{display:flex;gap:10px;align-items:center;margin-bottom:10px;flex-wrap:wrap}.stch-bl-list{flex:1;min-height:0;overflow-y:auto;border:1px solid #2a3f5a;border-radius:3px;background:#0003}.stch-bl-row{padding:6px 14px;border-bottom:1px solid rgba(69,85,107,.4);display:flex;align-items:center;gap:12px;font-size:14px}.stch-bl-row:hover{background:#67c1f514}.stch-bl-row .stch-bl-id{width:70px;color:#66c0f4;font-family:monospace}.stch-bl-row .stch-bl-name{flex:1;color:#e2e2e2}.stch-bl-row .stch-bl-source{width:50px;color:#8f98a0;font-size:12px;text-align:center}.stch-bl-row .stch-bl-price{width:94px;color:#8f98a0;font-size:12px;text-align:right}.stch-bl-row .stch-bl-price.exact{color:#75b022}.stch-bl-row .stch-bl-price.estimated{color:#ffc902}.stch-bl-row .stch-bl-fixed-col{width:40px;color:#75b022;font-size:12px;text-align:center}.stch-bl-row .stch-bl-days{width:45px;color:#8f98a0;font-size:12px;text-align:center}.stch-bl-row .stch-bl-cb-hd{width:24px;flex-shrink:0;text-align:center}.stch-bl-cb{cursor:pointer;accent-color:#75b022}.stch-bl-count{color:#8f98a0;font-size:12px;margin-top:6px}.stch-bl-sep{color:#45556b;font-size:12px;margin:4px 0;padding-left:8px}.stch-bl-fixed{color:#75b022}.stch-bl-result{color:#75b022;font-size:14px}.stch-log-resizer{flex:0 0 9px;height:9px;margin:6px 0 4px;cursor:row-resize;position:relative;border-radius:3px}.stch-log-resizer:before{content:"";position:absolute;left:0;right:0;top:4px;height:1px;background:#45556b}.stch-log-resizer:after{content:"";position:absolute;left:50%;top:2px;width:42px;height:5px;transform:translate(-50%);border-top:1px solid #66c0f4;border-bottom:1px solid #66c0f4;opacity:.55}.stch-log-resizer:hover,.stch-log-resizer.dragging{background:#67c1f514}body.stch-log-resizing{cursor:row-resize;user-select:none}#stch-log,#stch-craft-log,#stch-surplus-log,#stch-grind-log{margin-top:0;flex:1;min-height:0;overflow-y:auto;background:#0e1621;border-radius:3px;padding:10px;font-family:Courier New,monospace;font-size:13px;line-height:1.5;color:#b0c3d9;white-space:pre-wrap;word-break:break-all}#stch-craft-log,#stch-surplus-log,#stch-grind-log{flex:0 0 19vh}#stch-log .ok,#stch-craft-log .ok,#stch-surplus-log .ok,#stch-grind-log .ok{color:#75b022}#stch-log .warn,#stch-craft-log .warn,#stch-surplus-log .warn,#stch-grind-log .warn{color:#ffc902}#stch-log .warn-ip,#stch-craft-log .warn-ip,#stch-surplus-log .warn-ip,#stch-grind-log .warn-ip{color:#fff}#stch-log .err,#stch-craft-log .err,#stch-surplus-log .err,#stch-grind-log .err{color:#c04040}#stch-log .info,#stch-craft-log .info,#stch-surplus-log .info,#stch-grind-log .info{color:#67c1f5}.stch-progress{height:20px;background:#0e1621;border-radius:2px;overflow:hidden;margin:8px 0;position:relative}.stch-progress-bar{height:100%;background:linear-gradient(to right,#75b022,#8ed629);transition:width .2s}.stch-progress-text{position:absolute;inset:0;text-align:center;font-size:13px;line-height:20px;color:#fff}.stch-summary{font-size:14px;color:#8f98a0;margin:8px 0;display:flex;align-items:center;gap:12px}.stch-summary-text{min-width:0}.stch-summary b{color:#fff}#stch-order-dialog-backdrop{position:fixed;inset:0;z-index:10020;background:#000000a6;display:flex;align-items:center;justify-content:center}.stch-order-dialog{width:620px;max-width:92vw;max-height:82vh;display:flex;flex-direction:column;background:#1b2838;border:1px solid #45556b;border-radius:4px;box-shadow:0 12px 40px #000000b3;color:#c6d4df}.stch-order-dialog h3{margin:0;padding:14px 16px;color:#fff;font-size:18px;border-bottom:1px solid #45556b}.stch-order-summary{padding:12px 16px;line-height:1.7}.stch-order-summary b{color:#fff}.stch-order-list{margin:0 16px;max-height:42vh;overflow-y:auto;scrollbar-gutter:stable;border:1px solid #2a3f5a;background:#0e1621}.stch-order-item{display:grid;grid-template-columns:minmax(0,1fr) 58px 260px 76px;align-items:center;gap:10px;padding:7px 12px 7px 10px;border-bottom:1px solid rgba(69,85,107,.4);font-size:12px}.stch-order-item span:first-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stch-order-item span:nth-child(2){text-align:center;font-variant-numeric:tabular-nums;white-space:nowrap}.stch-order-price-basis{color:#8f98a0;text-align:right;white-space:nowrap}.stch-order-item span:last-child{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}.stch-processing-dialog-item.sell{grid-template-columns:minmax(0,1fr) 58px 95px 95px}.stch-processing-dialog-item.gem{grid-template-columns:minmax(0,1fr) 115px 78px}.stch-craft-dialog-item{grid-template-columns:minmax(0,1fr) 70px 70px 70px}.stch-order-note{padding:10px 16px;color:#ffc902;font-size:12px}.stch-order-dialog-actions{display:flex;justify-content:flex-end;gap:10px;padding:12px 16px;border-top:1px solid #45556b}';var Ce=typeof globalThis.unsafeWindow<"u"?globalThis.unsafeWindow:window,Jr=Ce.jQuery||Ce.$||window.jQuery||window.$||null;var Wn="stch_sidebar_pinned",Qn="stch_sidebar_gem_price",Xr="stch_order_cache";var Zr="753-Sack of Gems";var Oa={2:{factor:.78,highWeight:.2},3:{factor:.8,highWeight:.3},4:{factor:.84,highWeight:.25}},Yn="stch_onboarding_seen",en="stch_multibuy_data",Ba=300*1e3,Jn=3e4,tn=Object.freeze([Object.freeze({id:"scan",label:"价格扫描"}),Object.freeze({id:"orders",label:"订购卡牌"}),Object.freeze({id:"active-orders",label:"订购单"}),Object.freeze({id:"history",label:"价格走势"}),Object.freeze({id:"craft",label:"徽章合成"}),Object.freeze({id:"blacklist",label:"黑名单"}),Object.freeze({id:"surplus",label:"多余物品"}),Object.freeze({id:"collection",label:"物品收藏"}),Object.freeze({id:"settings",label:"设置"})]),yt=Object.freeze(tn.map(e=>e.id));function fr(e){let t=new Set(yt),r=new Set,n=[];if(Array.isArray(e))for(let s of e)typeof s!="string"||!t.has(s)||r.has(s)||(r.add(s),n.push(s));for(let s of yt)r.has(s)||n.push(s);return n}function Xn(e){let r=(typeof e=="string"?e.trim():"").match(/^#?([0-9a-f]{6})$/i);return r?`#${r[1].toUpperCase()}`:""}function Ht(e){let t=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r={};for(let n of yt){let s=Xn(t[n]);s&&(r[n]=s)}return r}var La="stch_config",Ta=32,vt=Object.freeze({conservative:Object.freeze({anchorKey:"automaticConservativeWallAnchor",wallOffsetKey:"automaticConservativeWallOffset",noWallOffsetKey:"automaticConservativeNoWallOffset"}),balanced:Object.freeze({anchorKey:"automaticBalancedWallAnchor",wallOffsetKey:"automaticBalancedWallOffset",noWallOffsetKey:"automaticBalancedNoWallOffset"}),aggressive:Object.freeze({anchorKey:"automaticAggressiveWallAnchor",wallOffsetKey:"automaticAggressiveWallOffset",noWallOffsetKey:"automaticAggressiveNoWallOffset"})}),O={configVersion:Ta,currencyId:23,threshold:5,requestInterval:330,showNoResultLogs:!1,showAdvancedSettings:!1,sidebarDisabled:!1,includeDrops:!1,foilScanMode:!1,showScanCompletionColumn:!0,showScanSellSetColumn:!0,orderCacheDays:3,skipCachedOrderResults:!1,maxBadgePages:1,blacklist:"",blacklistNames:"{}",blacklistSources:"{}",blacklistDates:"{}",blacklistFixed:"{}",blacklistPriceData:"{}",blacklistExpiryDays:7,autoBlackThreshold:10,autoBlackEnabled:!1,buyMode:"complete5",orderPriceSource:"lowest",priceAdjustment:0,automaticPricingEnabled:!1,automaticPriceStrategy:"balanced",automaticConservativeWallAnchor:"bottom",automaticConservativeWallOffset:0,automaticConservativeNoWallOffset:-.02,automaticBalancedWallAnchor:"top",automaticBalancedWallOffset:0,automaticBalancedNoWallOffset:-.01,automaticAggressiveWallAnchor:"top",automaticAggressiveWallOffset:.01,automaticAggressiveNoWallOffset:.01,parallelOrderPricingEnabled:!1,parallelOrderPricingConcurrency:4,parallelOtherRequestsEnabled:!0,parallelOtherRequestsConcurrency:8,minimumPriceFallback:!0,earlyPricePrediction:!0,earlyPredictionAutoBlacklist:!1,craftInterval:500,craftMode:"step",surplusOnlyTradable:!1,surplusOnlyRecommended:!0,surplusItemMode:"card",surplusSellPriceSource:"lowest",surplusSellPriceAdjustment:0,grindReserveCopies:1,grindIncludePointsShopItems:!1,tabOrder:[...yt],tabColors:{}};function Fa(e){let t={...O};if(!e||typeof e!="object"||Array.isArray(e))return t;let r=typeof e.surplusOnlyRecommended=="boolean"?e.surplusOnlyRecommended:typeof e.grindOnlyRecommended=="boolean"?e.grindOnlyRecommended:t.surplusOnlyRecommended,n=typeof e.minimumPriceFallback=="boolean"?e.minimumPriceFallback:typeof e.noBuyOrderMinimumFallback=="boolean"?e.noBuyOrderMinimumFallback:t.minimumPriceFallback,s={...t,...e};for(let u of Object.keys(s))Object.prototype.hasOwnProperty.call(t,u)||delete s[u];let o=Number(s.currencyId);s.currencyId=Number.isInteger(o)&&o>0?o:t.currencyId,s.automaticPricingEnabled=s.automaticPricingEnabled===!0,s.parallelOrderPricingEnabled=s.parallelOrderPricingEnabled===!0,s.parallelOtherRequestsEnabled=s.parallelOtherRequestsEnabled!==!1,s.showAdvancedSettings=s.showAdvancedSettings===!0,s.sidebarDisabled=s.sidebarDisabled===!0,s.showScanCompletionColumn=s.showScanCompletionColumn!==!1,s.showScanSellSetColumn=s.showScanSellSetColumn!==!1,s.minimumPriceFallback=n,s.surplusOnlyRecommended=r,s.tabOrder=fr(s.tabOrder),s.tabColors=Ht(s.tabColors);let i=Number(s.blacklistExpiryDays);s.blacklistExpiryDays=Number.isFinite(i)?Math.max(1,Math.floor(i)):t.blacklistExpiryDays;let c=Number(s.parallelOrderPricingConcurrency);s.parallelOrderPricingConcurrency=Number.isFinite(c)?Math.min(20,Math.max(1,Math.floor(c))):t.parallelOrderPricingConcurrency;let l=Number(s.parallelOtherRequestsConcurrency);s.parallelOtherRequestsConcurrency=Number.isFinite(l)?Math.min(20,Math.max(1,Math.floor(l))):t.parallelOtherRequestsConcurrency,s.automaticPriceStrategy=["conservative","balanced","aggressive"].includes(s.automaticPriceStrategy)?s.automaticPriceStrategy:t.automaticPriceStrategy;for(let u of["priceAdjustment",...Object.values(vt).flatMap(d=>[d.wallOffsetKey,d.noWallOffsetKey])]){let d=Number(s[u]);s[u]=Number.isFinite(d)?d:t[u]}for(let u of Object.values(vt))s[u.anchorKey]=["top","bottom"].includes(s[u.anchorKey])?s[u.anchorKey]:t[u.anchorKey];return s.configVersion=Ta,s}function Da(e=O,t="balanced"){let r=Object.hasOwn(vt,t)?t:O.automaticPriceStrategy;return{strategy:r,...Ha(e,r)}}function qt(e=O,t=null){if(e?.automaticPricingEnabled){let r=["conservative","balanced","aggressive"].includes(e.automaticPriceStrategy)?e.automaticPriceStrategy:O.automaticPriceStrategy,n=t?.strategy===r?t:null;return{automatic:!0,priceSource:r,adjustment:0,strategyRule:n?{wallAnchor:n.wallAnchor,wallOffsetMinor:n.wallOffsetMinor,noWallOffsetMinor:n.noWallOffsetMinor}:Ha(e,r)}}return{automatic:!1,priceSource:["lowest","median","highest"].includes(e?.orderPriceSource)?e.orderPriceSource:O.orderPriceSource,adjustment:Number.isFinite(Number(e?.priceAdjustment))?Number(e.priceAdjustment):O.priceAdjustment}}function Ha(e=O,t="balanced"){let r=Object.hasOwn(vt,t)?t:"balanced",n=vt[r],s=["top","bottom"].includes(e?.[n.anchorKey])?e[n.anchorKey]:O[n.anchorKey],o=i=>{let c=Number(e?.[i]),l=Number(O[i])||0;return Math.round((Number.isFinite(c)?c:l)*100)};return{wallAnchor:s,wallOffsetMinor:o(n.wallOffsetKey),noWallOffsetMinor:o(n.noWallOffsetKey)}}function qa(){let e={...O,tabOrder:[...yt],tabColors:{}};try{let t=GM_getValue(La,null);if(t){let r=typeof t=="string"?JSON.parse(t):t,n=Fa(r);return JSON.stringify(r)!==JSON.stringify(n)&&ue(n),n}}catch(t){console.warn("[STCH] Config load failed:",t)}return e}function ue(e){let t=Fa(e);for(let r of Object.keys(e||{}))Object.prototype.hasOwnProperty.call(t,r)||delete e[r];Object.assign(e,t),GM_setValue(La,JSON.stringify(t))}var a={cfg:qa(),currencyContext:null,results:[],scanning:!1,stopRequested:!1,skipCurrent:!1,queue:null,sortKey:null,sortAsc:!0,selectedResults:new Set,recalculationRunning:!1,orderSubmissionRunning:!1,automaticPricingDraft:null,pendingOrderQuantities:new Map,highestBuyPrices:new Map,marketOrderDepths:new Map,craftResults:[],craftScanning:!1,craftActionRunning:!1,craftStopRequested:!1,craftQueue:null,surplusResults:[],selectedSurplusResults:new Set,surplusScanning:!1,surplusStopRequested:!1,surplusQueue:null,surplusActionRunning:!1,surplusGemPrice:null,grindResults:[],selectedGrindResults:new Set,grindScanning:!1,grindStopRequested:!1,grindQueue:null,grindGemPrice:null,itemCollectionItems:[],selectedItemCollection:new Set,itemCollectionHealthy:!0,orderResults:[],selectedOrderResults:new Set,orderSortKey:"cached",orderSortAsc:!1,orderActionRunning:!1,activeBuyOrders:[],activeBuyOrderGroups:[],selectedActiveBuyOrderGroups:new Set,activeOrdersLoading:!1,activeOrderPriceQueryRunning:!1,activeOrdersCancelling:!1,activeOrdersLoadedAt:0,activeOrdersGameFilter:"all",activeOrderLowestPrices:new Map,historySource:"scan",historyMarketHashName:"",historyRange:"7d",historyRefreshing:!1,sidebarPriceRefreshing:!1,blLookupAppid:"",blLookupName:""};var Z=Object.freeze({USD:1,CNY:23,HKD:29}),Pl=Object.freeze({[Z.USD]:Object.freeze({currencyId:Z.USD,code:"USD",name:"US Dollar",symbol:"$",symbolPosition:"before",symbolSpacing:!1,locale:"en-US",decimalDigits:2,decimalSeparator:".",groupSeparator:",",marketMinimumMinor:1,minimumBuyerMinor:3,steamFeeRate:.05,publisherFeeRate:.1,steamFeeMinimumMinor:1,publisherFeeMinimumMinor:1,steamFeeBaseMinor:0,verified:!0}),[Z.CNY]:Object.freeze({currencyId:Z.CNY,code:"CNY",name:"Chinese Yuan",symbol:"¥",symbolPosition:"before",symbolSpacing:!1,locale:"zh-CN",decimalDigits:2,decimalSeparator:".",groupSeparator:",",marketMinimumMinor:7,minimumBuyerMinor:21,steamFeeRate:.05,publisherFeeRate:.1,steamFeeMinimumMinor:7,publisherFeeMinimumMinor:7,steamFeeBaseMinor:0,verified:!0}),[Z.HKD]:Object.freeze({currencyId:Z.HKD,code:"HKD",name:"Hong Kong Dollar",symbol:"HK$",symbolPosition:"before",symbolSpacing:!0,locale:"zh-HK",decimalDigits:2,decimalSeparator:".",groupSeparator:",",marketMinimumMinor:1,minimumBuyerMinor:3,steamFeeRate:.05,publisherFeeRate:.1,steamFeeMinimumMinor:1,publisherFeeMinimumMinor:1,steamFeeBaseMinor:0,verified:!0})}),Xe=null,Ua=new WeakSet;function fe(...e){return e.find(t=>t!=null&&t!=="")}function ts(e){let t=Number(e);return Number.isFinite(t)?t:null}function Zn(e,t){let r=ts(e);return r!=null&&r>=0?Math.floor(r):t}function za(e,t){let r=ts(e);return r!=null&&r>0?Math.floor(r):t}function Ga(e,t){let r=ts(e);return r==null||r<0?t:r>1?r/100:r}function nn(e){if(typeof e=="string"){let r=e.trim().toUpperCase();if(r==="USD")return Z.USD;if(r==="CNY"||r==="RMB")return Z.CNY;if(r==="HKD")return Z.HKD}let t=Number(e);return Number.isInteger(t)&&t>0?t:null}function qe(e){if(!e||typeof e!="object")return null;let t=fe(e.currencyId,e.currency_id,e.wallet_currency,e.walletCurrency,e.eCurrency,e.currency),r=nn(t);return r??nn(fe(e.code,e.currencyCode,e.wallet_currency_code))}function es(e){return!!(e&&typeof e=="object"&&(Object.hasOwn(e,"wallet_currency")||Object.hasOwn(e,"wallet_market_minimum")||Object.hasOwn(e,"wallet_fee_percent")||Object.hasOwn(e,"wallet_fee_minimum")))}function Ol(e){let t=e==null?"unknown":String(e);return{currencyId:e,code:e==null?"UNRESOLVED":`STEAM-${t}`,name:e==null?"Unresolved currency":`Steam currency ${t}`,symbol:"¤",symbolPosition:"before",symbolSpacing:!1,locale:"en-US",decimalDigits:2,decimalSeparator:".",groupSeparator:",",marketMinimumMinor:1,minimumBuyerMinor:3,steamFeeRate:.05,publisherFeeRate:.1,steamFeeMinimumMinor:1,publisherFeeMinimumMinor:1,steamFeeBaseMinor:0}}function Bl(e){return!e||typeof e!="object"?{}:e.currencyContext&&typeof e.currencyContext=="object"?e.currencyContext:e}function we(e,t={}){let r=Bl(e&&typeof e=="object"?e:{currencyId:e}),n=r.walletInfo&&typeof r.walletInfo=="object"?r.walletInfo:es(r)?r:{},s=qe(r)??qe(n),o=s==null?null:Pl[s],i=o||Ol(s),c={...n,...r},l=i.decimalDigits,u=za(fe(c.marketMinimumMinor,c.walletMarketMinimumMinor,c.wallet_market_minimum),i.marketMinimumMinor),d=za(fe(c.minimumBuyerMinor,c.marketMinimumBuyerMinor,c.minimumBuyerAmount),u*3),m=fe(c.wallet_fee_minimum,c.feeMinimumMinor),p=Zn(fe(c.steamFeeMinimumMinor,c.steam_fee_minimum,m,c.wallet_market_minimum),i.steamFeeMinimumMinor),h=Zn(fe(c.publisherFeeMinimumMinor,c.publisher_fee_minimum,c.wallet_publisher_fee_minimum,m,c.wallet_market_minimum),i.publisherFeeMinimumMinor),f=!!o?.verified,g=String(fe(t.source,c.source,"manual")),y=!!fe(t.isFallback,c.isFallback,!1),b=f?y?"fallback":"verified":"unverified",S=i.code,M=Object.freeze({currencyId:s,id:s,currency:s,code:S,currencyCode:S,name:i.name,symbol:i.symbol,symbolPosition:i.symbolPosition,symbolSpacing:i.symbolSpacing,locale:i.locale,decimalDigits:l,decimals:l,minorDigits:l,fractionDigits:l,minorUnitFactor:10**l,decimalSeparator:i.decimalSeparator,groupSeparator:i.groupSeparator,marketMinimumMinor:u,minimumBuyerMinor:d,marketMinimumBuyerMinor:d,steamFeeRate:Ga(fe(c.steamFeeRate,c.wallet_fee_percent),i.steamFeeRate),publisherFeeRate:Ga(fe(c.publisherFeeRate,c.wallet_publisher_fee_percent_default),i.publisherFeeRate),steamFeeMinimumMinor:p,publisherFeeMinimumMinor:h,steamFeeBaseMinor:Zn(fe(c.steamFeeBaseMinor,c.wallet_fee_base),i.steamFeeBaseMinor),verified:f,isVerified:f,unverified:!f,isUnverified:!f,verification:f?"verified":"unverified",status:b,source:g,isFallback:y});return Ua.add(M),M}function ja(e){return String(e||"").replace(/"|"|"/gi,'"').replace(/'|'|'/gi,"'").replace(/<|<|</gi,"<").replace(/>|>|>/gi,">").replace(/&|&|&/gi,"&")}function rn(e){if(e&&typeof e=="object")return e;let t=String(e||"").trim();if(!t)return null;for(let r=0;r<2;r+=1){t=ja(t).trim();try{let n=JSON.parse(t);if(n&&typeof n=="object")return n;if(typeof n=="string"){t=n;continue}}catch{}}return null}function Va(){return typeof globalThis>"u"?{}:globalThis.unsafeWindow||globalThis.window||globalThis}function Ll(e){let t=rn(e.applicationConfigWalletInfo);if(qe(t)!=null)return t;let r=e.applicationConfig;if(r){let c=typeof r=="string"?r:fe(r.dataset?.walletinfo,r.dataset?.walletInfo,r.getAttribute?.("data-walletinfo")),l=rn(c||r);if(qe(l)!=null)return l}let n=e.document||(typeof document<"u"?document:null),s=n?.getElementById?.("application_config")||n?.querySelector?.("#application_config"),o=fe(s?.dataset?.walletinfo,s?.dataset?.walletInfo,s?.getAttribute?.("data-walletinfo")),i=rn(o);return qe(i)!=null?i:null}function Tl(e){let t=e.document||(typeof document<"u"?document:null),r=Va(),n=e.location||r.location,s=fe(r.g_strCountryCode,r.UserConfig?.country_code,r.UserConfig?.COUNTRY),o=[e.pageText,e.pageHtml,t?.documentElement?.innerHTML,t?.body?.textContent,n?.href].filter(Boolean),i=ja(o.join(` `)).replace(/\\(["'])/g,"$1"),c=String(s||"").trim().toUpperCase()==="HK";if(!i)return c?Z.HKD:null;let l=[/wallet_currency["']?\s*[:=]\s*["']?(\d+)/i,/(?:data-)?currency(?:-id)?["']?\s*[:=]\s*["']?(\d+)/i,/[?&]currency=(\d+)(?:&|$)/i,/eCurrency["']?\s*[:=]\s*["']?(\d+)/i];for(let u of l){let d=i.match(u),m=nn(d?.[1]);if(m!=null)return m}return/\b(?:CNY|RMB)\b/i.test(i)||/[¥¥]\s*[+-]?\d/.test(i)?Z.CNY:/\bHKD\b/i.test(i)||/HK\$\s*[+-]?\d/i.test(i)||/(?:country_code|COUNTRY|country)[\\"']?\s*[:=]\s*[\\"']?HK\b/i.test(i)||c?Z.HKD:/\bUSD\b/i.test(i)||/\$\s*[+-]?\d/.test(i)?Z.USD:null}function Fl(e){return!e||typeof e!="object"?e==null?{}:{configuredCurrencyId:e}:["walletInfo","configuredCurrencyId","applicationConfigWalletInfo","applicationConfig","document","pageText","pageHtml","location"].some(r=>Object.hasOwn(e,r))?e:{walletInfo:e}}function Dl(e={}){let t=Fl(e),r=Va(),n=rn(Object.hasOwn(t,"walletInfo")?t.walletInfo:r.g_rgWalletInfo);if(qe(n)!=null)return we(n,{source:"walletInfo",isFallback:!1});let s=Ll(t);if(qe(s)!=null)return we(s,{source:"application_config",isFallback:!1});let o=Tl(t);if(o!=null)return we(o,{source:"page",isFallback:!1});let i=nn(t.configuredCurrencyId);return i!=null?we(i,{source:"configured",isFallback:!0}):we(null,{source:"unresolved",isFallback:!0})}function Ka(e={}){return Xe=Dl(e),Xe}function Wa(e){return e==null?(Xe=null,null):(Xe=we(e,{source:e?.source||"manual",isFallback:e?.isFallback||!1}),Xe)}function he(){return Xe}function xt(e){return we(e,{source:"definition",isFallback:!1})}function ze(e){return e==null?Xe||we(null,{source:"unresolved",isFallback:!0}):typeof e=="number"||typeof e=="string"?we(e,{source:"manual",isFallback:!1}):Ua.has(e)?e:e.currencyContext?ze(e.currencyContext):qe(e)!=null||es(e)?we(e,{source:e.source||(es(e)?"walletInfo":"manual"),isFallback:e.isFallback||!1}):Xe||we(null,{source:"unresolved",isFallback:!0})}function Qa(e,t){return e&&typeof e=="object"&&(Object.hasOwn(e,"useGrouping")||Object.hasOwn(e,"invalidPlaceholder"))&&qe(e)==null&&!e.currencyContext?{context:ze(),options:e}:{context:ze(e),options:t||{}}}function Hl(e){if(typeof e=="bigint")return e;if(typeof e=="number")return Number.isSafeInteger(e)?BigInt(e):null;let t=String(e??"").trim();return/^[+-]?\d+$/.test(t)?BigInt(t):null}function Ya(e,t,r){let n=Hl(e);if(n==null)return r.invalidPlaceholder||"?";let s=n<0n,o=s?-n:n,i=t.decimalDigits,c=10n**BigInt(i),l=i>0?o/c:o,u=i>0?o%c:0n,d=l.toString();r.useGrouping!==!1&&t.groupSeparator&&(d=d.replace(/\B(?=(\d{3})+(?!\d))/g,t.groupSeparator));let m=i>0?`${t.decimalSeparator}${u.toString().padStart(i,"0")}`:"";return`${s?"-":""}${d}${m}`}function zt(e,t,r){let{context:n,options:s}=Qa(t,r);return Ya(e,n,s)}function w(e,t,r){let{context:n,options:s}=Qa(t,r),o=Ya(e,n,s),i=s.invalidPlaceholder||"?";if(o===i)return i;let c=o.startsWith("-"),l=c?o.slice(1):o,u=n.symbolSpacing?" ":"",d=c?"-":"";return n.symbolPosition==="after"?`${d}${l}${u}${n.symbol}`:`${d}${n.symbol}${u}${l}`}function sn(e){return typeof e=="boolean"?e:!!e?.isFoil}function rs(e){if(!e||typeof e!="object")return!1;if(e.isUnlimitedLevelBadge)return!0;let t=[e.appid,e.gameName,e.badgeName,e.metaDescription].filter(Boolean).join(" ");return/(?:summer|winter|spring|autumn|fall)\s+sale|steam\s+(?:sale|awards)|(?:夏季|夏日|冬季|秋季|春季|农历新年|春节).{0,8}(?:特卖|促销|徽章)|(?:特卖|促销).{0,8}徽章/i.test(t)}function ae(e){return!sn(e)&&rs(e)?Math.max(0,Number(e.level)||0)+5:sn(e)?1:5}function hr(e,t={}){let r=new URLSearchParams;sn(e)&&r.set("border","1"),t.language&&r.set("l",t.language);let n=r.toString();return n?`?${n}`:""}function Ze(e,t,r,n={}){return`${String(e||"").replace(/\/+$/,"")}/gamecards/${t}/${hr(r,n)}`}function Ja(e){return sn(e)?"闪卡":"普通卡"}function an(e){return zt(e,Z.CNY,{useGrouping:!1})}function ie(e){let t=Number(e);return Number.isFinite(t)?t.toLocaleString("zh-CN"):"—"}function St(e){let t=parseInt(String(e||"").replace(/[^\d]/g,""),10);return Number.isFinite(t)?t:0}function on(e){let t=document.createElement("textarea");return t.innerHTML=String(e||""),t.value}var gr=typeof globalThis<"u"?globalThis.unsafeWindow||globalThis.window||globalThis:{};function Q(){let e=gr.g_strProfileURL||document.querySelector("#global_actions a.user_avatar")?.href||document.querySelector(".user_avatar[href*='/id/'], .user_avatar[href*='/profiles/']")?.href||null;return e?e.replace(/\/$/,""):null}function et(){let e=String(gr.g_steamID||"").trim();if(/^\d{17}$/.test(e))return e;let r=document.getElementById("application_config")?.getAttribute("data-userinfo")||"";if(r)try{let i=JSON.parse(on(r));if(/^\d{17}$/.test(String(i?.steamid||"")))return String(i.steamid)}catch{}let s=(Q()||"").match(/\/profiles\/(\d{17})(?:\/|$)/);if(s)return s[1];let o=document.documentElement.innerHTML.match(/g_steamID\s*=\s*["'](\d{17})["']/);return o?o[1]:""}function Xa(){return location.hostname==="steamcommunity.com"&&/\/inventory\/?$/i.test(location.pathname)}function Za(e){let t=String(e||"").match(/(?:g_steamID\s*=\s*["']|"steamid"\s*:\s*")(\d{17})/);return t?t[1]:""}function eo(e){let t=String(e||"").match(/\/profiles\/(\d{17})(?:\/|$)/);return t?t[1]:""}function ql(e){let r=e?.walletInfo||(e&&typeof e=="object"&&Object.hasOwn(e,"wallet_market_minimum")?e:null)||(e==null?gr.g_rgWalletInfo:null),n=Number(r?.wallet_market_minimum);if(Number.isFinite(n)&&n>0)return Math.floor(n)*3;let s=e??he();if(s||r){let o=ze(s||r),i=Number(o.minimumBuyerMinor??o.marketMinimumBuyerMinor??Number(o.marketMinimumMinor)*3);if(Number.isFinite(i)&&i>0)return Math.floor(i)}return null}function Ae(e){return ql(e)}function Pe(){if(gr.g_sessionID)return gr.g_sessionID;let e=document.cookie.match(/(?:^|;\s*)sessionid=([^;]+)/);return e?decodeURIComponent(e[1]):""}function zl(e){let t=e?.querySelector("img.gamecard, .game_card_ctn img"),r=String(t?.getAttribute("src")||"").trim();if(/^https?:\/\//i.test(r))return r;if(r.startsWith("//"))return`https:${r}`;let s=String(e?.querySelector(".game_card_ctn")?.getAttribute("onclick")||"").match(/https?:\\?\/\\?\/[^"')\s]+/i);return s?s[0].replace(/\\\//g,"/"):""}function Ct(e,t,r){let n=new DOMParser().parseFromString(e,"text/html"),s="",o=n.querySelector(".badge_title");o&&(s=(o.querySelector(".badge_title_row")?.textContent||o.textContent).replace(/(?:View badge progress|查看徽章进度|View details|查看详情|[\u200B\u200C\u200D\ufeff])/gi,"").replace(/\s*(?:徽章|Badge)\s*$/i,"").trim());let i=0,c=n.querySelector('meta[name="Description"]')?.content||"",l=c.match(/(?:徽章[((](\d+)\s*级|Badge\s*\(Level\s*(\d+)\)|Level\s*(\d+)\b)/i);l&&(i=parseInt(l[1]||l[2]||l[3],10));let u=!r&&rs({appid:t,gameName:s,level:i,metaDescription:c}),d=ae({isFoil:r,level:i,gameName:s,appid:t,metaDescription:c,isUnlimitedLevelBadge:u}),m=0,p=n.querySelector(".progress_info_bold");if(p){let x=p.textContent,I=x.match(/(\d+)\s*card drops?\s*remaining/i)||x.match(/(\d+)\s*张剩余卡牌掉落/);I&&(m=parseInt(I[1],10))}let h=n.querySelectorAll(".badge_card_set_card"),f=[];h.forEach((x,I)=>{let N=x.querySelector(".badge_card_set_title");if(!N)return;let A=x.querySelector(".badge_card_set_text_qty"),B=A&&parseInt(A.textContent.replace(/[()()\[\]]/g,""),10)||0,T=N.textContent.trim();A&&(T=T.replace(A.textContent,"").trim());let L="",q=(x.querySelector('a[href*="/market/listings/"]')?.getAttribute("href")||"").match(/\/market\/listings\/\d+\/(.+?)(?:\?|#|$)/);if(q)try{L=decodeURIComponent(q[1])}catch{L=q[1]}f.push({name:T,owned:B,marketHashName:L,imageUrl:zl(x),idx:I})});let g=n.querySelector('a[href*="multibuy"]');if(g){let x=g.getAttribute("href")||"",I=[];try{I=new URL(x,window.location.origin).searchParams.getAll("items[]")}catch{I=(x.match(/[?&]items\[\]=([^&]+)/g)||[]).map(B=>{try{return decodeURIComponent(B.replace(/[?&]items\[\]=/,"").replace(/&$/,""))}catch{return B}})}for(let N=0;N{let I=x.querySelector(".badge_card_set_title"),N=x.querySelector('a[href*="/market/listings/"]');if(!I||!N)return;let A=I.textContent.trim(),T=(N.getAttribute("href")||"").match(/\/market\/listings\/\d+\/(.+?)(?:\?|$)/);if(!T)return;let L="";try{L=decodeURIComponent(T[1])}catch{L=T[1]}for(let z of f)if(z.name===A&&!z.marketHashName){z.marketHashName=L;break}}),f.forEach(x=>{!x.marketHashName&&t&&x.name&&(x.marketHashName=`${t}-${x.name}`)});let b=f.length;if(b===0)return{gameName:s,level:i,isUnlimitedLevelBadge:u,totalInSet:0,dropsRemaining:m,cards:f,need:0,setsToLevel5:0,targetLevel:d};let S=f.reduce((x,I)=>x+Math.min(I.owned,1),0),M=Math.max(0,b-S),E=Math.max(0,d-i);return{gameName:s,level:i,isUnlimitedLevelBadge:u,totalInSet:b,dropsRemaining:m,cards:f,need:M,setsToLevel5:E,targetLevel:d}}function to(e){let t=new DOMParser().parseFromString(e,"text/html"),r=[],n=new Set;return t.querySelectorAll(".badge_row").forEach(s=>{let o=s.querySelector(".badge_progress_info a.badge_craft_button[href*='/gamecards/']");if(!o)return;let i=o.getAttribute("href")||"",c=i.match(/\/gamecards\/(\d+)\/?/);if(!c)return;let l=c[1],u=/[?&]border=1(?:&|$)/.test(i),d=`${l}_${u?1:0}`;if(n.has(d))return;n.add(d);let p=(s.querySelector(".badge_title")?.textContent||"").replace(/(?:View details|查看详情|[\u200B\u200C\u200D\ufeff])/gi,"").trim();r.push({appid:l,isFoil:u,gameName:p,href:i})}),r}function ro(e,t){let r=Ct(e,t.appid,t.isFoil),n=new DOMParser().parseFromString(e,"text/html"),s=n.querySelector(".gamecard_badge_craftbtn_ctn .badge_craft_button"),c=(n.querySelector(".gamecard_badge_craftbtn_ctn .badge_craft_button.multicraft")?.getAttribute("onclick")||"").match(/Profile_CraftGameBadge\([^)]*,\s*(\d+)\s*\)\s*;?\s*$/),l=c?Math.max(1,parseInt(c[1],10)||1):s?1:0,u=r.cards.length>0?Math.min(...r.cards.map(m=>Math.max(0,Number(m.owned)||0))):0,d=r.isUnlimitedLevelBadge&&l>0?u:Math.min(u,l);return{...t,gameName:t.gameName||r.gameName||"",level:r.level,cards:r.cards,totalInSet:r.totalInSet,isUnlimitedLevelBadge:r.isUnlimitedLevelBadge,availableSets:u,nativeMaxLevels:l,maxCraftable:d,craftCount:d,selected:d>0,status:d>0?"待合成":"不可合成"}}var ss=Object.freeze({PRICE_OVERVIEW:"priceoverview",LISTING_PAGE:"listing-page",LISTING_ORDERBOOK:"listing-orderbook",PRICE_HISTORY:"price-history",LEGACY_PRICE_RESULT:"legacy-price-result"}),br=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function kt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function de(...e){return e.find(t=>t!=null)}function Oe(e,t,r){for(let n of r)if(kt(e)&&br(e,n))return e[n];for(let n of r)if(kt(t)&&br(t,n))return t[n]}function ns(e){return String(e??"").trim()||null}function Gt(e){if(e==null||e==="")return null;let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}function Gl(e){return String(e??"").trim().toUpperCase()||null}function Ul(e){if(e instanceof Date){let n=e.getTime();return Number.isFinite(n)?n:null}if(typeof e=="number")return Number.isFinite(e)&&e>=0?Math.trunc(e):null;let t=String(e??"").trim();if(!t)return null;if(/^\d+$/.test(t)){let n=Number(t);return Number.isSafeInteger(n)?n:null}let r=Date.parse(t);return Number.isFinite(r)?r:null}function no(e){if(typeof e=="number")return Number.isSafeInteger(e)&&e>=0?e:null;let t=String(e??"").trim();if(!t||t.includes("-"))return null;let r=t.replace(/[\s\u00a0,.'’]/g,"");if(!/^\d+$/.test(r))return null;let n=Number(r);return Number.isSafeInteger(n)?n:null}function wt(e){let t=no(e);return t!==null&&t>0?t:null}function as(e){return no(e)}function so(e){let t=Number(de(e?.minorDigits,e?.decimalDigits,e?.fractionDigits,2));return Number.isInteger(t)&&t>=0&&t<=6?t:2}function yr(e,t=2){let r=Number.isInteger(Number(t))?Math.min(6,Math.max(0,Number(t))):2,n=10**r;if(typeof e=="number"){if(!Number.isFinite(e)||e<0)return null;let g=Math.round(e*n);return Number.isSafeInteger(g)?g:null}let s=String(e??"").trim();if(!s)return null;let o=s.replace(/[\s\u00a0'’]/g,"");if(o.includes("-"))return null;let i=o.replace(/[^\d.,]/g,"");if(!/\d/.test(i))return null;let c=[...i.matchAll(/\./g)].map(g=>g.index),l=[...i.matchAll(/,/g)].map(g=>g.index),u=c.at(-1)??-1,d=l.at(-1)??-1,m=null;if(r>0&&u>=0&&d>=0)m=u>d?".":",";else if(r>0&&(u>=0||d>=0)){let g=u>=0?".":",",y=g==="."?c:l,b=i.length-y.at(-1)-1,S=y.length===1&&b===3&&r!==3;b>0&&b<=r&&!S&&(m=g)}let p;if(m){let g=i.lastIndexOf(m),y=i.slice(0,g).replace(/[.,]/g,"")||"0",b=i.slice(g+1).replace(/[.,]/g,"");p=`${y}.${b}`}else p=i.replace(/[.,]/g,"");let h=Number(p);if(!Number.isFinite(h)||h<0)return null;let f=Math.round(h*n);return Number.isSafeInteger(f)?f:null}function os(e){return kt(e?.data)?e.data:kt(e)?e:{}}function jl(e){return e===!1||e===0||e==="0"}function is(e,t,r,n={}){return{appid:de(t?.appid,e?.appid,e?.app_id),marketHashName:de(t?.marketHashName,t?.market_hash_name,e?.marketHashName,e?.market_hash_name),currencyId:br(n,"currencyId")?n.currencyId:de(t?.currencyId,t?.currency),currencyCode:br(n,"currencyCode")?n.currencyCode:de(t?.currencyCode,t?.currency_code),observedAt:br(n,"observedAt")?n.observedAt:de(t?.observedAt,Date.now()),source:r}}function Ge(e,t={}){if(!kt(e))return null;let r=ns(Oe(e,t,["appid","app_id"])),n=ns(Oe(e,t,["marketHashName","market_hash_name"])),s=ns(Oe(e,t,["source"]));return!r||!n||!s?null:{schemaVersion:1,appid:r,marketHashName:n,currencyId:Gt(Oe(e,t,["currencyId","currency"])),currencyCode:Gl(Oe(e,t,["currencyCode","currency_code"])),lowestSellMinor:wt(Oe(e,t,["lowestSellMinor","lowestSellCents"])),medianMinor:wt(Oe(e,t,["medianMinor","medianCents"])),highestBuyMinor:wt(Oe(e,t,["highestBuyMinor","highestBuyCents"])),volume:as(Oe(e,t,["volume"])),observedAt:Ul(Oe(e,t,["observedAt","cachedAt","timestamp"])),source:s}}function ao(e,t={}){let r=os(e);if(jl(r.success))return null;let n=so(t);return Ge({...is(r,t,ss.PRICE_OVERVIEW),lowestSellMinor:yr(r.lowest_price,n),medianMinor:yr(r.median_price,n),highestBuyMinor:null,volume:as(r.volume)})}function Vl(e){let t=os(e);return kt(t.orderbook)?t.orderbook:kt(t.state?.data)?t.state.data:t}function cs(e,t={}){let r=Vl(e),n=Gt(de(r.eCurrency,r.currencyId,r.currency)),s=Gt(de(t.currencyId,t.currency)),o=n!==null&&s!==null&&n!==s;return Ge({...is(r,t,ss.LISTING_ORDERBOOK,{currencyId:de(n,s),currencyCode:o?null:de(t.currencyCode,t.currency_code)}),lowestSellMinor:wt(de(r.amtMinSellOrder,r.lowestSellMinor,r.lowestSellCents,r.lowest_sell_order)),medianMinor:null,highestBuyMinor:wt(de(r.amtMaxBuyOrder,r.highestBuyMinor,r.highestBuyCents,r.highest_buy_order)),volume:null})}function oo(e,t={}){let r=os(e),n=Gt(r.currency),s=Gt(r.historyCurrency),o=de(n,s),i=Gt(de(t.currencyId,t.currency)),c=n!==null&&i!==null&&n!==i||s!==null&&i!==null&&s!==i||n!==null&&s!==null&&n!==s;return Ge({...is(r,t,ss.LISTING_PAGE,{currencyId:de(o,i),currencyCode:c?null:de(t.currencyCode,t.currency_code)}),lowestSellMinor:wt(r.lowestSellCents),medianMinor:yr(r.medianPriceMajor,so(t)),highestBuyMinor:wt(r.highestBuyCents),volume:as(r.volume)})}function ls(e){let t=Ge(e);if(!t)return null;let r=t.lowestSellMinor??t.medianMinor;if(r===null)return{noPriceData:!0,volume:t.volume??0};let n=t.lowestSellMinor===null;return{lowestSellCents:r,medianCents:t.medianMinor??0,volume:t.volume??0,estimated:n,priceSource:n?"median":"lowest"}}var vr=1,uo="stch_market_cache",mo=720*60*60*1e3,po=5e3;function us(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ye(e,t,r="error",n=void 0){return n===void 0?{code:e,message:t,severity:r}:{code:e,message:t,severity:r,details:n}}function io(){return{schemaVersion:vr,records:[]}}function cn(e){return!e||e.currencyId===null?null:JSON.stringify([e.appid,e.marketHashName,e.currencyId,e.source])}function Kl(e){let t=new Map,r=0,n=0,s=0,o=0;return e.forEach(i=>{if(!us(i)){r+=1;return}if(i.schemaVersion===void 0||i.schemaVersion===null)s+=1;else{let d=Number(i.schemaVersion);if(!Number.isInteger(d)||d<=0)s+=1;else if(d!==1){o+=1;return}}let c=Ge(i),l=cn(c);if(!c||l===null||c.observedAt===null){r+=1;return}let u=t.get(l);u&&(n+=1),(!u||c.observedAt>=u.observedAt)&&t.set(l,c)}),{records:[...t.values()],invalidCount:r,duplicateCount:n,migratedSchemaCount:s,unsupportedSchemaCount:o}}function Wl(e){if(e==null||e===""){let c=io();return{ok:!0,envelope:c,cache:c,diagnostics:[],needsMigration:!1}}let t=e;if(typeof e=="string"){if(!e.trim()){let c=io();return{ok:!0,envelope:c,cache:c,diagnostics:[],needsMigration:!1}}try{t=JSON.parse(e)}catch(c){return{ok:!1,envelope:null,cache:null,diagnostics:[ye("invalid-json","Market cache is not valid JSON; the stored value was left untouched.","error",{error:String(c?.message||c)})],needsMigration:!1}}}let r=[],n=!1,s;if(Array.isArray(t))s=t,n=!0,r.push(ye("legacy-array-envelope","Legacy array cache was decoded in memory and has not been rewritten.","warning"));else if(us(t)){if(!Array.isArray(t.records))return{ok:!1,envelope:null,cache:null,diagnostics:[ye("invalid-records","Market cache envelope has no records array; the stored value was left untouched.")],needsMigration:!1};s=t.records;let c=Number(t.schemaVersion);if(!Number.isInteger(c)||c<=0)n=!0,r.push(ye("missing-schema-version","Cache envelope has no valid schema version and was normalized in memory only.","warning"));else if(c!==vr)return{ok:!1,envelope:null,cache:null,diagnostics:[ye("unsupported-schema-version",`Market cache schema ${c} is not supported by schema ${vr}.`,"error",{schemaVersion:c,supportedSchemaVersion:vr})],needsMigration:!1}}else return{ok:!1,envelope:null,cache:null,diagnostics:[ye("invalid-envelope","Market cache must be an object envelope or a legacy record array.")],needsMigration:!1};let o=Kl(s),i={schemaVersion:vr,records:o.records};return o.invalidCount>0&&(n=!0,r.push(ye("invalid-records-dropped",`${o.invalidCount} invalid market cache record(s) were excluded in memory; storage was not rewritten.`,"error",{count:o.invalidCount}))),o.unsupportedSchemaCount>0&&(n=!0,r.push(ye("unsupported-record-schema",`${o.unsupportedSchemaCount} record(s) use an unsupported market data schema and were excluded in memory.`,"error",{count:o.unsupportedSchemaCount,supportedSchemaVersion:1}))),o.migratedSchemaCount>0&&(n=!0,r.push(ye("record-schema-normalized",`${o.migratedSchemaCount} legacy record schema(s) were normalized in memory only.`,"warning",{count:o.migratedSchemaCount}))),o.duplicateCount>0&&(n=!0,r.push(ye("duplicate-records-collapsed",`${o.duplicateCount} duplicate cache record(s) were collapsed to the newest observation in memory.`,"warning",{count:o.duplicateCount}))),{ok:!r.some(c=>c.severity==="error"),envelope:i,cache:i,diagnostics:r,needsMigration:n}}function fo(e){if(us(e)&&e.schemaVersion!==void 0&&Number(e.schemaVersion)!==1)throw new TypeError(`Unsupported market record schema ${e.schemaVersion}.`);let t=Ge(e),r=cn(t);if(!t||r===null||t.observedAt===null)throw new TypeError("A cache record requires appid, marketHashName, currencyId, source, and observedAt.");if(t.schemaVersion!==1)throw new TypeError(`Unsupported market record schema ${t.schemaVersion}.`);return{normalized:t,key:r}}function Ql(e,t,r={}){let{normalized:n,key:s}=fo(t),o=e.records.findIndex(i=>cn(i)===s);return o<0?{...e,records:[...e.records,n]}:r.preferNewest!==!1&&e.records[o].observedAt>n.observedAt?e:{...e,records:e.records.map((i,c)=>c===o?n:i)}}function Yl(e,t,r={}){if(!Array.isArray(t))throw new TypeError("Market cache records must be an array.");let n=[...e.records],s=new Map(n.map((o,i)=>[cn(o),i]));for(let o of t){let{normalized:i,key:c}=fo(o),l=s.get(c);if(l===void 0){s.set(c,n.length),n.push(i);continue}r.preferNewest!==!1&&n[l].observedAt>i.observedAt||(n[l]=i)}return{...e,records:n}}function co(e,t={}){let r=Number(e?.observedAt);if(!Number.isFinite(r))return!1;let n=t.ttlMs===void 0?mo:Number(t.ttlMs);if(n===1/0)return!0;if(!Number.isFinite(n))return!1;let s=t.now===void 0?Date.now():Number(t.now);return Number.isFinite(s)?s-r<=Math.max(0,n):!1}function lo(e,t={}){let r=t.now===void 0?Date.now():Number(t.now),n=t.ttlMs===void 0?mo:Number(t.ttlMs),s=t.maxEntries===void 0?po:Number(t.maxEntries),i=n!==1/0&&Number.isFinite(n)&&Number.isFinite(r)?Math.max(0,n):1/0,c=e.records.filter(d=>i===1/0||r-d.observedAt<=i);if(s===1/0||!Number.isFinite(s))return{...e,records:c};let l=Math.max(0,Math.floor(s));if(c.length<=l)return{...e,records:c};if(l===0)return{...e,records:[]};if(c.length===l+1){let d=0;for(let m=1;mp!==d)}}let u=new Set(c.map((d,m)=>({index:m,observedAt:d.observedAt})).sort((d,m)=>m.observedAt-d.observedAt||m.index-d.index).slice(0,l).map(d=>d.index));return{...e,records:c.filter((d,m)=>u.has(m))}}function Jl(e){return typeof e=="function"?e:typeof GM_getValue=="function"?GM_getValue:null}function Xl(e){return typeof e=="function"?e:typeof GM_setValue=="function"?GM_setValue:null}function Zl(e,t,r,n=[]){let s=JSON.stringify(e);try{r(t,s)}catch(o){return{ok:!1,envelope:e,cache:e,raw:s,storageKey:t,diagnostics:[ye("gm-write-failed","Failed to write the market cache.","error",{error:String(o?.message||o)})]}}return{ok:!0,envelope:e,cache:e,raw:s,storageKey:t,diagnostics:n}}function eu(e,t={}){let r=t.storageKey||t.key||uo,n=Xl(t.setValue);return n?Zl(e,r,n):{ok:!1,envelope:null,cache:null,raw:void 0,storageKey:r,diagnostics:[ye("gm-set-unavailable","GM_setValue is not available.")]}}function tu(e={}){let t=e.storageKey||e.key||uo,r=Jl(e.getValue);if(!r)return{ok:!1,envelope:null,cache:null,raw:void 0,storageKey:t,diagnostics:[ye("gm-get-unavailable","GM_getValue is not available.")],needsMigration:!1};let n;try{n=r(t,null)}catch(s){return{ok:!1,envelope:null,cache:null,raw:void 0,storageKey:t,diagnostics:[ye("gm-read-failed","Failed to read the market cache; no stored value was changed.","error",{error:String(s?.message||s)})],needsMigration:!1}}return{...Wl(n),raw:n,storageKey:t}}function ho(e,t={}){if(!Array.isArray(e))throw new TypeError("Market cache records must be an array.");let r=tu(t);if(!r.ok||!r.envelope||e.length===0)return{...r,saved:!1};let n=t.maxEntries===void 0?po:Number(t.maxEntries),s=!Number.isFinite(n)||r.envelope.records.length+e.length<=Math.max(0,Math.floor(n)),o={...t,now:t.now===void 0?Date.now():t.now},i=r.envelope.records.every(u=>co(u,o))&&e.every(u=>co(u,o)),c=s&&i?lo(Yl(r.envelope,e,t),t):e.reduce((u,d)=>lo(Ql(u,d,t),t),r.envelope),l=eu(c,t);return{...l,saved:l.ok}}var xr=1,yo="stch_market_history",go=3600*1e3,vo=365*24*60*60*1e3,ru=2e4;var xo=300*1e3;function ln(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ee(e,t,r="error",n=void 0){return n===void 0?{code:e,message:t,severity:r}:{code:e,message:t,severity:r,details:n}}function bo(){return{schemaVersion:xr,records:[]}}function nu(e){return Array.isArray(e)?e:ln(e)&&Array.isArray(e.records)?e.records:[]}function So(e={}){let t=e.sampleIntervalMs===void 0?go:Number(e.sampleIntervalMs);return Number.isFinite(t)&&t>0?Math.max(1,Math.floor(t)):go}function ds(e,t){return!e||e.currencyId===null||e.observedAt===null?null:JSON.stringify([e.appid,e.marketHashName,e.currencyId,e.source,Math.floor(e.observedAt/t)])}function Co(e){if(ln(e)&&e.schemaVersion!==void 0&&Number(e.schemaVersion)!==1)return null;let t=Ge(e);return!t||t.currencyId===null||t.observedAt===null||t.lowestSellMinor===null&&t.medianMinor===null&&t.highestBuyMinor===null&&t.volume===null?null:t}function wo(e,t={}){let r=So(t),n=new Map,s=0,o=0,i=0,c=0;return e.forEach(l=>{if(!ln(l)){s+=1;return}if(l.schemaVersion===void 0||l.schemaVersion===null)i+=1;else if(Number(l.schemaVersion)!==1){c+=1;return}let u=Co(l),d=ds(u,r);if(!u||d===null){s+=1;return}let m=n.get(d);m&&(o+=1),(!m||u.observedAt>=m.observedAt)&&n.set(d,u)}),{records:[...n.values()],invalidCount:s,duplicateCount:o,migratedSchemaCount:i,unsupportedSchemaCount:c}}function ko(e,t={}){return{schemaVersion:xr,records:wo(nu(e),t).records}}function su(e,t={}){if(e==null||e===""){let l=bo();return{ok:!0,envelope:l,history:l,diagnostics:[],needsMigration:!1}}let r=e;if(typeof e=="string"){if(!e.trim()){let l=bo();return{ok:!0,envelope:l,history:l,diagnostics:[],needsMigration:!1}}try{r=JSON.parse(e)}catch(l){return{ok:!1,envelope:null,history:null,diagnostics:[Ee("invalid-json","Market history is not valid JSON; the stored value was left untouched.","error",{error:String(l?.message||l)})],needsMigration:!1}}}let n=[],s=!1,o;if(Array.isArray(r))o=r,s=!0,n.push(Ee("legacy-array-envelope","Legacy market history was decoded in memory and has not been rewritten.","warning"));else{if(!ln(r)||!Array.isArray(r.records))return{ok:!1,envelope:null,history:null,diagnostics:[Ee("invalid-envelope","Market history must contain a records array; the stored value was left untouched.")],needsMigration:!1};if(Number(r.schemaVersion)!==xr)return{ok:!1,envelope:null,history:null,diagnostics:[Ee("unsupported-schema-version",`Market history schema ${r.schemaVersion} is not supported.`,"error",{schemaVersion:r.schemaVersion,supportedSchemaVersion:xr})],needsMigration:!1};o=r.records}let i=wo(o,t),c={schemaVersion:xr,records:i.records};return i.invalidCount>0&&(s=!0,n.push(Ee("invalid-records-dropped",`${i.invalidCount} invalid market history record(s) were excluded in memory.`,"error",{count:i.invalidCount}))),i.unsupportedSchemaCount>0&&(s=!0,n.push(Ee("unsupported-record-schema",`${i.unsupportedSchemaCount} market history record(s) use an unsupported schema.`,"error",{count:i.unsupportedSchemaCount,supportedSchemaVersion:1}))),i.migratedSchemaCount>0&&(s=!0,n.push(Ee("record-schema-normalized",`${i.migratedSchemaCount} legacy record schema(s) were normalized in memory only.`,"warning",{count:i.migratedSchemaCount}))),i.duplicateCount>0&&(s=!0,n.push(Ee("duplicate-samples-collapsed",`${i.duplicateCount} duplicate market history sample(s) were collapsed.`,"warning",{count:i.duplicateCount}))),{ok:!n.some(l=>l.severity==="error"),envelope:c,history:c,diagnostics:n,needsMigration:s}}function au(e,t={}){let r=t.now===void 0?Date.now():Number(t.now),n=t.ttlMs===void 0?vo:Number(t.ttlMs),s=t.maxEntries===void 0?ru:Number(t.maxEntries),o=t.futureToleranceMs===void 0?xo:Math.max(0,Number(t.futureToleranceMs)||0),c=n!==1/0&&Number.isFinite(n)&&Number.isFinite(r)?Math.max(0,n):1/0,l=e.records.filter(u=>(c===1/0||r-u.observedAt<=c)&&(!Number.isFinite(r)||u.observedAt<=r+o));if(s!==1/0&&Number.isFinite(s)){let u=Math.max(0,Math.floor(s));if(l.length>u){let d=new Map;l.forEach((h,f)=>{let g=JSON.stringify([h.appid,h.marketHashName,h.currencyId]);d.has(g)||d.set(g,[]),d.get(g).push({index:f,observedAt:h.observedAt})});let m=[...d.values()].map(h=>h.sort((f,g)=>g.observedAt-f.observedAt||g.index-f.index)).sort((h,f)=>f[0].observedAt-h[0].observedAt||f[0].index-h[0].index),p=new Set;for(let h=0;p.size=u)break;g[h]&&(p.add(g[h].index),f=!0)}if(!f)break}l=l.filter((h,f)=>p.has(f))}}return{...e,records:l}}function ou(e,t,r={}){if(!Array.isArray(t))throw new TypeError("Market history records must be an array.");let n=So(r),s=ko(e,r),o=[...s.records],i=new Map(o.map((c,l)=>[ds(c,n),l]));return t.forEach(c=>{let l=Co(c),u=ds(l,n);if(!l||u===null)throw new TypeError("A history record requires appid, marketHashName, currencyId, source, and observedAt.");let d=i.get(u);d===void 0?(i.set(u,o.length),o.push(l)):o[d].observedAt<=l.observedAt&&(o[d]=l)}),au({...s,records:o},r)}function iu(e){return typeof e=="function"?e:typeof GM_getValue=="function"?GM_getValue:null}function cu(e){return typeof e=="function"?e:typeof GM_setValue=="function"?GM_setValue:null}function lu(e,t={}){let r=t.storageKey||t.key||yo,n=cu(t.setValue);if(!n)return{ok:!1,envelope:null,history:null,storageKey:r,diagnostics:[Ee("gm-set-unavailable","GM_setValue is not available.")]};let s=JSON.stringify(e);try{n(r,s)}catch(o){return{ok:!1,envelope:e,history:e,raw:s,storageKey:r,diagnostics:[Ee("gm-write-failed","Failed to write market history.","error",{error:String(o?.message||o)})]}}return{ok:!0,envelope:e,history:e,raw:s,storageKey:r,diagnostics:[]}}function ms(e={}){let t=e.storageKey||e.key||yo,r=iu(e.getValue);if(!r)return{ok:!1,envelope:null,history:null,storageKey:t,diagnostics:[Ee("gm-get-unavailable","GM_getValue is not available.")],needsMigration:!1};let n;try{n=r(t,null)}catch(s){return{ok:!1,envelope:null,history:null,storageKey:t,diagnostics:[Ee("gm-read-failed","Failed to read market history.","error",{error:String(s?.message||s)})],needsMigration:!1}}return{...su(n,e),raw:n,storageKey:t}}function Io(e,t={}){if(!Array.isArray(e))throw new TypeError("Market history records must be an array.");let r=ms(t);if(!r.ok||!r.envelope||e.length===0)return{...r,saved:!1};let n=ou(r.envelope,e,t),s=lu(n,t);return{...s,saved:s.ok}}function Mo(e,t,r={}){let n=String(t?.appid??"753").trim(),s=Number(t?.currencyId??t?.currency);if(!n||!Number.isSafeInteger(s)||s<=0)return new Map;let o=r.now===void 0?Date.now():Number(r.now),i=r.ttlMs===void 0?vo:Number(r.ttlMs),c=r.futureToleranceMs===void 0?xo:Math.max(0,Number(r.futureToleranceMs)||0),l=i===1/0||!Number.isFinite(i)||!Number.isFinite(o)?-1/0:o-Math.max(0,i),u=Number.isFinite(o)?o+c:1/0,d=new Map,m=r.normalized===!0?e:ko(e,r);return(Array.isArray(m?.records)?m.records:[]).forEach(p=>{p.appid!==n||p.currencyId!==s||p.observedAtu||(d.has(p.marketHashName)||d.set(p.marketHashName,[]),d.get(p.marketHashName).push(p))}),d.forEach(p=>p.sort((h,f)=>h.observedAt-f.observedAt)),d}function Eo(e,t=!1){let r=(Array.isArray(e)?e:[]).filter(n=>n?.source==="priceoverview"||n?.source==="listing-page");return t?r:r.sort((n,s)=>Number(n.observedAt)-Number(s.observedAt))}function No(e,t={}){let r=Eo(e,t.sorted===!0),n=r.filter(p=>Number.isFinite(Number(p.lowestSellMinor))&&Number(p.lowestSellMinor)>0),s=r.filter(p=>p.volume!==null&&p.volume!==void 0&&p.volume!==""&&Number.isFinite(Number(p.volume))&&Number(p.volume)>=0),o=r.at(-1)||null,c=o&&Number.isFinite(Number(o.lowestSellMinor))&&Number(o.lowestSellMinor)>0?o:null,l=c&&n.filter(p=>p!==c).at(-1)||null,u=c?Number(c.lowestSellMinor):null,d=l?Number(l.lowestSellMinor):null,m=u!==null&&d!==null?u-d:null;return{currentMinor:u,previousMinor:d,changeMinor:m,percentChange:m!==null&&d>0?m/d*100:null,volume24h:s.length>0?Number(s.at(-1).volume):null,observedAt:o?.observedAt??null,priceSampleCount:n.length}}function Ao(e,t={}){let r=t.from===void 0?-1/0:Number(t.from),n=t.maxPoints===void 0?96:Number(t.maxPoints),s=Number.isFinite(n)?Math.max(1,Math.floor(n)):96,o=Eo(e,t.sorted===!0).filter(c=>Number(c.observedAt)>=r&&Number.isFinite(Number(c.lowestSellMinor))&&Number(c.lowestSellMinor)>0).map(c=>({observedAt:Number(c.observedAt),value:Number(c.lowestSellMinor)}));if(o.length<=s)return o;if(s===1)return[o.at(-1)];let i=[];for(let c=0;ce?.[t]!==null&&e?.[t]!==void 0)}function mu(e){return e?.diagnostics?.some(t=>t.code!=="gm-get-unavailable"&&t.code!=="gm-set-unavailable")}function Ro(e,t){mu(t)&&console.warn(`[STCH] ${e} update skipped:`,t.diagnostics)}function _o(){return{ok:!0,saved:!1,skipped:!0,diagnostics:[]}}function ee(e,t={}){let r=(Array.isArray(e)?e:[e]).filter(Boolean);if(r.length===0){let i=_o();return{ok:!0,saved:!1,cache:{...i},history:i}}let n=ho(r,t.cacheOptions);Ro("Market cache",n);let s=r.filter(du),o=s.length>0?Io(s,t.historyOptions):_o();return Ro("Market history",o),{ok:!!n?.ok&&!!o?.ok,saved:!!n?.saved||!!o?.saved,cache:n,history:o}}var $o=Object.freeze({isolationMinimumGapRatio:.03,isolationGapMultiplier:2,isolationLookaheadLevels:4,isolationMaxTopShare:.25,maxDistanceRatio:.04,quantityRatioThreshold:3,precedingWindow:3,minimumPrecedingCount:2,clusterGapMinor:1});function Be(e){let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}function ps(e,t,r){let n=Be(t),s=Be(r);n===null||s===null||e.set(n,(e.get(n)||0)+s)}function Po(e,t={}){if(!Array.isArray(e)||e.length===0||e.length%2!==0)return null;let r=[],n=1/0;for(let o=0;o=n)return null;r.push({priceMinor:i,quantity:c}),n=i}let s=t.expectedBestPriceMinor===void 0?null:Be(t.expectedBestPriceMinor);return t.expectedBestPriceMinor!==void 0&&(s===null||r[0].priceMinor!==s)?null:r}function pu(e){let t=new Map;if(!Array.isArray(e))return[];if(e.every(r=>!Array.isArray(r)&&typeof r!="object"))for(let r=0;r+1{Array.isArray(r)?ps(t,r[0],r[1]):r&&typeof r=="object"&&ps(t,r.priceMinor??r.priceCents??r.price,r.quantity??r.count)});return[...t.entries()].map(([r,n])=>({priceMinor:r,quantity:n})).sort((r,n)=>n.priceMinor-r.priceMinor)}function Oo(e){let t=e.map(Number).filter(Number.isFinite).sort((n,s)=>n-s);if(t.length===0)return null;let r=Math.floor(t.length/2);return t.length%2===0?(t[r-1]+t[r])/2:t[r]}function fu(e,t,r,n){let s=Math.max(0,t-r),o=e.slice(s,t).map(i=>i.quantity);return o.length>=n?Oo(o):null}function hu(e,t={}){let r={...$o,...t},n=pu(e),s=n[0]?.priceMinor??null,o={classification:"normal",originalBestPriceMinor:s,effectiveBestPriceMinor:s,isolatedLevels:[],levels:n,effectiveLevels:n};if(n.length<3||s===null)return o;let i=Be(r.minimumPriceMinor);if(i!==null&&s<=i)return{...o,minimumPriceProtected:!0,minimumPriceMinor:i};let c=Math.max(2,Math.floor(Number(r.isolationLookaheadLevels)||2)),l=n.slice(0,c+1),u=[];for(let N=1;N+1N>0));if(!Number.isFinite(d)||d<=0)return o;let m=n[0],p=n[1],h=m.priceMinor-p.priceMinor,f=h/p.priceMinor,g=h/d,y=l.reduce((N,A)=>N+A.quantity,0),b=y>0?m.quantity/y:1,S=Math.max(0,Number(r.isolationMinimumGapRatio)||0),M=Math.max(1,Number(r.isolationGapMultiplier)||1),E=Math.min(1,Math.max(0,Number(r.isolationMaxTopShare)||0));if(!(f>=S&&g>=M&&b<=E))return{...o,topGapMinor:h,topGapRatio:f,topGapVsTypical:g,topQuantityShare:b};let I=n.slice(1);return{classification:"isolated-high",originalBestPriceMinor:s,effectiveBestPriceMinor:I[0]?.priceMinor??null,isolatedLevels:[{...m,gapToNextMinor:h,gapRatio:f,gapVsTypical:g,localQuantityShare:b}],levels:n,effectiveLevels:I,topGapMinor:h,topGapRatio:f,topGapVsTypical:g,topQuantityShare:b}}function gu(e,t){let r=[];return e.forEach(n=>{let s=r.at(-1);if(s&&s.bottomPriceMinor-n.priceMinor<=t){s.walls.push(n),s.bottomPriceMinor=n.priceMinor,s.totalQuantity+=n.quantity,s.maxQuantityRatio=Math.max(s.maxQuantityRatio,n.quantityRatio);return}r.push({topPriceMinor:n.priceMinor,bottomPriceMinor:n.priceMinor,distanceFromBestMinor:n.distanceFromBestMinor,totalQuantity:n.quantity,maxQuantityRatio:n.quantityRatio,walls:[n]})}),r}function bu(e,t={}){let r={...$o,...t},n=hu(e,r),s=n.effectiveLevels,i=Be(t.bestPriceMinor)??n.originalBestPriceMinor??null,c=n.effectiveBestPriceMinor;if(s.length===0||c===null)return{classification:"balanced",bestPriceMinor:c,originalBestPriceMinor:i,levels:s,walls:[],clusters:[],nearestCluster:null,isolation:n};let l=Math.max(0,Number(r.maxDistanceRatio)||0),u=Math.max(1,Math.floor(c*l)),d=Math.max(1,Number(r.quantityRatioThreshold)||1),m=Math.max(1,Math.floor(Number(r.precedingWindow)||1)),p=Math.max(1,Math.floor(Number(r.minimumPrecedingCount)||1)),h=Math.max(0,Math.floor(Number(r.clusterGapMinor)||0)),f=[];s.forEach((M,E)=>{let x=c-M.priceMinor;if(x<0||x>u)return;let I=fu(s,E,m,p);if(!Number.isFinite(I)||I<=0)return;let N=M.quantity/I;N0?"near-wall":"balanced",bestPriceMinor:c,originalBestPriceMinor:i,maxDistanceMinor:u,levels:s,walls:b,clusters:S,nearestCluster:y,wallCandidates:f,isolation:n}}var yu=Object.freeze(["conservative","balanced","aggressive"]),vu=Object.freeze({conservative:Object.freeze({wallAnchor:"bottom",wallOffsetMinor:0,noWallOffsetMinor:-2}),balanced:Object.freeze({wallAnchor:"top",wallOffsetMinor:0,noWallOffsetMinor:-1}),aggressive:Object.freeze({wallAnchor:"top",wallOffsetMinor:1,noWallOffsetMinor:1})});function xu(e,t){let r=vu[e],n=t&&typeof t=="object"?t:{},s=(o,i)=>Number.isSafeInteger(Number(o))?Number(o):i;return{wallAnchor:["top","bottom"].includes(n.wallAnchor)?n.wallAnchor:r.wallAnchor,wallOffsetMinor:s(n.wallOffsetMinor,r.wallOffsetMinor),noWallOffsetMinor:s(n.noWallOffsetMinor,r.noWallOffsetMinor)}}function un(e,t={}){let r=yu.includes(t.strategy)?t.strategy:"balanced",n=Be(e?.highestBuyMinor??e?.amtMaxBuyOrder);if(n===null)return null;let s=Be(t.minimumPriceMinor)??1,o=bu(e?.buyLevels??e?.rgCompactBuyOrders??[],{...t.wallOptions,bestPriceMinor:n,minimumPriceMinor:s}),i=o.nearestCluster,c=o.bestPriceMinor??n,l=xu(r,t.strategyRule),u=i?l.wallAnchor==="bottom"?i.bottomPriceMinor:i.topPriceMinor:null,d=i?u+l.wallOffsetMinor:c+l.noWallOffsetMinor,m=Number.isSafeInteger(Number(t.adjustmentMinor))?Number(t.adjustmentMinor):0,p=Be(e?.lowestSellMinor??e?.amtMinSellOrder);if(p!==null&&p<=s)return null;let h=p===null?null:p-1,f=d+m,g=Math.max(s,f);return h!==null&&(g=Math.min(g,h)),{strategy:r,strategyRule:l,classification:o.classification,highestBuyMinor:n,effectiveHighestBuyMinor:c,wallReferencePriceMinor:u,strategyBasePriceMinor:d,adjustmentMinor:m,adjustedPriceMinor:f,minimumPriceMinor:s,lowestSellMinor:p,sellGuardMinor:h,finalPriceMinor:g,wasMinimumClamped:g>f,wasSellGuardClamped:h!==null&&g===h&&f>h,detection:o}}var Bo=1440*60,Su=7200;function Sr(e,t=753){return`https://steamcommunity.com/market/listings/${t}/${encodeURIComponent(e)}?l=english`}function Ue(e){if(e==null||e==="")return null;let t=Number(String(e).replace(/[\s,.'’]/g,""));return Number.isSafeInteger(t)&&t>=0?t:null}function dn(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)&&t>=0?t:null}function Lo(e){let t=String(e||"").match(/window\.SSR\.renderContext=JSON\.parse\(("(?:\\.|[^"\\])*")\);/);if(!t)return[];try{let r=JSON.parse(JSON.parse(t[1])),n=JSON.parse(r?.queryData||"{}");return Array.isArray(n?.queries)?n.queries:[]}catch{return[]}}function Cu(e){let t=String(e?.icon_url_large||e?.icon_url||"").trim();return t?/^https?:\/\//i.test(t)?t:`https://community.fastly.steamstatic.com/economy/image/${t}`:""}function mn(e,t,r,n){let s=e.find(i=>{let c=i?.queryKey;return Array.isArray(c)&&c[0]==="market"&&c[1]===r&&String(c[2])==="753"&&c[3]===t});if(s)return s;let o=e.filter(i=>{let c=i?.queryKey;return(!Array.isArray(c)||c.length===0)&&n(i?.state?.data)});return o.length===1?o[0]:null}function wu(e,t,r=Date.now()){let s=mn(e,t,"pricehistory",p=>p&&Array.isArray(p.prices))?.state?.data;if(!s)return null;let o=[],i=0;for(let p of s.prices){let h={time:Ue(p?.time),price:dn(p?.price_median),purchases:Ue(p?.purchases)};h.time===null||h.price===null||h.price<=0||h.purchases===null||h.purchases<=0||(o.push(h),i=Math.max(i,h.time))}let c=Math.floor(Number(r)/1e3),l=Math.max(i-Bo,c-Bo-Su),u=o.filter(p=>p.time>l),d=u.reduce((p,h)=>p+h.purchases,0),m=null;if(d>0){let p=0,h=d/2;for(let f of u.sort((g,y)=>g.price-y.price))if(p+=f.purchases,p>=h){m=f.price;break}}return{historyCurrency:Ue(s.ecurrency),medianPriceMajor:m,volume:d}}function To(e,t,r=!0){try{let s=mn(e,t,"orderbook",m=>m&&Object.prototype.hasOwnProperty.call(m,"amtMaxBuyOrder"))?.state?.data,o=dn(s?.amtMaxBuyOrder),i=dn(s?.amtMinSellOrder),c=dn(s?.eCurrency),u=mn(e,t,"description",m=>m&&(m.icon_url||m.icon_url_large)&&m.name)?.state?.data;if(!s&&!u)return null;let d=r?wu(e,t):null;return{highestBuyCents:o,lowestSellCents:i,currency:c,sellOrderCount:Ue(s?.cSellOrders??s?.sell_order_count),displayName:String(u?.name||"").trim(),imageUrl:Cu(u),...d||{}}}catch{return null}}function pn(e,t,r={}){return To(Lo(e),t,r.includeHistory!==!1)}function ku(e,t){let n=mn(e,t,"orderbook",u=>u&&Array.isArray(u.rgCompactBuyOrders))?.state?.data;if(!n)return null;let s=Ue(n.amtMaxBuyOrder),o=Ue(n.eCurrency);if(!s||!o)return null;let i=Po(n.rgCompactBuyOrders,{expectedBestPriceMinor:s});if(!i)return null;let c=Ue(n.cBuyOrders);if(c!==null&&i.reduce((u,d)=>u+d.quantity,0)!==c)return null;let l=Ue(n.amtMinSellOrder);return{currencyId:o,highestBuyMinor:s,lowestSellMinor:l&&l>0?l:null,buyOrderCount:c,sellOrderCount:Ue(n.cSellOrders),buyLevels:i}}function Fo(e,t,r={}){let n=Lo(e);return{snapshot:To(n,t,r.includeHistory!==!1),depth:ku(n,t)}}function Do(e){let r=(e?.getAttribute("href")||e?.href||"").match(/\/market\/listings\/753\/(.+?)(?:\?|#|$)/);if(!r)return"";try{return decodeURIComponent(r[1])}catch{return r[1]}}var ve=Object.freeze({PRICED:"priced",NO_PRICE:"no-price",ERROR:"error"}),j=Object.freeze({INVALID_INPUT:"invalid-input",CURRENCY:"currency",HTTP:"http",NETWORK:"network",PARSE:"parse",RESPONSE:"response",STOPPED:"stopped"}),zo=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);function Iu(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Mu(e){return e===!0||e===1||e==="1"}function ke(e,t={}){let r=Number(t.httpStatus);return{outcome:ve.ERROR,errorKind:e,errorMessage:String(t.errorMessage||"价格请求失败"),httpStatus:Number.isSafeInteger(r)&&r>0?r:null,record:null,currencyId:t.currencyId??null,observedAt:null}}function Ho(e,t){let r=Number(e?.status),n=String(e?.error||e?.message||e||"价格请求失败");return r===0||/\b(?:stopped|skipped)\b/i.test(n)?ke(j.STOPPED,{errorMessage:n,currencyId:t}):Number.isSafeInteger(r)&&r>0?ke(j.HTTP,{errorMessage:n,httpStatus:r,currencyId:t}):ke(j.NETWORK,{errorMessage:n,currencyId:t})}function Eu(e){return["lowest_price","median_price"].some(t=>zo(e,t)&&String(e[t]??"").trim()!=="")}function Ie(e){return e?.outcome===ve.PRICED}function je(e){return e?.outcome===ve.NO_PRICE}function Cr(e){return e?.outcome===ve.ERROR}function Ut(e,t,r=null){let n=e&&typeof e=="object"?e:{},s=Ie(t)||je(t)||Cr(t)?t:ke(j.PARSE,{errorMessage:"未知查价结果",currencyId:r});return n.lowestCents=null,n.medianCents=null,n.volume=null,n.priceOutcome=s.outcome,n.currencyId=s.currencyId??r,n.observedAt=s.observedAt??null,n.marketRecord=s.record??null,delete n.priceErrorKind,delete n.priceErrorStatus,Ie(s)?(n.lowestCents=s.lowestSellCents,n.medianCents=s.medianCents,n.volume=s.volume,n.priceSource=s.priceSource):je(s)?(n.volume=s.record?.volume??null,n.priceSource="none"):(n.priceSource="failed",n.priceErrorKind=s.errorKind,n.priceErrorStatus=s.httpStatus),s}function Nu(e={}){return e.currencyContext?ze(e.currencyContext):e.currencyId!=null?xt(e.currencyId):he()||xt(Z.CNY)}function qo(e,t,r,n,s=ls(e)){if(!e||!s)return ke(j.PARSE,{errorMessage:"价格响应无法规范化",currencyId:t.currencyId});if(r.persistMarketCache!==!1){let o=ee(e);typeof r.onPersist=="function"&&r.onPersist(o)}return s.noPriceData?{outcome:ve.NO_PRICE,noPriceData:!0,volume:s.volume||0,record:e,currencyId:t.currencyId,observedAt:n}:{outcome:ve.PRICED,...s,record:e,currencyId:t.currencyId,observedAt:n}}async function me(e,t,r={}){let n=String(e||"").trim();if(!n||typeof t?.fetch!="function")return ke(j.INVALID_INPUT,{errorMessage:n?"价格请求队列不可用":"缺少 market_hash_name"});let s=null;try{if(s=Nu(r),!s?.currencyId)return ke(j.CURRENCY,{errorMessage:"无法确认市场币种"});let o=String(r.appid||753);if(r.preferListing===!0)try{let h=Sr(n,o),f=await t.fetch(h,{requestPolicy:"default"}),g=pn(f?.text||"",n,{includeHistory:r.requireMedian===!0||r.requireVolume===!0}),y=Date.now();g&&typeof r.onMetadata=="function"&&r.onMetadata({displayName:g.displayName||"",imageUrl:g.imageUrl||"",sellOrderCount:g.sellOrderCount,observedAt:y});let b=g&&(g.currency||g.historyCurrency)?oo(g,{appid:o,marketHashName:n,currencyId:s.currencyId,currencyCode:s.code,decimalDigits:s.decimalDigits,observedAt:y}):null,S=b?.currencyId===s.currencyId&&b?.currencyCode===s.code,M=(!r.requireMedian||b?.medianMinor!==null)&&(!r.requireVolume||b?.volume!==null);if(b&&S&&M)return qo(b,s,r,y)}catch(h){let f=Ho(h,s.currencyId);if(f.errorKind===j.STOPPED)return f}let c=`https://steamcommunity.com/market/priceoverview/?${new URLSearchParams({appid:o,currency:String(s.currencyId),market_hash_name:n}).toString()}`,l=await t.fetch(c,{...r.fetchOptions||{},requestPolicy:r.requestPolicy||"priceoverview"}),u=Number(l?.status);if(Number.isSafeInteger(u)&&u>0&&(u<200||u>=300))return ke(j.HTTP,{errorMessage:`价格接口返回 HTTP ${u}`,httpStatus:u,currencyId:s.currencyId});if(!Iu(l?.data))return ke(j.PARSE,{errorMessage:"价格接口未返回有效 JSON",currencyId:s.currencyId});if(!zo(l.data,"success"))return ke(j.PARSE,{errorMessage:"价格响应缺少 success 字段",currencyId:s.currencyId});if(!Mu(l.data.success))return ke(j.RESPONSE,{errorMessage:"Steam 返回查价失败",currencyId:s.currencyId});let d=Date.now(),m=ao(l?.data,{appid:o,marketHashName:n,currencyId:s.currencyId,currencyCode:s.code,decimalDigits:s.decimalDigits,observedAt:d}),p=ls(m);return!m||!p?ke(j.PARSE,{errorMessage:"价格响应无法规范化",currencyId:s.currencyId}):p.noPriceData&&Eu(l.data)?ke(j.PARSE,{errorMessage:"价格字段无法解析",currencyId:s.currencyId}):qo(m,s,r,d,p)}catch(o){return Ho(o,s?.currencyId??null)}}function Go(e,t,r){let n=e.length,s=Oa[n];if(!s||t<=n)return null;let o=e.map(d=>d.lowestCents);if(e.some(d=>d.volume<=0)||o.some(d=>!Number.isFinite(d)||d<=0))return null;let i=Math.min(...o),c=Math.max(...o);if(c/i>=2)return null;let u=(i+s.highWeight*(c-i))*s.factor;return{sampleCount:n,minPrice:i,maxPrice:c,predictedCents:Math.ceil(r+(t-n)*u)}}function U(e){if(e?.parallelOrderPricingEnabled!==!0)return 1;let t=Math.floor(Number(e.parallelOrderPricingConcurrency));return Number.isFinite(t)?Math.min(20,Math.max(1,t)):4}function jt(e){if(e?.parallelOtherRequestsEnabled===!1)return 1;let t=Math.floor(Number(e?.parallelOtherRequestsConcurrency));return Number.isFinite(t)?Math.min(20,Math.max(1,t)):8}function oe(e,t){let r=Math.max(1,Math.floor(Number(e))||1),n=Array.from({length:r},(o,i)=>({index:i,queue:null,pending:0})),s=!1;return{get stopped(){return s},fetch(o,i){if(s)return Promise.reject({status:0,error:"stopped"});let c=null;for(let l of n)l.queue?.stopped||(!c||l.pending{c.pending--})}catch(l){return c.pending--,Promise.reject(l)}},stop(){s=!0,n.forEach(o=>o.queue?.stop())}}}async function Y(e,t,r){let n=0,s=async()=>{for(;ns()))}function te(e){return`${e.appid}_${e.isFoil?1:0}`}function rt(){return a.results.filter(e=>a.selectedResults.has(te(e)))}function nt(){return a.orderResults.filter(e=>a.selectedOrderResults.has(te(e)))}async function fn(e,t){let r=Q();if(!r)throw new Error("未找到 Profile URL");let n=await t.fetch(Ze(r,e.appid,e,{language:"english"}));if(!n?.text?.includes("badge_card_set_card"))throw new Error("未找到卡牌套组");let s=Ct(n.text,e.appid,e.isFoil);s.appid=e.appid,s.isFoil=e.isFoil,s.targetLevel=ae(s),s.gameName=e.gameName||s.gameName||"",s.cardPrices=[],s.currencyId=a.currencyContext?.currencyId||a.cfg.currencyId||23,s.cheapestSetCostCents=0,s.fullSetCostCents=0,s.level5CostCents=0;let o=0,i=0,c=0,l=1/0,u=Math.max(0,s.targetLevel-s.level),d=[],m=[],p=new Array(s.cards.length),h=0;try{await Y(s.cards,U(a.cfg),async(f,g)=>{if(!f.marketHashName){Ut(f,{outcome:ve.ERROR,errorKind:j.INVALID_INPUT,errorMessage:"缺少 market_hash_name",httpStatus:null,record:null,currencyId:s.currencyId,observedAt:null},s.currencyId),h++;return}let y=await me(f.marketHashName,t,{preferListing:!0,requireMedian:!0,requireVolume:!0,persistMarketCache:!1});y?.record&&m.push(y.record);let b=Ut(f,y,s.currencyId);if(b.outcome===ve.ERROR){h++;return}if(b.outcome===ve.NO_PRICE){d.push(f);return}l=Math.min(l,y.volume),y.estimated&&(s.hasEstimated=!0,s.hasMedianFallback=!0),p[g]={name:f.name,lowestCents:y.lowestSellCents,medianCents:y.medianCents,volume:y.volume,marketHashName:f.marketHashName,priceSource:y.priceSource,currencyId:y.currencyId,observedAt:y.observedAt};let S=Math.max(0,1-f.owned),M=Math.max(0,u-f.owned);o+=y.lowestSellCents*S,i+=y.lowestSellCents,c+=M>0?y.lowestSellCents+(M-1)*Math.max(y.lowestSellCents,y.medianCents):0})}finally{ee(m)}return s.cardPrices=p.filter(Boolean),s.noPriceDataCount=d.length,s.failedPriceCount=h,s.hasIncompletePricing=d.length+h>0,s.cheapestSetCostCents=s.hasIncompletePricing?null:o,s.fullSetCostCents=s.hasIncompletePricing?null:i,s.level5CostCents=s.hasIncompletePricing?null:c,s.minVolume=l===1/0?0:l,s}var fs=23,bs=new WeakSet;function wr(e,t=fs){let r=Number(e);if(Number.isInteger(r)&&r>0)return r;let n=Number(t);return Number.isInteger(n)&&n>0?n:fs}function Vt(){return wr(a?.currencyContext?.id??a?.currencyContext?.currencyId??a?.cfg?.currencyId,O.currencyId)}function st(e=Date.now()){return{schemaVersion:2,updatedAt:Number(e)||Date.now(),partitions:{}}}function kr(e,t=Date.now(),r=null){if(!e?.appid)return null;let n=JSON.parse(JSON.stringify(e));n.appid=String(n.appid).trim(),n.isFoil=!!n.isFoil,n.targetLevel=ae(n),n.cachedAt=Number(n.cachedAt||t)||t,n.currencyId=wr(n.currencyId,r??Vt()),n.cards=Array.isArray(n.cards)?n.cards:[],n.cardPrices=Array.isArray(n.cardPrices)?n.cardPrices:[],n.hasIncompletePricing=n.hasIncompletePricing===!0,n.cheapestSetCostCents=n.hasIncompletePricing?null:Number(n.cheapestSetCostCents)||0,n.fullSetCostCents=n.hasIncompletePricing?null:Number(n.fullSetCostCents)||0,n.level5CostCents=n.hasIncompletePricing?null:Number(n.level5CostCents)||0;let s=xt(n.currencyId);return n.currencyCode=n.currencyCode||s.code,n.cheapestSetFormatted=n.hasIncompletePricing?"-":zt(n.cheapestSetCostCents,s),n.fullSetFormatted=n.hasIncompletePricing?"-":zt(n.fullSetCostCents,s),n.level5Formatted=n.hasIncompletePricing?"-":zt(n.level5CostCents,s),n.cheapestSetCNY=n.hasIncompletePricing?"-":n.cheapestSetCNY||an(n.cheapestSetCostCents),n.fullSetCNY=n.hasIncompletePricing?"-":n.fullSetCNY||an(n.fullSetCostCents),n.level5CNY=n.hasIncompletePricing?"-":n.level5CNY||an(n.level5CostCents),bs.add(n),n.appid?n:null}function hs(e,t,r=Date.now(),n=!1){let s=Array.isArray(e)?e:e?.items;return{currencyId:t,updatedAt:Number(e?.updatedAt)||r,items:(Array.isArray(s)?s:[]).map(o=>{let c=n&&bs.has(o)&&o.currencyId===t?o:kr(o,o?.cachedAt||r,t);return c&&(c.currencyId=t),c}).filter(Boolean)}}function Uo(e,t,r,n,s=!1){let o=wr(t);return{schemaVersion:2,updatedAt:n,partitions:{...e.partitions,[String(o)]:hs({items:r,updatedAt:n},o,n,s)}}}function Au(e,t={}){let r=Number(t.now)||Date.now(),n=e;try{typeof n=="string"&&(n=JSON.parse(n||"[]"))}catch(o){return{envelope:st(r),migrated:!1,corrupt:!0,error:o,raw:e}}if(Array.isArray(n)){let o=st(r),i=fs;return o.partitions[String(i)]=hs(n,i,r),{envelope:o,migrated:!0,corrupt:!1,error:null,raw:e}}if(!n||typeof n!="object"||Array.isArray(n.partitions))return{envelope:st(r),migrated:!1,corrupt:!0,error:new Error("Invalid order cache envelope"),raw:e};if(Number(n.schemaVersion)!==2)return{envelope:st(r),migrated:!1,corrupt:!0,error:new Error(`Unsupported order cache schema: ${n.schemaVersion}`),raw:e};let s=st(n.updatedAt||r);for(let[o,i]of Object.entries(n.partitions||{})){let c=Number(i?.currencyId??o);!Number.isInteger(c)||c<=0||(s.partitions[String(c)]=hs(i,c,r))}return{envelope:s,migrated:!1,corrupt:!1,error:null,raw:e}}function ys(e={}){let t=GM_getValue(Xr,"[]"),r=Au(t);return r.migrated&&e.persistMigration!==!1&&GM_setValue(Xr,JSON.stringify(r.envelope)),r}function vs(e){GM_setValue(Xr,JSON.stringify(e))}function Ru(){let e=Number(a?.cfg?.orderCacheDays??O.orderCacheDays);return Number.isFinite(e)?Math.max(0,Math.floor(e)):O.orderCacheDays}function Ir(e){let t=Number(e)||Date.now();return Math.max(0,Math.floor((Date.now()-t)/864e5))}function jo(e){return Ir(e?.cachedAt)<=Ru()}function hn(e=Vt()){try{let t=ys({persistMigration:!0});if(t.corrupt)return console.warn("[STCH] Order cache load failed; original value was preserved:",t.error),[];let r=wr(e),s=t.envelope.partitions[String(r)]?.items||[],o=s.filter(jo);return o.length!==s.length&&vs(Uo(t.envelope,r,o,Date.now(),!0)),o}catch(t){return console.warn("[STCH] Order cache load failed:",t),[]}}function It(e=Vt()){let t=Date.now(),r;try{r=ys({persistMigration:!1})}catch(o){r={corrupt:!0,raw:null,envelope:st(t),error:o}}let n=r.corrupt?st(t):r.envelope,s=Uo(n,e,a.orderResults,t,!0);vs(s)}function xs(){a.orderResults=[],a.selectedOrderResults=new Set,a.pendingOrderQuantities=new Map,a.highestBuyPrices=new Map,vs(st())}function Le(e=!1){let t=a.orderResults.length;if(a.orderResults=a.orderResults.map(r=>bs.has(r)?r:kr(r,r?.cachedAt,Vt())).filter(Boolean).filter(jo),e&&a.orderResults.length!==t){It();let r=new Set(a.orderResults.map(te));a.selectedOrderResults.forEach(n=>{r.has(n)||a.selectedOrderResults.delete(n)})}return t-a.orderResults.length}function gn(e){Le(!0);let t=te(e);return a.orderResults.find(r=>te(r)===t)||null}function Kt(e,t={}){let r=Vt(),n=kr(e,t.cachedAt||Date.now(),r);if(!n)return null;n.cachedAt=t.cachedAt||Date.now(),n.currencyId=r,Le(!1);let s=te(n),o=a.orderResults.findIndex(i=>te(i)===s);return o>=0?a.orderResults[o]=n:a.orderResults.push(n),t.select&&a.selectedOrderResults.add(s),t.persist!==!1&&It(r),n}function Vo(e,t={}){let r=a.orderResults.length;a.orderResults=a.orderResults.filter(n=>te(n)!==e),a.selectedOrderResults.delete(e),a.orderResults.length!==r&&t.persist!==!1&&It()}function Ko(e=Vt()){try{let t=ys({persistMigration:!0});if(t.corrupt)return[];let r=wr(e);return t.envelope.partitions[String(r)]?.items||[]}catch{return[]}}var Wo="stch_item_collection",Qo=1,Yo=new Set(["card","background","emoticon"]);function Ve(e,t=500){return String(e||"").trim().slice(0,t)}function Jo(e,t=e?.category){let r=Yo.has(t)?t:"",n=Ve(e?.appid,20)||"0",s=Ve(e?.marketHashName),o=Ve(e?.descriptionKey,100);return!r||!s&&!o?"":JSON.stringify([r,n,s?"market":"class",s||o])}function Xo(e,t=Date.now()){let n={category:Yo.has(e?.category)?e.category:"",appid:Ve(e?.appid,20),marketHashName:Ve(e?.marketHashName),descriptionKey:Ve(e?.descriptionKey,100),itemName:Ve(e?.itemName||e?.cardName||e?.name),gameName:Ve(e?.gameName),imageUrl:Ve(e?.imageUrl,1e3),addedAt:Number.isFinite(Number(e?.addedAt))&&Number(e.addedAt)>0?Math.floor(Number(e.addedAt)):t};return n.key=Jo(n),n.key?n:null}function _u(e){if(e==null||e==="")return{ok:!0,items:[],migrated:!1};try{let t=typeof e=="string"?JSON.parse(e):e;if(!t||typeof t!="object"||t.schemaVersion!==Qo||!Array.isArray(t.items))return{ok:!1,items:[],error:"收藏数据格式不受支持"};let r=[],n=new Set;for(let s of t.items){let o=Xo(s);!o||n.has(o.key)||(n.add(o.key),r.push(o))}return{ok:!0,items:r,migrated:r.length!==t.items.length}}catch{return{ok:!1,items:[],error:"收藏数据已损坏"}}}function $u(e){return{schemaVersion:Qo,items:e.map(({key:t,...r})=>r)}}function Ss(e){GM_setValue(Wo,JSON.stringify($u(e)))}function Zo(){let e=_u(GM_getValue(Wo,null));if(a.itemCollectionHealthy=e.ok,a.itemCollectionItems=e.items,e.ok&&e.migrated)try{Ss(e.items)}catch{}return e.items}function at(){return a.itemCollectionHealthy!==!1}function Wt(e,t=e?.category){let r=Jo(e,t);return!!r&&(a.itemCollectionItems||[]).some(n=>n.key===r)}function ei(e){if(!at())return{ok:!1,added:0,error:"收藏数据已损坏,未写入新数据"};let t=a.itemCollectionItems||[],r=new Map(t.map(o=>[o.key,o])),n=0;for(let o of e||[]){let i=Xo(o);if(!i)continue;let c=r.get(i.key);c||n++,r.set(i.key,c?{...c,...i,addedAt:c.addedAt}:i)}let s=[...r.values()];try{return Ss(s),a.itemCollectionItems=s,{ok:!0,added:n,total:s.length}}catch(o){return{ok:!1,added:0,error:o?.message||"收藏保存失败"}}}function ti(e){if(!at())return{ok:!1,removed:0,error:"收藏数据已损坏,未执行删除"};let t=new Set(e||[]),r=a.itemCollectionItems||[],n=r.filter(o=>!t.has(o.key)),s=r.length-n.length;try{return Ss(n),a.itemCollectionItems=n,{ok:!0,removed:s,total:n.length}}catch(o){return{ok:!1,removed:0,error:o?.message||"收藏保存失败"}}}var Mr=null,Cs=0;function Pu(e){(Mr===null||e=6e4)&&(Mr=e,Cs=0)}function ws(e=Date.now()){return Pu(e),Cs<20?(Cs++,0):Math.max(0,6e4-(e-Mr))}var Te=Symbol("request-queue-cancelled"),ks=Object.freeze({name:"default",applyInterval:!1,retry429:!1}),Is=Object.freeze({name:"priceoverview",applyInterval:!0,retry429:!0});function Ke(){return{status:0,error:"stopped"}}function bn(...e){return e.find(t=>t!==void 0)}var G=class{constructor(t=330,r=null,n=null,s=null,o={}){this.interval=t,this.state=r,this.onStatus=n,this.onLog=s,this.queue=[],this.running=!1,this.cooling=!1,this.stopped=!1,this._consecutive429=0,this._429Warned=!1,this._currentJob=null,this._currentController=null,this._waiters=new Set;let i=o&&typeof o=="object"?o:{},c=i.timer||i.timers||i.clock||{},l=typeof c=="function"?{setTimeout:c}:c,u=i.setTimeout||l.setTimeout||globalThis.setTimeout,d=i.clearTimeout||l.clearTimeout||globalThis.clearTimeout,m=i.setTimeout?i:l.setTimeout?l:globalThis,p=i.clearTimeout?i:l.clearTimeout?l:globalThis;this._setTimeout=(...h)=>u.apply(m,h),this._clearTimeout=(...h)=>d.apply(p,h),this._now=()=>{let h=i.now??l.now??Date.now,f=i.now!=null?i:l.now!=null?l:Date;return Number(typeof h=="function"?h.call(f):h)},this._fetchImpl=i.fetch||i.fetchImpl||null,this._stopPredicate=i.stopPredicate||i.shouldStop||null,this._AbortController=Object.prototype.hasOwnProperty.call(i,"AbortController")?i.AbortController:globalThis.AbortController||null}async fetch(t,r={}){if(this.stopped)throw Ke();if(this._externalStopRequested())throw this.stop(),Ke();let{policy:n,requestPolicy:s,endpointPolicy:o,...i}=r||{},c=bn(n,s,o),l=this._resolvePolicy(t,c);return new Promise((u,d)=>{if(this.stopped){d(Ke());return}this.queue.push({url:t,fetchOptions:i,policy:l,resolve:u,reject:d,settled:!1,cancelActive:null}),this._run()})}_cfgNumber(t,r,n=0){let s=Number(this.state?.cfg?.[t]);return Number.isFinite(s)?Math.max(n,s):r}_priceInterval(){return this._cfgNumber("requestInterval",this.interval,0)}_urlText(t){return typeof t=="string"?t:t&&typeof t.url=="string"?t.url:String(t||"")}_detectedPolicy(t){return/\/market\/priceoverview(?:\/|[?#]|$)/i.test(this._urlText(t))?Is:ks}_namedPolicy(t,r){let n=String(t||"").trim().toLowerCase();if(!n||n==="auto")return r;if(n==="priceoverview"||n==="price-overview")return Is;if(n==="default"||n==="ordinary"||n==="normal"||n==="none")return ks;throw new TypeError(`Unknown request policy: ${t}`)}_resolvePolicy(t,r){let n=this._detectedPolicy(t);if(r==null||r==="auto")return n;if(typeof r=="string")return this._namedPolicy(r,n);if(typeof r=="boolean")return r?Is:ks;if(typeof r!="object")throw new TypeError("Request policy must be a policy name or object");let s=bn(r.base,r.name,r.type),o=s==null?n:this._namedPolicy(s,n),i=bn(r.applyInterval,r.interval,r.pace),c=bn(r.retry429,r.retryOn429),l=typeof i=="number"&&Number.isFinite(i)?Math.max(0,i):null;return{name:o.name,applyInterval:i===void 0?o.applyInterval:l!=null||!!i,retry429:c===void 0?o.retry429:!!c,intervalMs:l??this._optionalNumber(r.intervalMs,0)}}_optionalNumber(t,r,n=!1){if(t==null||t==="")return null;let s=Number(t);if(!Number.isFinite(s))return null;let o=Math.max(r,s);return n?Math.floor(o):o}_policyInterval(t){return t.intervalMs==null?this._priceInterval():t.intervalMs}_defaultStateStopRequested(){return!!(this.state?.stopRequested||this.state?.craftStopRequested||this.state?.surplusStopRequested||this.state?.grindStopRequested)}_externalStopRequested(){return this._stopPredicate?!!this._stopPredicate(this.state,this):this._defaultStateStopRequested()}_sleepShouldStop(){return this.stopped||this.state?.skipCurrent||this._externalStopRequested()}_wait(t){let r=Math.max(0,Number(t)||0);return r===0?Promise.resolve(!this._sleepShouldStop()):new Promise((n,s)=>{let o={id:null,settled:!1,finish:i=>{if(!o.settled){if(o.settled=!0,this._waiters.delete(o),!i&&o.id!=null)try{this._clearTimeout(o.id)}catch{}n(i)}}};this._waiters.add(o);try{o.id=this._setTimeout(()=>o.finish(!0),r)}catch(i){this._waiters.delete(o),o.settled=!0,s(i);return}this._sleepShouldStop()&&o.finish(!1)})}_interruptWaits(){for(let t of[...this._waiters])t.finish(!1)}async _sleep(t){let r=this._now()+Math.max(0,Number(t)||0);for(;this._now(){try{n.abort(o.reason)}catch{try{n.abort()}catch{}}};o.aborted?i():typeof o.addEventListener=="function"&&(o.addEventListener("abort",i,{once:!0}),s=()=>{o.removeEventListener?.("abort",i)})}r.signal=n.signal}catch{n=null}return this._currentController=n,{options:r,controller:n,cleanup:()=>{s?.(),this._currentController===n&&(this._currentController=null)}}}async _awaitActive(t,r){let n=Promise.resolve().then(()=>{if(this.stopped)throw Te;return r()}).then(o=>({value:o}),o=>({error:o})),s=await Promise.race([n,t.cancelPromise]);if(s===Te)throw Te;if(Object.prototype.hasOwnProperty.call(s,"error"))throw s.error;return s.value}async _attempt(t){let r=this._now(),n=!1,s;t.cancelPromise=new Promise(i=>{s=()=>i(Te)}),t.cancelActive=s,this._currentJob=t;let o=this._prepareFetch(t);try{if(this.stopped)throw Te;if(t.policy.name==="priceoverview"){let u=ws(this._now());for(;u>0;){if(!await this._sleepWithCountdown(u,m=>`主动冷却中 (${m}s)`))throw Te;u=ws(this._now())}}n=!0;let i=await this._awaitActive(t,()=>this._callFetch(t.url,o.options));if(this.stopped)throw Te;if(i.status===429&&t.policy.retry429)return this._consecutive429++,this._consecutive429>=3&&!this._429Warned&&this.onLog&&(this._429Warned=!0,this.onLog("Steam 可能已临时限制此 IP 访问价格 API;建议等待至少半小时或者更换 IP 后再继续","warn-ip")),await this._sleepWithCountdown(6e4,d=>`429 限流冷却中 (第${this._consecutive429}次, ${d}s)`)?this.state?.skipCurrent?(this._rejectJob(t,{status:429,error:"skipped by user"}),{attempted:!1,retry:!1,requestStartedAt:r}):this.stopped||this._externalStopRequested()?(this.stopped||this.stop(),this._rejectJob(t,Ke()),{attempted:!1,retry:!1,requestStartedAt:r}):{attempted:!1,retry:!0,requestStartedAt:r}:(this.state?.skipCurrent?this._rejectJob(t,{status:429,error:"skipped by user"}):(this.stopped||this.stop(),this._rejectJob(t,Ke())),{attempted:!1,retry:!1,requestStartedAt:r});if(t.policy.retry429&&(this._consecutive429=0),t.policy.name==="priceoverview"&&this.onStatus&&!this._sleepShouldStop()&&this.onStatus("扫描卡牌价格中",!0),i.status>=500&&t.policy.applyInterval&&(await this._sleep(this._policyInterval(t.policy)*3),this._externalStopRequested()&&!this.stopped&&this.stop(),this.stopped))throw Te;let c=await this._awaitActive(t,()=>i.text());if(this.stopped)throw Te;let l=null;try{l=JSON.parse(c)}catch{}return i.ok?this._resolveJob(t,{status:i.status,text:c,data:l}):this._rejectJob(t,{status:i.status,text:c,data:l}),{attempted:n,retry:!1,requestStartedAt:r}}catch(i){return i===Te||this.stopped?(this._rejectJob(t,Ke()),{attempted:!1,retry:!1,requestStartedAt:r}):(this._rejectJob(t,{error:i?.message||String(i)}),{attempted:n,retry:!1,requestStartedAt:r})}finally{o.cleanup(),t.cancelActive=null,t.cancelPromise=null,this._currentJob===t&&(this._currentJob=null)}}async _applyPolicy(t,r){if(this.stopped)return;let n=t.policy;if(n.applyInterval&&!this.stopped){let s=this._now()-r;await this._sleep(Math.max(0,this._policyInterval(n)-s)),this._externalStopRequested()&&!this.stopped&&this.stop()}}async _run(){if(!(this.running||this.stopped)){this.running=!0;try{for(;this.queue.length>0&&!this.stopped;){if(this._externalStopRequested()){this.stop();break}let t=this.queue.shift(),r=await this._attempt(t);if(this.stopped){this._rejectJob(t,Ke());break}if(r.retry&&!t.settled){this.queue.unshift(t);continue}r.attempted&&await this._applyPolicy(t,r.requestStartedAt)}}finally{this.cooling=!1,this._currentJob=null,this._currentController=null,this.stopped&&(this._consecutive429=0,this._429Warned=!1),this.running=!1}this.queue.length>0&&!this.stopped&&this._run()}}stop(){this.stopped=!0,this.cooling=!1,this._consecutive429=0,this._429Warned=!1,this._interruptWaits();let t=this._currentJob;if(t&&(this._rejectJob(t,Ke()),t.cancelActive?.()),this._currentController)try{this._currentController.abort()}catch{}for(let r of this.queue)this._rejectJob(r,Ke());this.queue=[]}};async function ri(e,t,r){let n=Q();if(!n)throw new Error("Profile URL not found");let o=new URL(window.location.href).searchParams.get("sort")||"p",i=[],c=new Set,l=150,u=e.foilScanMode?"闪卡":"普通卡";for(let d=1;d<=e.maxBadgePages;d++){let m=(d-1)*l+1,p=d*l;t?.(`正在扫描${u}候选徽章 ${m}-${p} (页${d})...`);let h=`${n}/badges/?sort=${o}&p=${d}`,f=await r.fetch(h);if(!f||!f.text){if(d===1)throw new Error(`Failed to fetch badges: ${f?.status}`);break}let g=new DOMParser().parseFromString(f.text,"text/html"),y=g.querySelectorAll(".badge_row"),b=Math.min(p,m+y.length-1);if(y.length===0)break;let S=0;for(let E of y){let x=E.querySelector(".badge_row_overlay");if(!x)continue;let I=x.getAttribute("href")||"",N=I.match(/\/(?:gamecards|badges)\/(\d+)\/?(\?|$)/);if(!N)continue;let A=N[1],B=I.includes("border=1");if(!e.foilScanMode&&B)continue;let T=e.foilScanMode||B,L=`${A}_${T?1:0}`;if(c.has(L))continue;c.add(L);let z=E.querySelector(".badge_progress_info");if(!z)continue;let q=z.textContent.trim().match(/(\d+)\s*\/\s*(\d+)/);if(!q)continue;let be=parseInt(q[1],10),gt=parseInt(q[2],10);if(!e.foilScanMode&&(be===0||be>=gt))continue;let He=E.querySelector(".badge_title"),Ye="";He&&(Ye=(He.querySelector(".badge_title_row")?.textContent||He.textContent).replace(/(?:View details|查看详情|[\u200B\u200C\u200D\ufeff])/gi,"").trim());let Se=0,bt=E.querySelector(".progress_info_bold");if(bt){let ne=bt.textContent.match(/(\d+)\s*(?:张剩余卡牌掉落|card drops? remaining)/i);ne&&(Se=parseInt(ne[1],10))}i.push({appid:A,isFoil:T,gameName:Ye,owned:be,totalInSet:gt,dropsRemaining:Se}),S++}if(t?.(`徽章 ${m}-${b}: ${S} 个${u}候选 (共 ${y.length} 个徽章)`),!g.querySelector(`a.pagebtn[href*="p=${d+1}"]`))break}return t?.(`徽章列表扫描完成, 共 ${i.length} 个${u}候选`),i}function P(e,t){let r=document.createElement("span");return r.className=e,r.textContent=String(t),r}function yn(e){let t=document.createElement("span");return t.className="stch-check-hit",t.appendChild(e),t}function Mt(e,t){let r=document.createElement("div");r.className="stch-inventory-empty",r.textContent=t,e.appendChild(r)}function Qt(e,t,r){let n=document.createElement(t?"img":"div");t?(n.src=t,n.alt=r||""):(n.className="stch-inv-placeholder",n.textContent=r||"?"),e.appendChild(n)}function vn(e,t){for(let r of t){let n=e.querySelector(r)?.textContent?.trim();if(n)return n}return""}function Ms(e,t,r){for(let n of t){let s=e.querySelector(n)?.getAttribute(r);if(s)return s}return""}function Bu(e){let t=String(e||"").trim().replace(/^url\(["']?/,"").replace(/["']?\)$/,"");if(!t)return"";try{return new URL(t,location.origin).href}catch{return t}}function Er(e){let t=Bu(e);return t.includes("avatars.fastly.steamstatic.com/")?t.replace(/(?:_(?:medium|full))?(\.[a-z0-9]+)(\?.*)?$/i,"_full$1$2"):t}function ni(e){if(!e)return"";let t=e.getAttribute("src")||e.getAttribute("data-src")||e.getAttribute("data-original")||e.getAttribute("data-fullsrc");if(t)return Er(t);let r=e.getAttribute("srcset")||e.getAttribute("data-srcset");if(r){let s=r.split(",").map(o=>o.trim().split(/\s+/)[0]).filter(Boolean).pop();if(s)return Er(s)}let n=e.style?.backgroundImage||"";return n&&n!=="none"?Er(n):""}function Es(e,t){for(let r of t){let n=e.querySelector(r),s=ni(n);if(s)return s;let o=n?.querySelector?.("img"),i=ni(o);if(i)return i}return""}var Lu=new Set(["exact","estimated"]),Tu=new Set(["complete","prediction","fallback"]);function xn(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let t=Number(e.priceMinor),r=Number(e.currencyId),n=Number(e.observedAt);return!Number.isSafeInteger(t)||t<=0||!Number.isInteger(r)||r<=0||!Lu.has(e.accuracy)?null:{priceMinor:t,currencyId:r,accuracy:e.accuracy,reason:Tu.has(e.reason)?e.reason:e.accuracy==="exact"?"complete":"fallback",observedAt:Number.isFinite(n)&&n>0?Math.floor(n):0}}var si=Object.freeze([Object.freeze({configKey:"blacklistNames",dataKey:"names",label:"名称"}),Object.freeze({configKey:"blacklistSources",dataKey:"sources",label:"来源"}),Object.freeze({configKey:"blacklistDates",dataKey:"dates",label:"日期"}),Object.freeze({configKey:"blacklistFixed",dataKey:"fixed",label:"固定状态"}),Object.freeze({configKey:"blacklistPriceData",dataKey:"priceData",label:"价格"})]);function Fu(e,t,r){let n=e;if(n==null||n==="")return{};if(typeof n=="string")try{n=JSON.parse(n)}catch{return r.push({field:t.configKey,label:t.label,reason:"invalid-json"}),{}}return!n||typeof n!="object"||Array.isArray(n)?(r.push({field:t.configKey,label:t.label,reason:"invalid-shape"}),{}):{...n}}function Du(e,t){let r={};for(let[n,s]of Object.entries(e)){let o=xn(s);if(!/^\d+$/.test(n)||!o){t.push({field:"blacklistPriceData",label:"价格",reason:"invalid-entry",appid:n});continue}r[n]=o}return r}function Ns(e={}){let t=[],r={appids:String(e.blacklist||"").split(",").map(n=>n.trim()).filter(Boolean)};for(let n of si){let s=Fu(e[n.configKey],n,t);r[n.dataKey]=n.dataKey==="priceData"?Du(s,t):s}return{ok:t.length===0,diagnostics:t,...r}}function Hu(e,t){e.blacklist=t.appids.join(",");for(let r of si)e[r.configKey]=JSON.stringify(t[r.dataKey])}function ai(e,t){let r=Ns(e);if(!r.ok)return{ok:!1,changed:!1,diagnostics:r.diagnostics,storage:r};let n=t(r)!==!1;return n&&Hu(e,r),{ok:!0,changed:n,diagnostics:[],storage:r}}function oi(e){let t=e?.diagnostics||[];return t.length===0?"":`黑名单${[...new Set(t.map(n=>n.label).filter(Boolean))].join("、")}数据损坏,已禁止修改;原始数据未被覆盖`}var ii=new WeakSet,ci=new WeakSet;function ot(e,t={}){if(!e||ii.has(e))return;ii.add(e);let r=t.checkboxSelector||'input[type="checkbox"]',n=t.activationSelector||r,s=t.rowSelector||"",o=t.excludeSelector||"",i=null,c=0,l=m=>{if(!(m instanceof Element)||!e.contains(m))return null;let p=m.closest(r);if(!p){let h=m.closest(n);p=h?.matches?.(r)?h:h?.querySelector?.(r)}return!p&&s&&(p=m.closest(s)?.querySelector?.(r)),!p||!e.contains(p)||p.disabled||o&&p.matches(o)?null:p},u=m=>{!i||i.visited.has(m)||(i.visited.add(m),m.checked!==i.checked&&(m.checked=i.checked,m.dispatchEvent(new Event("change",{bubbles:!0}))))},d=()=>{if(!i)return;let m=i.pointerId;i=null,c=Date.now()+80,e.classList.remove("stch-checkbox-dragging");try{e.hasPointerCapture?.(m)&&e.releasePointerCapture(m)}catch{}};e.addEventListener("pointerdown",m=>{if(m.button!==0||m.pointerType==="touch")return;let p=l(m.target);if(p){i={pointerId:m.pointerId,checked:!p.checked,visited:new Set},e.classList.add("stch-checkbox-dragging");try{e.setPointerCapture?.(m.pointerId)}catch{}u(p),c=Date.now()+80,m.preventDefault(),m.stopPropagation()}}),e.addEventListener("pointermove",m=>{if(!i||m.pointerId!==i.pointerId)return;let p=l(document.elementFromPoint(m.clientX,m.clientY));p&&u(p),m.preventDefault()},{passive:!1}),e.addEventListener("pointerup",m=>{i&&m.pointerId===i.pointerId&&d()}),e.addEventListener("pointercancel",m=>{i&&m.pointerId===i.pointerId&&d()}),e.addEventListener("lostpointercapture",d),e.addEventListener("click",m=>{if(Date.now()>c)return;let p=m.target instanceof Element?m.target.closest(n):null;!p||!e.contains(p)||(m.preventDefault(),m.stopImmediatePropagation())},!0)}function Yt(e,t={}){if(!e||ci.has(e))return;ci.add(e);let r=t.itemSelector||".stch-inv-tile",n=null,s=0,o=l=>{if(!(l instanceof Element)||!e.contains(l))return null;let u=l.closest(r);return u&&e.contains(u)?u:null},i=l=>{!n||n.visited.has(l)||(n.visited.add(l),t.isSelected?.(l)===!0===n.selected)||(t.setSelected?.(l,n.selected),l.classList.toggle("selected",n.selected),t.onSelectionChange?.(l,n.selected))},c=()=>{if(!n)return;let l=n.pointerId;n=null,s=Date.now()+80,e.classList.remove("stch-checkbox-dragging");try{e.hasPointerCapture?.(l)&&e.releasePointerCapture(l)}catch{}};e.addEventListener("pointerdown",l=>{if(l.button!==0||l.pointerType==="touch")return;let u=o(l.target);if(u){n={pointerId:l.pointerId,selected:t.isSelected?.(u)!==!0,visited:new Set},e.classList.add("stch-checkbox-dragging");try{e.setPointerCapture?.(l.pointerId)}catch{}i(u),s=Date.now()+80,l.preventDefault(),l.stopPropagation()}}),e.addEventListener("pointermove",l=>{if(!n||l.pointerId!==n.pointerId)return;let u=o(document.elementFromPoint(l.clientX,l.clientY));u&&i(u),l.preventDefault()},{passive:!1}),e.addEventListener("pointerup",l=>{n&&l.pointerId===n.pointerId&&c()}),e.addEventListener("pointercancel",l=>{n&&l.pointerId===n.pointerId&&c()}),e.addEventListener("lostpointercapture",c),e.addEventListener("click",l=>{let u=o(l.target);if(!u)return;if(Date.now()<=s){l.preventDefault(),l.stopImmediatePropagation();return}let d=t.isSelected?.(u)!==!0;t.setSelected?.(u,d),u.classList.toggle("selected",d),t.onSelectionChange?.(u,d)},!0)}function As(e){let t=oi(e);if(!t)return"";console.warn(`[STCH] ${t}`,e.diagnostics);let r=document.getElementById("stch-bl-result");return r&&(r.dataset.storageError="true",r.textContent=t,r.style.color="#d94126"),t}function Rs(){let e=document.getElementById("stch-bl-result");!e||e.dataset.storageError!=="true"||(delete e.dataset.storageError,e.textContent="",e.style.removeProperty("color"))}function _s(e){let t=ai(a.cfg,e);return t.ok?(Rs(),t.changed&&ue(a.cfg),t):(As(t),t)}function $s(){return Ns(a.cfg)}function Jt(e,t,r,n=0,s=null){let o=String(e||"");if(!/^\d+$/.test(o))return{ok:!1,changed:!1,diagnostics:[{field:"blacklist",label:"AppID",reason:"invalid-appid",appid:o}]};let i=xn(s);return _s(c=>{let l=c.appids.includes(o),u=!1;return l||(c.appids.push(o),c.names[o]=String(t||""),c.sources[o]=r,c.dates[o]=Date.now(),u=!0),n&&!c.fixed[o]&&(c.fixed[o]=1,u=!0),i&&(c.priceData[o]=i,u=!0),u})}function Ps(e){let t=new Set(e.map(r=>String(r||"")).filter(Boolean));return _s(r=>{let n=r.appids.filter(s=>!t.has(s));if(n.length===r.appids.length)return!1;r.appids=n;for(let s of t)delete r.names[s],delete r.sources[s],delete r.dates[s],delete r.fixed[s],delete r.priceData[s];return!0})}function Os(e,t){let r=new Set(e.map(n=>String(n||"")).filter(Boolean));return _s(n=>{let s=!1;for(let o of n.appids)r.has(o)&&(t&&!n.fixed[o]?(n.fixed[o]=1,s=!0):!t&&Object.hasOwn(n.fixed,o)&&(delete n.fixed[o],s=!0));return s})}function li(e,t=Date.now()){let r=$s();if(!r.ok)return{...r,appids:[]};let n=Math.max(1,Number(e)||1)*864e5;return{ok:!0,diagnostics:[],appids:r.appids.filter(s=>!r.fixed[s]&&r.dates[s]&&t-r.dates[s]>n)}}async function ui(e){try{let t=Q();if(!t)return null;let r=`${t}/gamecards/${e}/`,n=await fetch(r,{credentials:"include"});if(!n.ok)return null;let s=await n.text(),i=new DOMParser().parseFromString(s,"text/html").querySelector(".badge_title");return i&&(i.querySelector(".badge_title_row")?.textContent||i.textContent).replace(/(?:View badge progress|查看徽章进度|View details|查看详情|[\u200B\u200C\u200D\ufeff])/gi,"").trim().replace(/\s*徽章\s*$/,"").trim()||null}catch{return null}}function it(){let e=document.getElementById("stch-bl-add"),t=document.getElementById("stch-bl-add-fixed"),r=document.getElementById("stch-bl-del-sel"),n=document.getElementById("stch-bl-fix-sel"),s=document.getElementById("stch-bl-unfix-sel");if(!e)return;let o=document.getElementById("stch-bl-list"),i=document.getElementById("stch-bl-list-fixed"),c=[...o?o.querySelectorAll(".stch-bl-cb:checked"):[]];i&&c.push(...i.querySelectorAll(".stch-bl-cb:checked"));let l=$s(),u=l.ok;u?Rs():As(l);let d=u&&c.length>0,m=l.fixed,p=c.some(f=>!m[f.dataset.appid]),h=c.some(f=>!!m[f.dataset.appid]);e.style.display=u&&a.blLookupName&&!d?"":"none",t.style.display=u&&a.blLookupName&&!d?"":"none",r.style.display=d?"":"none",n.style.display=d&&p?"":"none",s.style.display=d&&h?"":"none",r.classList.toggle("disabled",!d),r.classList.toggle("stch-btn-danger",d),n.classList.toggle("disabled",n.style.display==="none"),s.classList.toggle("disabled",s.style.display==="none"),d&&document.getElementById("stch-bl-result")?.dataset.storageError!=="true"&&(document.getElementById("stch-bl-result").textContent="")}function Fe(){let e=document.getElementById("stch-bl-list"),t=document.getElementById("stch-bl-list-fixed"),r=document.getElementById("stch-bl-count");if(!e)return;ot(document.getElementById("stch-tab-blacklist"),{checkboxSelector:".stch-bl-cb",activationSelector:".stch-bl-cb, .stch-bl-cb-hd",rowSelector:".stch-bl-row"});let n=$s(),{appids:s,names:o,sources:i,dates:c,fixed:l,priceData:u}=n;n.ok?Rs():As(n);let d={0:"手动",1:"自动"},m=s.filter(x=>!l[x]),p=s.filter(x=>l[x]),h=x=>x?String(Math.floor((Date.now()-x)/864e5)):"—",f=()=>{let x=document.createElement("div");x.className="stch-bl-row stch-row-header",x.appendChild(P("stch-bl-id","游戏ID")),x.appendChild(P("stch-bl-name","游戏名")),x.appendChild(P("stch-bl-fixed-col","")),x.appendChild(P("stch-bl-source","来源"));let I=P("stch-bl-price","单套价格");return I.title=`绿色:完整查价且无估算 黄色:提前预测跳过或价格包含估算`,x.appendChild(I),x.appendChild(P("stch-bl-days","天数")),x.appendChild(P("stch-bl-cb-hd","")),x},g=x=>{let I=document.createElement("div");I.className="stch-bl-row";let N=P("",x);return N.style.color="#8f98a0",I.appendChild(N),I},y=(x,I)=>{let N=document.createDocumentFragment();for(let A of I){let B=document.createElement("div");B.className="stch-bl-row",B.appendChild(P("stch-bl-id",A)),B.appendChild(P("stch-bl-name",o[A]||"—")),B.appendChild(P("stch-bl-fixed-col",l[A]?"固定":"")),B.appendChild(P("stch-bl-source",d[i[A]]||"—"));let T=u[A],L=P(`stch-bl-price ${T?.accuracy==="exact"?"exact":T?"estimated":""}`,T?w(T.priceMinor,T.currencyId):"—");T&&(L.title=T.accuracy==="exact"?"完整查价":T.reason==="prediction"?"提前预测后跳过":"价格包含中位价或缺价估算"),B.appendChild(L),B.appendChild(P("stch-bl-days",c[A]?h(c[A]):"—"));let z=document.createElement("span");z.className="stch-bl-cb-hd";let D=document.createElement("input");D.type="checkbox",D.className="stch-bl-cb",D.dataset.appid=A,D.setAttribute("aria-label",`选择 ${o[A]||A}`),D.disabled=!n.ok,z.appendChild(D),B.appendChild(z),N.appendChild(B)}x.appendChild(N)};if(e.replaceChildren(),t&&t.replaceChildren(),m.length===0&&p.length===0?(e.appendChild(g("游戏/AppID黑名单为空")),r&&(r.textContent="")):(e.appendChild(f()),m.length>0?y(e,m):e.appendChild(g("—")),r&&(r.innerHTML=`共 ${s.length} 项(固定 ${p.length})`)),t&&p.length>0){let x=P("stch-bl-sep","固定游戏黑名单");t.appendChild(x),y(t,p)}let b=document.getElementById("stch-bl-del-sel");b&&(b.classList.add("disabled"),b.classList.remove("stch-btn-danger"));let S=document.getElementById("stch-bl-cleanup");S&&(S.classList.add("disabled"),S.classList.remove("stch-btn-danger"));let M=[...e.querySelectorAll(".stch-bl-cb")];t&&M.push(...t.querySelectorAll(".stch-bl-cb"));let E=0;if(M.forEach(x=>{x.addEventListener("change",()=>{E||(E=requestAnimationFrame(()=>{E=0,it()}))})}),S&&n.ok){let x=Math.max(1,Number(a.cfg.blacklistExpiryDays)||7);s.some(N=>!l[N]&&c[N]&&Date.now()-c[N]>x*864e5)&&(S.classList.remove("disabled"),S.classList.add("stch-btn-danger"))}}function Xt({tag:e,logId:t=null,statusId:r=null,progressWrapId:n=null,progressBarId:s=null,progressTextId:o=null}){let i=null;function c(m,p=""){let h=t?document.getElementById(t):null;if(!h){console.log(`[${e}]`,m);return}let f=document.createElement("div");p&&(f.className=p),f.textContent=`[${new Date().toLocaleTimeString()}] ${m}`,h.appendChild(f),h.scrollTop=h.scrollHeight}function l(m,p=!0){if(!r)return;let h=document.getElementById(r);if(!h)return;if(i&&(clearInterval(i),i=null),!m){h.textContent="",h.style.display="none";return}if(h.style.display="",h.textContent=m,!p)return;let f=0;i=setInterval(()=>{f=(f+1)%4,h.textContent=m+" "+".".repeat(f)},500)}function u(m,p,h=""){if(!n)return;let f=document.getElementById(n),g=document.getElementById(s),y=document.getElementById(o);if(!f||!g||!y)return;f.style.display="";let b=p>0?Math.min(100,m/p*100):0;g.style.width=`${b}%`,y.textContent=h||`${m}/${p}`}function d(){if(!n)return;let m=document.getElementById(n);m&&(m.style.display="none")}return{log:c,setStatus:l,setProgress:u,hideProgress:d}}var ct=Xt({tag:"STCH",logId:"stch-log",statusId:"stch-status",progressWrapId:"stch-progress-wrap",progressBarId:"stch-progress-bar",progressTextId:"stch-progress-text"}),Nr=Xt({tag:"STCH Order",statusId:"stch-order-status"}),di=Xt({tag:"STCH Craft",logId:"stch-craft-log",statusId:"stch-craft-status",progressWrapId:"stch-craft-progress-wrap",progressBarId:"stch-craft-progress-bar",progressTextId:"stch-craft-progress-text"}),Et=Xt({tag:"STCH Surplus",logId:"stch-surplus-log",statusId:"stch-surplus-status",progressWrapId:"stch-surplus-progress-wrap",progressBarId:"stch-surplus-progress-bar",progressTextId:"stch-surplus-progress-text"}),Ar=Xt({tag:"STCH Grind",logId:"stch-grind-log",statusId:"stch-grind-status",progressWrapId:"stch-grind-progress-wrap",progressBarId:"stch-grind-progress-bar",progressTextId:"stch-grind-progress-text"});function lt(e,t=""){console.log("[STCH][Order]",e),["ok","warn","err"].includes(t)&&Nr.setStatus(e.replace(/^\s*[✓✗]\s*/,""),!1)}var{log:Sn}=ct;function Cn(){GM_setValue(en,null)}function Bs(e,t,r,n=5){let s=Math.max(1,Math.floor(Number(n)||5));switch(e){case"complete5":return Math.max(0,s-t-r);case"buy1":return 1;case"buy5":return s;default:return r<1?1:0}}function qu(e,t){if(e.length!==t.length)return!1;let r=[...e].sort(),n=[...t].sort();return r.every((s,o)=>s===n[o])}function zu(e){let t=new URL(e).searchParams,r=t.getAll("items[]");if(r.length>0)return r;let n=[];for(let[s,o]of t.entries()){let i=s.match(/^items\[(\d+)\]$/);i&&n.push({index:Number(i[1]),value:o})}return n.sort((s,o)=>s.index-o.index),n.map(s=>s.value)}function mi(e){return[e?.name,e?.id,e?.className,e?.getAttribute?.("placeholder"),e?.getAttribute?.("aria-label"),e?.getAttribute?.("data-field")].filter(Boolean).join(" ").toLowerCase()}function Gu(e){let t=e.querySelector("input.market_multi_quantity, input[name$='_qty'], input[id$='_qty']"),r=e.querySelector("input.market_multi_price, input[name$='_price'], input[id$='_price']");if(t||r)return{quantity:t,price:r};let n=[...e.querySelectorAll("input, select")].filter(u=>{let d=(u.type||"").toLowerCase();return!u.disabled&&!["hidden","button","submit","checkbox","radio"].includes(d)}),s=/qty|quantity|count|数量/,o=/price|cost|currency|buyorder|金额|价格|单价/,i=n.find(u=>s.test(mi(u)))||null,c=n.filter(u=>u!==i&&(u.tagName||"").toUpperCase()!=="SELECT"),l=c.find(u=>o.test(mi(u)))||null;if(!l){let u=[...e.querySelectorAll(".market_multibuy_price input, .market_commodity_buyorder_price input, [class*='price'] input")].filter(d=>c.includes(d));u.length===1&&(l=u[0])}return!l&&c.length===1&&(l=c[0]),{quantity:i,price:l}}function Uu(e){let t=s=>s?.querySelector("input, select")?(s.querySelectorAll?.('a[href*="/market/listings/753/"]').length||0)<=1:!1,r=e.closest("tr, .market_multibuy_item, .multibuy_item_row, [class*='multibuy'][class*='item']");if(t(r))return r;let n=e.parentElement;for(let s=0;n&&n!==document.body&&s<8;s++,n=n.parentElement)if(t(n))return n;return null}function pi(e,t){if(!e)return!1;let r=String(t);return e.value===r?!1:(e.value=r,e.dispatchEvent(new Event("input",{bubbles:!0})),e.dispatchEvent(new Event("change",{bubbles:!0})),e.dispatchEvent(new KeyboardEvent("keyup",{bubbles:!0,key:"0"})),Jr(e).trigger("blur"),!0)}function fi(e){let t=e.cards.filter(f=>f.marketHashName);if(t.length===0){Sn(`${e.gameName}: 无可用卡牌数据`,"warn");return}let r=a.cfg.buyMode||"complete1",n=new URLSearchParams;n.set("appid","753");let s=[];t.forEach(f=>{let g=Bs(r,e.level,f.owned,ae(e));s.push({card:f,qty:g})});let o=s.filter(f=>f.qty>0);if(o.length===0){Sn(`${e.gameName}: 当前模式下无需购买卡牌`,"info");return}o.forEach(f=>{n.append("items[]",f.card.marketHashName),n.append("qty[]",String(f.qty))});let i=Q();i&&n.set("steamdb_return_to",`${i}/gamecards/${e.appid}/${hr(e)}`);let c=a.cfg.priceAdjustment,l=Math.round((Number.isFinite(c)?c:0)*100),u=he(),d=Ae(u);if(!Number.isInteger(u?.currencyId)||!Number.isSafeInteger(d)||d<=0){Sn(`${e.gameName}: 无法确认 Steam 钱包币种,已停止打开批量购买`,"warn");return}let m={appid:e.appid,isFoil:!!e.isFoil,gameName:e.gameName,currencyId:u?.currencyId??null,bufferCents:l,createdAt:Date.now(),items:o.map(f=>f.card.marketHashName),cards:o.map(f=>({marketHashName:f.card.marketHashName,lowestCents:f.card.priceSource==="lowest"&&Number.isFinite(f.card.lowestCents)&&f.card.lowestCents>0?f.card.lowestCents:null,name:f.card.name,qty:f.qty}))};GM_setValue(en,JSON.stringify(m));let p=`https://steamcommunity.com/market/multibuy?${n.toString()}`,h=o.reduce((f,g)=>f+g.qty,0);Sn(`${e.gameName}: 打开批量购买 (${h} 张, 模式: ${r})`,"ok"),window.open(p,"_blank")}function hi(){let e;try{let x=GM_getValue(en,null);if(!x)return;e=JSON.parse(x)}catch{Cn();return}let t=zu(window.location.href),r=Array.isArray(e?.items)?e.items:[],n=qu(t,r),s=Number.isFinite(e?.createdAt)&&Date.now()-e.createdAt<=Ba,o=he(),i=Number.isInteger(o?.currencyId)&&Number(e?.currencyId)===o.currencyId;if(!e||!Array.isArray(e.cards)||e.cards.length===0||!n||!s||!i){console.warn("[STCH] Ignoring stale or mismatched multibuy data",{currentItems:t,storedItems:r,isFresh:s,storedCurrencyId:e?.currencyId,activeCurrencyId:o?.currencyId}),Cn();return}let c=e.bufferCents||0,l=Ae(o);if(!Number.isSafeInteger(l)||l<=0){console.warn("[STCH] Ignoring multibuy data because the market minimum is unavailable"),Cn();return}(()=>{let x=document.querySelector("h2, h1, .market_multibuy_header, .pageheader");if(x&&!document.getElementById("stch-reset-btn")){let I=document.createElement("span");I.id="stch-reset-btn",I.textContent="恢复默认价格",I.style.cssText="margin-left:12px;padding:4px 12px;background:rgba(67,137,179,0.85);color:#fff;border-radius:3px;cursor:pointer;font-size:13px;",I.addEventListener("click",()=>{location.reload()}),x.appendChild(I)}})();let d=new Map(e.cards.map(x=>[x.marketHashName,x])),m=new Set,p=new Set,h=!1,f=null,g=null,y=null,b=()=>{h||(h=!0,f&&clearTimeout(f),g&&clearTimeout(g),Cn(),y?.disconnect())},S=()=>{if(h)return;let x=!1;document.querySelectorAll('a[href*="/market/listings/753/"]').forEach(N=>{let A=Do(N);if(m.has(A))return;let B=d.get(A);if(!B)return;let T=Uu(N);if(!T)return;let{quantity:L,price:z}=Gu(T);if(!z){p.has(A)||(p.add(A),console.warn(`[STCH] Price input not found for ${A}`));return}B.lowestCents>0&&(x=pi(z,(Math.max(l,B.lowestCents+c)/o.minorUnitFactor).toFixed(o.decimalDigits))||x),L&&(x=pi(L,B.qty||0)||x),m.add(A)}),x&&typeof Ce.UpdateOrderTotal=="function"&&Ce.UpdateOrderTotal(),m.size===e.cards.length&&!f&&(f=setTimeout(()=>{S(),b()},750))},M=0,E=()=>{if(S(),!h){if(++M>=Jn/500){b();return}setTimeout(E,500)}};setTimeout(E,600),y=new MutationObserver(()=>{h||S()}),y.observe(document.body,{childList:!0,subtree:!0}),g=setTimeout(b,Jn)}function ju(){let e=document.getElementById("stch-surplus-item-mode")?.value||a.cfg.surplusItemMode||"card";return["card","background","emoticon"].includes(e)?e:"card"}function Vu(){let e=ju(),t=e==="card"?a.selectedSurplusResults?.size||0:a.selectedGrindResults?.size||0,r=document.getElementById(e==="card"?"stch-surplus-list":"stch-grind-list"),n=r?[...r.querySelectorAll(".stch-inv-tile")]:[],s=n.filter(l=>l.classList.contains("selected")).length,o=n.length>0&&s===n.length,i=document.getElementById("stch-surplus-select-all-btn");i&&(i.textContent=o?"取消全选":"全选",i.classList.toggle("disabled",n.length===0||xe()));let c=t===0||xe();document.getElementById("stch-surplus-sell-btn")?.classList.toggle("disabled",c||At()),document.getElementById("stch-surplus-gem-btn")?.classList.toggle("disabled",c),document.getElementById("stch-surplus-collect-btn")?.classList.toggle("disabled",c),["stch-surplus-sell-price-source","stch-surplus-sell-adjustment"].forEach(l=>{let u=document.getElementById(l);u&&(u.disabled=xe())})}function Nt(){let e=a.craftScanning||a.craftActionRunning,t=a.activeOrdersCancelling||a.surplusActionRunning,r=ut(e),n=a.craftResults.length>0,s=a.craftResults.some(c=>c.selected&&c.maxCraftable>0&&(a.cfg.craftMode==="max"?c.maxCraftable:parseInt(c.craftCount,10)||0)>0);document.getElementById("stch-craft-scan-btn")?.classList.toggle("disabled",r),document.getElementById("stch-craft-stop-btn")?.classList.toggle("disabled",!e),["stch-craft-one-btn","stch-craft-max-btn","stch-craft-clear-btn"].forEach(c=>{let l=c==="stch-craft-one-btn"&&a.cfg.craftMode==="max";document.getElementById(c)?.classList.toggle("disabled",!n||e||t||l)}),document.getElementById("stch-craft-submit-btn")?.classList.toggle("disabled",!s||e||t);let o=document.getElementById("stch-craft-mode"),i=document.getElementById("stch-craft-max-pages");o&&(o.disabled=e||t),i&&(i.disabled=e||t)}function Ku(){let e=a.surplusScanning||a.grindScanning,t=J(e);document.getElementById("stch-surplus-scan-btn")?.classList.toggle("disabled",t),document.getElementById("stch-surplus-stop-btn")?.classList.toggle("disabled",!e),["stch-surplus-only-tradable","stch-surplus-only-recommended","stch-grind-reserve-copies","stch-grind-include-points-shop","stch-surplus-item-mode"].forEach(r=>{let n=document.getElementById(r);n&&(n.disabled=t)})}function Me(){Ku(),Vu()}function xe(){return a.scanning||a.recalculationRunning||a.orderSubmissionRunning||a.orderActionRunning||a.activeOrdersLoading||a.activeOrderPriceQueryRunning||a.activeOrdersCancelling||a.historyRefreshing||a.craftScanning||a.craftActionRunning||a.surplusActionRunning||a.surplusScanning||a.grindScanning}function gi(){return a.activeOrdersCancelling||a.surplusActionRunning}function At(){return a.scanning||a.orderActionRunning||a.historyRefreshing||a.surplusScanning||a.grindScanning||a.activeOrderPriceQueryRunning||a.recalculationRunning||a.sidebarPriceRefreshing}function J(e=!1){return!!e||At()||gi()}function ut(e=!1){return!!e||gi()}function Zt(){let e=rt().length,t=document.getElementById("stch-selected-count");t&&(t.textContent=`已选择 ${e} 项`);let r=e===0||At(),n=e===0||a.orderSubmissionRunning;document.getElementById("stch-recalculate-btn")?.classList.toggle("disabled",r),document.getElementById("stch-submit-orders-btn")?.classList.toggle("disabled",n),document.getElementById("stch-scan-btn")?.classList.toggle("disabled",J(a.scanning));let s=document.getElementById("stch-result-select-all");s&&(s.checked=a.results.length>0&&e===a.results.length,s.indeterminate=e>0&&e0&&e===a.orderResults.length,s.indeterminate=e>0&&ea.selectedActiveBuyOrderGroups.has(u.key)),o=document.getElementById("stch-active-orders-selected-count");o&&(o.textContent=`已选 ${s.length} 项`);let i=document.getElementById("stch-active-orders-refresh");i?.classList.toggle("disabled",r),i&&(i.disabled=r);let c=document.getElementById("stch-active-orders-cancel-selected");c?.classList.toggle("disabled",e||s.length===0),c&&(c.disabled=e||s.length===0);let l=document.getElementById("stch-active-orders-query-prices");l?.classList.toggle("disabled",n||s.length===0),l&&(l.disabled=n||s.length===0)}function R(){Zt(),Nt(),Me(),Wu();let e=document.getElementById("stch-history-refresh"),t=J(a.historyRefreshing);e?.classList.toggle("disabled",t);let r=document.getElementById("stch-sidebar-refresh");r&&(r.disabled=At()),document.getElementById("stch-settings-reset")?.classList.toggle("disabled",xe()||a.sidebarPriceRefreshing),e&&(e.disabled=t)}function _r(e){let t=Number(e);return Number.isFinite(t)&&t>0?Math.round(t):null}function Qu(e){return Math.max(0,Number(e)||0)}function bi(e,t={}){if(e?.hasIncompletePricing)return{completionCents:null,fullCents:null,levelCents:null};let r={completion:Math.max(0,Number(e?.cheapestSetCostCents)||0),full:Math.max(0,Number(e?.fullSetCostCents)||0),level:Math.max(0,Number(e?.level5CostCents)||0)},n=Number.isFinite(Number(t.adjustmentMinor))?Math.round(Number(t.adjustmentMinor)):0,s=_r(t.minimumPriceMinor);if(s===null)return{completionCents:null,fullCents:null,levelCents:null};let o=String(t.priceSource||"lowest"),i=t.automatic===!0,c=Math.max(0,(Number(e?.targetLevel)||5)-(Number(e?.level)||0)),l={completion:0,full:0,level:0},u={completion:0,full:0,level:0};for(let d of Array.isArray(e?.cards)?e.cards:[]){let m=_r(d?.lowestCents);if(m===null)continue;let p=_r(d?.medianCents)??m,h=Qu(d?.owned),f=Math.max(0,1-h),g=Math.max(0,c-h),y=_r(t.resolveFinalPriceMinor?.(d)),b=_r(t.resolveBasePriceMinor?.(d))??m,S=y??Math.max(s,b+n);if(l.completion+=m*f,l.full+=m,l.level+=g>0?m+(g-1)*Math.max(m,p):0,u.completion+=S*f,u.full+=S,!i&&o==="lowest"&&y===null){let M=Math.max(s,m+n),E=Math.max(s,Math.max(m,p)+n);u.level+=g>0?M+(g-1)*E:0}else u.level+=S*g}return{completionCents:Math.max(0,r.completion-l.completion)+u.completion,fullCents:Math.max(0,r.full-l.full)+u.full,levelCents:Math.max(0,r.level-l.level)+u.level}}var wn=new Set,Ls=0;function vi(e){wn.add(e),!Ls&&(Ls=requestAnimationFrame(()=>{Ls=0,wn.has("order")&&($r({prune:!1}),Rr()),wn.has("scan")&&(dt(),Zt()),wn.clear()}))}function xi(e){ot(e,{checkboxSelector:".stch-result-cb",activationSelector:".stch-result-cb, .stch-check-hit, .stch-check",rowSelector:".stch-game-row",excludeSelector:"[id$='select-all']"})}function Si(e){let t=document.getElementById("stch-summary");t&&(t.innerHTML=e)}function Ts(e){let t=document.getElementById("stch-summary-row");t&&(t.style.display=e?"":"none")}function Fs(e="scan"){return e==="order"?{results:a.orderResults,selected:a.selectedOrderResults,sortKey:a.orderSortKey,sortAsc:a.orderSortAsc,render:ge,selectAllId:"stch-order-select-all"}:{results:a.results,selected:a.selectedResults,sortKey:a.sortKey,sortAsc:a.sortAsc,render:Rt,selectAllId:"stch-result-select-all"}}function We(e,t="scan"){let r=Fs(t);return r.sortKey!==e?"":r.sortAsc?" ▲":" ▼"}function Ds(e,t={}){let r=t.source||"scan",n=Fs(r),s=t.showCacheAge?`天数${We("cached",r)}`:"",o=document.createElement("div");o.className="stch-game-row stch-row-header",o.innerHTML=` 游戏ID${We("appid",r)} 游戏名${We("name",r)} 等级${We("level",r)} 卡牌${We("cards",r)} 单套补全${We("cost",r)} 单套在售${We("full",r)} 满级估算 ${We("lv5",r)}? 掉落${We("drops",r)} ${s} 手动购买 `,o.querySelectorAll(".stch-sortable").forEach(u=>{u.addEventListener("click",()=>{r==="order"?Zu(u.dataset.sort):Xu(u.dataset.sort)})});let i=o.querySelector(`#${n.selectAllId}`),c=i.closest(".stch-check"),l=u=>{u?n.results.forEach(d=>n.selected.add(te(d))):n.selected.clear(),n.render(),vi(r)};i.addEventListener("click",u=>{u.stopPropagation(),l(i.checked)}),c.addEventListener("click",u=>{u.stopPropagation(),u.target!==i&&(i.checked=!i.checked,l(i.checked))}),e.appendChild(o)}function Ci(e,t,r){let n=[...e];return t?n.sort((s,o)=>{let i,c;switch(t){case"appid":i=+s.appid,c=+o.appid;break;case"name":i=s.gameName||"",c=o.gameName||"";break;case"level":i=s.level,c=o.level;break;case"cards":i=s.cards.reduce((l,u)=>l+Math.min(u.owned,1),0),c=o.cards.reduce((l,u)=>l+Math.min(u.owned,1),0);break;case"cost":i=s.hasIncompletePricing?null:s.cheapestSetCostCents,c=o.hasIncompletePricing?null:o.cheapestSetCostCents;break;case"full":i=s.hasIncompletePricing?null:s.fullSetCostCents,c=o.hasIncompletePricing?null:o.fullSetCostCents;break;case"lv5":i=s.hasIncompletePricing?null:s.level5CostCents,c=o.hasIncompletePricing?null:o.level5CostCents;break;case"drops":i=s.dropsRemaining,c=o.dropsRemaining;break;case"cached":i=s.cachedAt||0,c=o.cachedAt||0;break;default:return 0}if(typeof i=="string"){let l=i.localeCompare(c,"zh");return r?l:-l}return i==null&&c==null?0:i==null?1:c==null?-1:r?i-c:c-i}):n}function Yu(){return Ci(a.results,a.sortKey,a.sortAsc)}function Ju(){return Ci(a.orderResults,a.orderSortKey,a.orderSortAsc)}function Rt(){let e=document.getElementById("stch-list");if(!e)return;if(xi(e),e.innerHTML="",a.results.length===0){Zt(),tr();return}let t=document.createDocumentFragment();Ds(t),Yu().forEach(n=>Hs(t,n)),e.appendChild(t),Zt(),tr()}function ge(){let e=document.getElementById("stch-order-list");if(!e)return;xi(e),Le(!0),e.innerHTML="";let t=document.createDocumentFragment();if(a.orderResults.length===0){let r=document.createElement("div");r.className="stch-game-row";let n=P("","订购缓存为空");n.style.color="#8f98a0",r.appendChild(n),t.appendChild(r),e.appendChild(t),yi(!1),Rr(),kn();return}Ds(t,{source:"order",showCacheAge:!0}),Ju().forEach(r=>{Hs(t,r,{source:"order",showCacheAge:!0})}),e.appendChild(t),$r({prune:!1}),yi(!0),Rr(),kn()}function Xu(e){a.sortKey===e?a.sortAsc=!a.sortAsc:(a.sortKey=e,a.sortAsc=!0),Rt()}function Zu(e){a.orderSortKey===e?a.orderSortAsc=!a.orderSortAsc:(a.orderSortKey=e,a.orderSortAsc=e!=="cached"),ge()}function Hs(e,t,r={}){let n=r.source||"scan",s=Fs(n),o=document.createElement("div");o.className="stch-game-row",o.dataset.appid=t.appid,o.dataset.foil=t.isFoil?1:0;let i=ae(t),c=t.cards.reduce((E,x)=>E+Math.min(x.owned,1),0),l=t.minVolume||0,u=t.hasIncompletePricing||t.hasEstimated?"color:#888":l>1?"color:#4caf50":l===1?"color:#c9a02c":"",d=t.hasIncompletePricing?"价格请求不完整":t.hasEstimated?"信息不全,采用估计":l>1?"近期成交>1,参考性较强":l===1?"近期成交=1,参考性不强":"近期成交=0,参考性较弱";o.appendChild(P("stch-appid",`${t.appid}${t.isFoil?"(箔)":""}`)),o.appendChild(P("stch-name",t.gameName||"(未知)")),o.appendChild(P("stch-level",`Lv${t.level}/${i}`)),o.appendChild(P("stch-cards",`${c}/${t.totalInSet}`));let m=t.hasIncompletePricing?"-":w(t.cheapestSetCostCents),p=t.hasIncompletePricing?"-":w(t.fullSetCostCents),h=t.hasIncompletePricing?"-":w(t.level5CostCents);o.appendChild(P("stch-cost",m)),o.appendChild(P("stch-full",p));let f=P("stch-lv5",h);if(f.style.cssText=u,f.title=d,o.appendChild(f),o.appendChild(P("stch-drops",t.dropsRemaining)),r.showCacheAge){let E=P("stch-order-cache-age",String(Ir(t.cachedAt)));E.title=t.cachedAt?new Date(t.cachedAt).toLocaleString():"",o.appendChild(E)}let g=document.createElement("span");g.className="stch-buy";let y=document.createElement("a");y.href="javascript:void(0)",y.className="stch-buy-link",y.dataset.appid=t.appid,y.style.cssText="text-decoration:underline;color:#66c0f4;cursor:pointer;",y.textContent="购买";let b=document.createElement("input");b.type="checkbox",b.className="stch-result-cb",b.checked=s.selected.has(te(t)),b.setAttribute("aria-label",`选择 ${t.gameName||t.appid}`),g.appendChild(y),o.appendChild(g);let S=document.createElement("span");S.className="stch-check",S.appendChild(yn(b)),o.appendChild(S),y.addEventListener("click",E=>{E.stopPropagation(),fi(t)});let M=E=>{let x=te(t);E?s.selected.add(x):s.selected.delete(x),vi(n)};b.addEventListener("click",E=>E.stopPropagation()),b.addEventListener("change",E=>{E.stopPropagation(),M(b.checked)}),S.addEventListener("click",E=>{E.stopPropagation(),E.target!==b&&(b.checked=!b.checked,M(b.checked))}),o.addEventListener("click",E=>{if(E.target.closest(".stch-buy-link, .stch-result-cb, .stch-check, .stch-check-hit"))return;let x=Q();x&&window.open(`${x}/gamecards/${t.appid}/${hr(t)}`,"_blank")}),o.style.cursor="pointer",e.appendChild(o)}function wi(e){let t=document.getElementById("stch-list");t.children.length===0&&Ds(t),Hs(t,e);let r=a.results.length%10===0;Kt(e,{persist:r}),r&&ge(),Zt(),tr()}function ed(e){let t=qt(a.cfg,a.automaticPricingDraft),r=t.automatic?Math.round(Number(t.strategyRule?.noWallOffsetMinor)||0):Math.round((Number(t.adjustment)||0)*100),n=Ae();return!Number.isSafeInteger(n)||n<=0?{completionCents:null,fullCents:null,levelCents:null}:bi(e,{automatic:!1,priceSource:"lowest",adjustmentMinor:r,minimumPriceMinor:n})}function ki(e){let t={completion:0,full:0,level:0};for(let r of e){let n=ed(r);if(n.completionCents==null||n.fullCents==null||n.levelCents==null)return null;t.completion+=n.completionCents,t.full+=n.fullCents,t.level+=n.levelCents}return t}function er(e,t){return e?w(e[t]):"-"}function dt(){let e=document.getElementById("stch-summary");if(!e)return;let t=a.results.length,r=a.results.some(o=>o.isFoil)?"闪卡":"普通卡",n=Math.round((Number(a.cfg.threshold)||0)*100),s=ki(rt());e.innerHTML=` 共 ${t} 个${r} ≤ ${w(n)} (单套卡牌价格上限),补全总价 ${er(s,"completion")},全套总价 ${er(s,"full")},满级总价 ${er(s,"level")} `}function yi(e){let t=document.getElementById("stch-order-summary-row");t&&(t.style.display=e?"":"none")}function $r(e={}){let t=document.getElementById("stch-order-summary");if(!t)return;e.prune!==!1&&Le(!0);let r=a.orderResults.length,n=nt(),s=n.length,o=ki(n);t.innerHTML=` 缓存 ${r} 个 · 已选择 ${s} 个 · 补全总价 ${er(o,"completion")},全套总价 ${er(o,"full")},满级总价 ${er(o,"level")} `}function kn(){let e=a.orderResults.some(r=>Number(r.dropsRemaining)>0),t=document.getElementById("stch-order-list");t?.classList.toggle("stch-show-drops",e),t?.classList.toggle("stch-show-completion",a.cfg.showScanCompletionColumn!==!1),t?.classList.toggle("stch-show-sell-set",a.cfg.showScanSellSetColumn!==!1)}var{log:F,setStatus:_t,setProgress:qs,hideProgress:zs}=ct;function rd(e){if(e?.errorKind===j.HTTP)return`HTTP ${e.httpStatus||"错误"}`;switch(e?.errorKind){case j.PARSE:return"响应解析失败";case j.RESPONSE:return"Steam 返回失败";case j.STOPPED:return"请求已停止";case j.CURRENCY:return"币种未确认";case j.INVALID_INPUT:return"请求信息不完整";default:return"网络请求失败"}}function Ii(e){return String(e?.error||e?.message||e?.diagnostics?.[0]?.reason||"黑名单存储不可用")}function Mi(){a.skipCurrent=!0,F("跳过当前徽章...","warn")}function $t(e){let t=document.getElementById("stch-scan-btn");if(t)switch(t.textContent="开始扫描",e){case"phase1":t.textContent="扫描中: 徽章列表";break;case"phase2":t.textContent="扫描中: 卡牌详情+查价";break;case"phase3":t.textContent="扫描完成";break;case"scanning":t.textContent="扫描中...";break;case"done":t.textContent="扫描完成";break}}function tr(){let e=a.cfg.includeDrops&&a.results.some(r=>Number(r.dropsRemaining)>0),t=document.getElementById("stch-list");t?.classList.toggle("stch-show-drops",e),t?.classList.toggle("stch-show-completion",a.cfg.showScanCompletionColumn!==!1),t?.classList.toggle("stch-show-sell-set",a.cfg.showScanSellSetColumn!==!1)}function Ot(){let e=!!a.cfg.foilScanMode;document.getElementById("stch-tab-scan")?.classList.toggle("stch-foil-mode",e);let t=document.getElementById("stch-foil-mode-label"),r=document.getElementById("stch-foil-scan-mode"),n=document.getElementById("stch-buy-mode"),s=document.getElementById("stch-buy-mode-label");t?.classList.toggle("active",e),t?.classList.toggle("disabled",a.scanning),r&&(r.disabled=!!a.scanning),n&&(e?(!n.dataset.normalValue&&n.value!=="complete1"&&(n.dataset.normalValue=n.value),n.value="complete1",n.disabled=!0):(n.disabled=!1,n.value=n.dataset.normalValue||a.cfg.buyMode||O.buyMode,delete n.dataset.normalValue)),s?.classList.toggle("stch-control-disabled",e)}async function Ei(){if(J(a.scanning))return;Pt&&(clearTimeout(Pt),Pt=null),a.scanning=!0,a.stopRequested=!1,a.skipCurrent=!1,a.results=[],a.selectedResults.clear(),Si(""),Ts(!1),document.getElementById("stch-list").innerHTML="",document.getElementById("stch-log").innerHTML="",document.getElementById("stch-scan-btn").classList.add("disabled"),document.getElementById("stch-skip-btn").classList.remove("disabled"),document.getElementById("stch-stop-btn").classList.remove("disabled"),R(),Ot(),$t("scanning"),_t("正在扫描徽章页");let e={...a.cfg,foilScanMode:!!a.cfg.foilScanMode,buyMode:a.cfg.foilScanMode?"complete1":a.cfg.buyMode},t=U(e),r=oe(t,()=>new G(e.requestInterval,a,_t,F,{stopPredicate:o=>!!o?.stopRequested}));a.queue=r;let n=Q();if(!n){F("未找到 Profile URL","err"),r.stop(),a.scanning=!1,a.queue=null,zs(),_t(null),document.getElementById("stch-scan-btn")?.classList.remove("disabled"),document.getElementById("stch-skip-btn")?.classList.add("disabled"),document.getElementById("stch-stop-btn")?.classList.add("disabled"),R(),Ot();return}let s=[];try{let o=Ja(e.foilScanMode);F(`【阶段 1/3】正在扫描徽章页 (${o}模式,找候选游戏)...`),qs(0,1,"阶段1: 扫描徽章页列表中..."),$t("phase1");let i=await ri(e,f=>F(f,"info"),r);if(i.length===0){F(`未找到任何${o}候选徽章`,"warn"),_t(null),$t("done");return}F(`找到 ${i.length} 个${o}候选徽章,开始逐个获取卡牌详情`),F("【阶段 2/3】逐个获取卡牌页 + 查价中..."),qs(0,i.length,`阶段2: 获取卡牌详情 0/${i.length}`),$t("phase2"),_t("扫描卡牌价格中");let c=0,l=0,u=()=>Math.round((Number(a.cfg.threshold)||0)*100),d=null,m=new Set,p=()=>{let f=e.blacklist||"";return f!==d&&(d=f,m=new Set(f.split(",").map(g=>g.trim()).filter(Boolean))),m};for(let f of i){if(a.stopRequested){F("已手动停止","warn");break}if(a.skipCurrent){a.skipCurrent=!1,F(`[${f.appid}] 跳过 (手动)`,"warn"),l++;continue}if(p().has(String(f.appid))){F(`[${f.appid}] ${f.gameName||""}: 在游戏/AppID黑名单中, 跳过`,"info"),l++;continue}if(e.skipCachedOrderResults){let g=gn(f);if(g){F(`[${f.appid}] ${f.gameName||g.gameName||""}: 订购缓存内已有结果 (${Ir(g.cachedAt)} 天),跳过扫描`,"info"),l++;continue}}c++,qs(c,i.length,`阶段2: 获取卡牌详情 ${c}/${i.length} · ${f.gameName||f.appid}`);try{let g=Ze(n,f.appid,f,{language:"english"}),y;try{y=await r.fetch(g)}catch{if(a.stopRequested){F("已手动停止","warn");break}if(a.skipCurrent){a.skipCurrent=!1,F("已跳过当前徽章","warn"),l++;continue}F(`[${f.appid}] ${f.gameName||""}: 拉取 gamecards 网络错误`,"warn"),l++;continue}if(!y||!y.text){F(`[${f.appid}] ${f.gameName||""}: 拉取 gamecards 失败`,"warn"),l++;continue}if(!y.text.includes("badge_card_set_card")){F(`[${f.appid}] ${f.gameName||""}: 无卡牌套组 (可能是社区徽章)`,"info"),l++;continue}let b=Ct(y.text,f.appid,f.isFoil);if(b.appid=f.appid,b.isFoil=f.isFoil,b.targetLevel=ae(b),b.gameName=f.gameName||b.gameName||"",b.cardPrices=[],b.currencyId=a.currencyContext?.currencyId||a.cfg.currencyId||23,b.cheapestSetCostCents=0,b.fullSetCostCents=0,b.level5CostCents=0,b.totalInSet===0||b.need===0){F(`[${f.appid}] ${b.gameName}: Lv${b.level}, 套卡完整或无卡牌`,"info"),l++;continue}if(!a.cfg.includeDrops&&b.dropsRemaining>0){F(`[${f.appid}] ${b.gameName}: 还有 ${b.dropsRemaining} 张掉落,跳过 (可勾选“包含掉落”来扫描)`,"info"),l++;continue}if(b.level>=b.targetLevel){F(`[${f.appid}] ${b.gameName}: 已满级 Lv${b.level}/${b.targetLevel}`,"info"),l++;continue}F(`[${f.appid}] ${b.gameName} ${o} Lv${b.level}/${b.targetLevel} 缺 ${b.need}/${b.totalInSet} 张, 正在查价...`);let S=0,M=0,E=0,x=1/0,I=Math.max(0,b.targetLevel-b.level),N=!0,A=!1,B=!1,T=[],L=0;if(await Y(b.cards,t,async D=>{if(A)return;if(a.stopRequested||a.skipCurrent){B=!0;return}if(!D.marketHashName){F(` ⚠ 卡牌 "${D.name}" 无 market hash name,保留为缺价`,"warn"),Ut(D,{outcome:ve.ERROR,errorKind:j.INVALID_INPUT,errorMessage:"缺少 market_hash_name",httpStatus:null,record:null,currencyId:b.currencyId,observedAt:null},b.currencyId),L++;return}let q=await me(D.marketHashName,r,{preferListing:!0,requireMedian:!0,requireVolume:!0,persistMarketCache:!1});if(A)return;if(a.stopRequested||a.skipCurrent){B=!0;return}q?.record&&s.push(q.record);let be=Ut(D,q,b.currencyId);if(be.outcome===ve.ERROR){F(` ⚠ 卡牌 "${D.name}" (market: ${D.marketHashName}) ${rd(be)},保留为缺价`,"warn"),L++;return}if(be.outcome===ve.NO_PRICE){F(` ⚠ 卡牌 "${D.name}" Steam 未返回可用价格,保留为缺价`,"warn"),T.push(D);return}q.volume0?q.lowestSellCents+(He-1)*Math.max(q.lowestSellCents,q.medianCents):0;let Ye=T.length+L>0;if(!Ye&&M>u()){F(` → 已查${b.cardPrices.length}/${b.totalInSet}张, 全套 ${w(M)} > ${w(u())},跳过`,"info"),N=!1,A=!0;return}if(!Ye&&a.cfg.earlyPricePrediction){let Se=Go(b.cardPrices,b.totalInSet,M),bt=Math.ceil(u()*1.05);if(Se&&Se.predictedCents>bt){let Je=Math.round((a.cfg.autoBlackThreshold||0)*100),ne=a.cfg.earlyPredictionAutoBlacklist&&a.cfg.autoBlackEnabled&&Je>0&&Se.predictedCents>Je;if(F(` → 已查 ${Se.sampleCount}/${b.totalInSet},预测 ${w(Se.predictedCents)} > ${w(bt)},跳过`,"info"),ne){let Qr=Jt(f.appid,b.gameName||f.gameName||"",1,0,{priceMinor:Se.predictedCents,currencyId:b.cardPrices[0]?.currencyId||a.cfg.currencyId,accuracy:"estimated",reason:"prediction",observedAt:Date.now()});Qr.ok?(m.add(String(f.appid)),F(` → 价格预测自动加入游戏黑名单: 预测全套≥${w(Se.predictedCents)} > `+w(Je),"info")):F(` → 自动加入游戏黑名单失败: ${Ii(Qr)}`,"warn")}N=!1,A=!0;return}}}),B){if(a.skipCurrent){a.skipCurrent=!1,F(`[${f.appid}] ${b.gameName}: 已跳过当前徽章`,"warn"),l++;continue}if(a.stopRequested){F("已手动停止","warn");break}}if(!N){A||F(" → 部分卡牌无法取价, 跳过","warn"),l++;continue}b.noPriceDataCount=T.length,b.failedPriceCount=L,b.hasIncompletePricing=T.length+L>0,b.cheapestSetCostCents=b.hasIncompletePricing?null:S,b.fullSetCostCents=b.hasIncompletePricing?null:M,b.level5CostCents=b.hasIncompletePricing?null:E,b.minVolume=x===1/0?0:x;let z=Math.round((a.cfg.autoBlackThreshold||0)*100);if(!b.hasIncompletePricing&&a.cfg.autoBlackEnabled&&z>0&&M>z){let D=Jt(f.appid,b.gameName||f.gameName||"",1,0,{priceMinor:M,currencyId:b.cardPrices[0]?.currencyId||a.cfg.currencyId,accuracy:b.hasEstimated?"estimated":"exact",reason:b.hasEstimated?"fallback":"complete",observedAt:Date.now()});if(D.ok){m.add(String(f.appid)),F(` → 自动加入游戏黑名单: 全套 ${w(M)} > ${w(z)}`,"info"),l++;continue}F(` → 自动加入游戏黑名单失败: ${Ii(D)}`,"warn")}if(!b.hasIncompletePricing&&M>u()){F(` → 整套卡牌价格已大于上限(${w(M)} > ${w(u())}),跳过`,"info"),l++;continue}a.results.push(b),wi(b),b.hasIncompletePricing&&F(`[${f.appid}] ${b.gameName}: 缺价 ${T.length+L}/${b.totalInSet},已保留`,"warn")}catch(g){F(`[${f.appid}] ${f.gameName||""}: 出错 ${g?.error||g?.status||JSON.stringify(g)}`,"err"),l++}}let h=a.results.length;!a.stopRequested&&!r.stopped&&(dt(),Ts(h>0)),_t(null),h>0?$t("phase3"):$t("done")}catch(o){F(`扫描中断: ${o?.message||JSON.stringify(o)}`,"err")}finally{r.stop(),ee(s);try{a.results.length>0&&It()}catch(o){F(`订购缓存保存失败: ${o?.message||o}`,"warn")}ge(),Pt&&(clearTimeout(Pt),Pt=null),a.scanning=!1,a.stopRequested=!1,a.skipCurrent=!1,a.queue=null,zs(),_t(null),document.getElementById("stch-scan-btn")?.classList.remove("disabled"),document.getElementById("stch-skip-btn")?.classList.add("disabled"),document.getElementById("stch-stop-btn")?.classList.add("disabled"),R(),Ot()}}var Pt=null;function Ni(){a.scanning&&(a.stopRequested=!0,a.queue?.stop(),F("已请求停止...","warn"),Pt=setTimeout(()=>{a.scanning&&(a.scanning=!1,a.stopRequested=!1,a.queue=null,zs(),document.getElementById("stch-scan-btn").classList.remove("disabled"),document.getElementById("stch-skip-btn").classList.add("disabled"),document.getElementById("stch-stop-btn").classList.add("disabled"),Ot(),$t("done"),R())},5e3))}var{setStatus:nd,log:sd}=ct,{setStatus:ad}=Nr;async function Ai(e="scan"){let t=e==="order",r=t?nt():rt();if(r.length===0||At())return;let n=t?ad:nd,s=t?lt:sd,o=t?a.selectedOrderResults:a.selectedResults,i=t?a.orderResults:a.results;a.recalculationRunning=!0,R();let c=a.cfg,l=oe(U(c),()=>new G(c.requestInterval,a,n,s,{stopPredicate:()=>!1})),u=0,d=0,m=0;try{for(let p=0;pte(b)===f);if(g.level>=ae(g))y>=0&&i.splice(y,1),o.delete(f),t||Vo(f,{render:!1}),d++,s(`[${h.appid}] ${h.gameName}: 已满级,从结果中移除`,"info");else if(y>=0){t?i[y]=kr(g,Date.now()):(i[y]=g,Kt(g,{persist:!1})),u++;let b=g.hasIncompletePricing?"-":w(g.cheapestSetCostCents),S=g.hasIncompletePricing?"-":w(g.level5CostCents);s(`[${h.appid}] ${h.gameName}: 重算完成,补全 ${b} | 满级 ${S}`,g.hasIncompletePricing?"warn":"ok")}}catch(g){m++,s(`[${h.appid}] ${h.gameName}: 重算失败 ${g?.message||g}`,"err")}}}finally{l.stop(),a.recalculationRunning=!1,n(null);try{It()}catch(p){s(`订购缓存保存失败: ${p?.message||p}`,"warn")}t?ge():(Rt(),dt(),ge()),R(),s(`选中项重算结束: 成功 ${u}, 移除 ${d}, 失败 ${m}`,m?"warn":"ok")}}async function Ri(){return Ai("scan")}async function _i(){return Ai("order")}var $i="stch_market_watchlist";function Gs(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function mt(e,t,r=void 0){return r===void 0?{code:e,message:t,severity:"error"}:{code:e,message:t,severity:"error",details:r}}function od(e){let t=Number(e);return Number.isSafeInteger(t)&&t>0?t:null}function id(e){if(e==null||e==="")return null;if(typeof e=="number")return Number.isSafeInteger(e)&&e>=0?e:null;let t=Number(String(e).replace(/[\s,.'’]/g,""));return Number.isSafeInteger(t)&&t>=0?t:null}function cd(e){if(e==null||e==="")return null;let t=Number(e);return Number.isFinite(t)&&t>=0?Math.trunc(t):null}function Pi(e){return String(e||"").replace(/^\d+-/,"").trim()||e}function Pr(e){let t=String(e?.appid??"753").trim(),r=String(e?.marketHashName??e?.market_hash_name??"").trim();return t&&r?JSON.stringify([t,r]):null}function Us(e,t=Date.now()){if(!Gs(e))return null;let r=String(e.appid??"753").trim(),n=String(e.marketHashName??e.market_hash_name??"").trim(),s=od(e.currencyId??e.currency);if(!r||!n||s===null)return null;let o=Number(e.addedAt),i=Number.isFinite(o)&&o>=0?Math.trunc(o):Math.trunc(t),c=id(e.sellOrderCount??e.sell_order_count);return{appid:r,marketHashName:n,currencyId:s,displayName:String(e.displayName??e.name??"").trim()||Pi(n),imageUrl:String(e.imageUrl??e.image_url??"").trim(),addedAt:i,sellOrderCount:c,metadataObservedAt:c===null?null:cd(e.metadataObservedAt??e.metadata_observed_at)}}function Oi(e,t){let r=Pi(t.marketHashName),n=t.displayName&&t.displayName!==r,s=e.displayName&&e.displayName!==r,o=t.sellOrderCount!==null&&t.metadataObservedAt!==null&&(e.metadataObservedAt===null||t.metadataObservedAt>=e.metadataObservedAt);return{...e,currencyId:t.currencyId,displayName:n||!s?t.displayName:e.displayName,imageUrl:t.imageUrl||e.imageUrl,addedAt:Math.min(e.addedAt,t.addedAt),sellOrderCount:o&&t.sellOrderCount!==null?t.sellOrderCount:e.sellOrderCount,metadataObservedAt:o?t.metadataObservedAt:e.metadataObservedAt}}function rr(e,t={}){let r=Array.isArray(e)?e:Gs(e)&&Array.isArray(e.items)?e.items:[],n=t.now===void 0?Date.now():Number(t.now),s=new Map;r.forEach(l=>{let u=Us(l,n),d=Pr(u);if(!u||!d)return;let m=s.get(d);s.set(d,m?Oi(m,u):u)});let o=t.maxItems===void 0?200:Number(t.maxItems),i=[...s.values()],c=Number.isFinite(o)?Math.max(0,Math.floor(o)):i.length;return{schemaVersion:1,items:i.length>c?i.slice(i.length-c):i}}function ld(e,t={}){if(e==null||e===""||String(e).trim()==="")return{ok:!0,envelope:rr([],t),diagnostics:[]};let r=e;if(typeof e=="string")try{r=JSON.parse(e)}catch(s){return{ok:!1,envelope:null,diagnostics:[mt("invalid-json","Market watchlist is not valid JSON.",{error:String(s?.message||s)})]}}if(!Gs(r)||!Array.isArray(r.items))return{ok:!1,envelope:null,diagnostics:[mt("invalid-envelope","Market watchlist must contain an items array.")]};if(Number(r.schemaVersion)!==1)return{ok:!1,envelope:null,diagnostics:[mt("unsupported-schema-version",`Market watchlist schema ${r.schemaVersion} is not supported.`)]};let n=r.items.reduce((s,o)=>Us(o,t.now)?s:s+1,0);return n>0?{ok:!1,envelope:rr(r,t),diagnostics:[mt("invalid-items",`${n} invalid market watchlist item(s) were left untouched.`,{count:n})]}:{ok:!0,envelope:rr(r,t),diagnostics:[]}}function ud(e,t,r={}){let n=Us(t,r.now),s=Pr(n);if(!n||!s)throw new TypeError("A watchlist item requires appid, marketHashName, and currencyId.");let o=rr(e,r),i=o.items.findIndex(l=>Pr(l)===s),c=[...o.items];return i<0?c.push(n):c[i]=Oi(c[i],n),rr({...o,items:c},r)}function dd(e,t,r={}){let n=Pr(t),s=rr(e,r);return n?{...s,items:s.items.filter(o=>Pr(o)!==n)}:s}function md(e){return typeof e=="function"?e:typeof GM_getValue=="function"?GM_getValue:null}function pd(e){return typeof e=="function"?e:typeof GM_setValue=="function"?GM_setValue:null}function nr(e={}){let t=md(e.getValue);if(!t)return{ok:!1,envelope:null,diagnostics:[mt("gm-get-unavailable","GM_getValue is not available.")]};let r=e.storageKey||$i;try{return{...ld(t(r,null),e),storageKey:r}}catch(n){return{ok:!1,envelope:null,storageKey:r,diagnostics:[mt("gm-read-failed","Failed to read market watchlist.",{error:String(n?.message||n)})]}}}function Bi(e,t={}){let r=pd(t.setValue),n=t.storageKey||$i;if(!r)return{ok:!1,saved:!1,envelope:null,storageKey:n,diagnostics:[mt("gm-set-unavailable","GM_setValue is not available.")]};try{return r(n,JSON.stringify(e)),{ok:!0,saved:!0,envelope:e,storageKey:n,diagnostics:[]}}catch(s){return{ok:!1,saved:!1,envelope:e,storageKey:n,diagnostics:[mt("gm-write-failed","Failed to write market watchlist.",{error:String(s?.message||s)})]}}}function js(e,t={}){let r=nr(t);if(!r.ok||!r.envelope)return{...r,saved:!1};let n=ud(r.envelope,e,t);return JSON.stringify(n)===JSON.stringify(r.envelope)?{...r,saved:!1}:Bi(n,t)}function Li(e,t={}){let r=nr(t);if(!r.ok||!r.envelope)return{...r,saved:!1,removed:!1};let n=r.envelope.items.length,s=dd(r.envelope,e,t);return s.items.lengthr.label.localeCompare(n.label,"zh-CN"))}function Or(e=a.historySource){return e==="scan"?Di(a.results):e==="order"?Di(a.orderResults):[]}function hd(){let e=Or("scan"),t=Or("order");return a.historySource==="scan"&&e.length>0?"scan":a.historySource==="order"&&t.length>0?"order":a.historySource==="manual"?"manual":e.length>0?"scan":t.length>0?"order":"manual"}function zi(){let e=document.getElementById("stch-history-source"),t=document.getElementById("stch-history-card"),r=document.getElementById("stch-history-card-label"),n=document.getElementById("stch-history-manual-label");if(!e||!t)return;let s=Or("scan"),o=Or("order");e.querySelectorAll("option").forEach(l=>{l.value==="scan"?(l.textContent=`扫描结果 (${s.length})`,l.disabled=s.length===0):l.value==="order"&&(l.textContent=`订购缓存 (${o.length})`,l.disabled=o.length===0)}),a.historySource=hd(),e.value=a.historySource;let i=a.historySource==="manual";if(r?.classList.toggle("stch-history-hidden",i),n?.classList.toggle("stch-history-hidden",!i),i)return;let c=a.historySource==="scan"?s:o;t.replaceChildren(),c.forEach(l=>{let u=document.createElement("option");u.value=l.marketHashName,u.textContent=l.label,t.appendChild(u)}),c.some(l=>l.marketHashName===a.historyMarketHashName)||(a.historyMarketHashName=c[0]?.marketHashName||""),t.value=a.historyMarketHashName}function Gi(){document.querySelectorAll("#stch-tab-history [data-history-range]").forEach(e=>{let t=e.dataset.historyRange===a.historyRange;e.classList.toggle("active",t),e.setAttribute("aria-pressed",String(t))})}function gd(e){let t=e.getBoundingClientRect(),r=Math.max(1,Math.floor(t.width)),n=Math.max(1,Math.floor(t.height)),s=Math.max(1,Math.min(3,Number(window.devicePixelRatio)||1)),o=Math.max(1,Math.floor(r*s)),i=Math.max(1,Math.floor(n*s));return(e.width!==o||e.height!==i)&&(e.width=o,e.height=i),{width:r,height:n,ratio:s}}function bd(e){if(!e?.isConnected)return;let t=Array.isArray(e._stchPoints)?e._stchPoints:[],{width:r,height:n,ratio:s}=gd(e),o=e.getContext("2d");if(!o||(o.setTransform(s,0,0,s,0,0),o.clearRect(0,0,r,n),t.length===0))return;let i=5,c=Math.max(1,r-i*2),l=Math.max(1,n-i*2),u=t[0].observedAt,d=t.at(-1).observedAt,m=Math.max(1,d-u),p=Math.min(...t.map(g=>g.value)),h=Math.max(...t.map(g=>g.value));if(p===h){let g=Math.max(1,p*.05);p-=g,h+=g}let f=t.map((g,y)=>({x:t.length===1?i+c/2:i+(g.observedAt-u)/m*c,y:i+l-(g.value-p)/(h-p)*l,index:y}));o.strokeStyle="rgba(102, 192, 244, 0.16)",o.lineWidth=1,o.beginPath(),o.moveTo(i,n-i),o.lineTo(r-i,n-i),o.stroke(),o.strokeStyle="#66c0f4",o.lineWidth=2,o.lineJoin="round",o.lineCap="round",o.beginPath(),o.moveTo(f[0].x,f[0].y),f.slice(1).forEach(g=>o.lineTo(g.x,g.y)),o.stroke(),f.length===1&&(o.fillStyle="#66c0f4",o.beginPath(),o.arc(f[0].x,f[0].y,2.5,0,Math.PI*2),o.fill())}function Ui(){Bt&&cancelAnimationFrame(Bt),Bt=requestAnimationFrame(()=>{Bt=0,document.querySelectorAll("#stch-history-list canvas.stch-history-spark").forEach(bd)})}function Hi(e){return e!=null&&e!==""&&Number.isFinite(Number(e))?Number(e).toLocaleString("zh-CN"):"—"}function yd(e){if(!Number.isFinite(e.changeMinor))return"—";if(e.changeMinor===0)return`${w(0)} (0.00%)`;let t=e.changeMinor>0?"+":"−",r=Number.isFinite(e.percentChange)?` (${e.percentChange>0?"+":""}${e.percentChange.toFixed(2)}%)`:"";return`${t}${w(Math.abs(e.changeMinor))}${r}`}function In(e,t,r=""){let n=document.createElement("div");n.className=`stch-history-row-metric ${r}`.trim();let s=document.createElement("span");s.textContent=e;let o=document.createElement("b");return o.textContent=t,n.append(s,o),n}function vd(e,t){let r=No(t,{sorted:!0}),n=Fi[a.historyRange]??Fi["7d"],s=Ao(t,{from:n===1/0?-1/0:Date.now()-n,maxPoints:96,sorted:!0}),o=document.createElement("div");o.className="stch-history-row",o.dataset.marketHashName=e.marketHashName;let i=document.createElement("a");i.className="stch-history-item-link",i.href=`https://steamcommunity.com/market/listings/${Lt}/${encodeURIComponent(e.marketHashName)}`,i.target="_blank",i.rel="noopener noreferrer",i.title="打开 Steam 市场挂牌页";let c=document.createElement("span");c.className="stch-history-thumb";let l=document.createElement("span");if(l.className="stch-history-thumb-placeholder",l.textContent="▧",c.appendChild(l),e.imageUrl){let S=document.createElement("img");S.src=e.imageUrl,S.alt="",S.loading="lazy",S.addEventListener("load",()=>c.classList.add("loaded")),S.addEventListener("error",()=>S.remove()),c.appendChild(S)}let u=document.createElement("span");u.className="stch-history-item-names";let d=document.createElement("b");d.textContent=e.displayName||e.marketHashName;let m=document.createElement("small");m.textContent=e.marketHashName,u.append(d,m),i.append(c,u);let p=document.createElement("div");p.className="stch-history-spark-wrap";let h=document.createElement("canvas");if(h.className="stch-history-spark",h._stchPoints=s,h.setAttribute("aria-label",`${e.displayName||e.marketHashName} 价格折线图`),p.appendChild(h),s.length===0){let S=document.createElement("span");S.className="stch-history-spark-empty",S.textContent="暂无价格样本",p.appendChild(S)}let f=document.createElement("div");f.className="stch-history-row-stats",f.append(In("在售",Hi(e.sellOrderCount)),In("24 小时销量",Hi(r.volume24h)),In("现价",Number.isFinite(r.currentMinor)?w(r.currentMinor):"—"),In("较上次",yd(r),Number.isFinite(r.changeMinor)?r.changeMinor>0?"up":r.changeMinor<0?"down":"flat":""));let g=r.observedAt??e.metadataObservedAt,y=g==null?null:Number(g);y!==null&&Number.isFinite(y)&&(f.title=`最新数据:${new Date(y).toLocaleString()}`);let b=document.createElement("button");return b.type="button",b.className="stch-history-remove",b.textContent="删除",b.setAttribute("aria-label",`删除 ${e.displayName||e.marketHashName}`),b.addEventListener("click",S=>{if(S.preventDefault(),S.stopPropagation(),a.historyRefreshing){V("请先停止刷新,再删除已保存物品","warn");return}if(!Li(e).ok){V("已保存物品无法更新;原有数据未被修改","err");return}V(`已从总览移除:${e.displayName||e.marketHashName}`),sr()}),o.append(i,p,f,b),o}function sr(){Gi();let e=document.getElementById("stch-history-list"),t=document.getElementById("stch-history-count");if(!e)return;e.replaceChildren();let r=nr();if(!r.ok||!r.envelope){t&&(t.textContent="已保存 — 项");let l=document.createElement("div");l.className="stch-history-list-empty error",l.textContent="已保存物品无法读取;原有数据未被修改。",e.appendChild(l),V("已保存物品读取失败","err");return}let n=[...r.envelope.items].sort((l,u)=>l.addedAt-u.addedAt);if(t&&(t.textContent=`已保存 ${n.length} 项`),n.length===0){let l=document.createElement("div");l.className="stch-history-list-empty",l.textContent="暂无保存项",e.appendChild(l);return}let s=ms();(!s.ok||!s.envelope)&&V("本地价格历史读取失败;物品列表仍可管理","err");let o=Br(),i=s.ok&&s.envelope?Mo(s.envelope,{appid:Lt,currencyId:o},{normalized:!0}):new Map,c=document.createDocumentFragment();n.forEach(l=>{let u=i.get(l.marketHashName)||[];c.appendChild(vd(l,u))}),e.appendChild(c),Ui()}function xd(){if(a.historySource==="manual"){let r=document.getElementById("stch-history-manual"),n=String(r?.value||"").trim();return n?{appid:Lt,marketHashName:n,currencyId:Br()}:null}let e=Or(a.historySource),t=document.getElementById("stch-history-card")?.value||a.historyMarketHashName;return e.find(r=>r.marketHashName===t)||null}function qi(){if(a.historyRefreshing){V("请先停止刷新,再添加已保存物品","warn");return}let e=xd();if(!e){V(a.historySource==="manual"?"请输入 market_hash_name":"请选择要保存的卡牌","warn"),document.getElementById("stch-history-manual")?.focus();return}let t=nr();if(!t.ok||!t.envelope){V("已保存物品无法读取;原有数据未被修改","err");return}if(!t.envelope.items.some(s=>s.appid===Lt&&s.marketHashName===e.marketHashName)&&t.envelope.items.length>=200){V(`已保存物品已达 ${200} 项上限,请先删除不需要的物品`,"warn");return}if(!js({...e,appid:Lt,currencyId:Br()}).ok){V("已保存物品无法更新;原有数据未被修改","err");return}a.historyMarketHashName=e.marketHashName,V(`已添加:${e.displayName||e.marketHashName}`),sr()}function Sd(e,t){return t?{displayName:t.displayName||e?.displayName||"",imageUrl:t.imageUrl||e?.imageUrl||"",sellOrderCount:t.sellOrderCount??e?.sellOrderCount??null,observedAt:Math.max(Number(e?.observedAt)||0,Number(t.observedAt)||0)}:e}async function Cd(){if(a.historyRefreshing)return;if(J(a.historyRefreshing)){V("请先停止当前操作,再刷新价格","warn");return}let e=nr();if(!e.ok||!e.envelope){V("已保存物品无法读取;原有数据未被修改","err");return}let t=e.envelope.items;if(t.length===0){V("请先添加要保存的物品","warn");return}a.historyRefreshing=!0;let r=++Qe;Ks(!0),R();let n=U(a.cfg),s=oe(n,()=>new G(a.cfg.requestInterval,a,d=>V(d||"正在刷新全部价格"),null,{stopPredicate:()=>!1}));pt=s;let o=[],i=0,c=!1,l=!1,u=()=>(l=!0,ee(o));try{let d=Br(),m=new Array(t.length),p=0;await Y(t,n,async(f,g)=>{if(r!==Qe)return;V(`正在刷新 ${g+1}/${t.length}:${f.displayName||f.marketHashName}`);let y=null,b=await me(f.marketHashName,s,{appid:Lt,currencyId:d,preferListing:!0,requireVolume:!0,persistMarketCache:!1,onMetadata:S=>{y=Sd(y,S)}});r===Qe&&(m[g]={item:f,overview:b,metadata:y},p++,V(`正在刷新 ${p}/${t.length}`))});for(let f of m.filter(Boolean)){let{item:g,overview:y,metadata:b}=f;y?.record&&o.push(y.record);let S=Number.isFinite(Number(y?.record?.lowestSellMinor))&&Number(y.record.lowestSellMinor)>0,M=y?.record?.volume!==null&&y?.record?.volume!==void 0&&Number.isFinite(Number(y.record.volume)),E=b?.sellOrderCount!==null&&b?.sellOrderCount!==void 0&&Number.isFinite(Number(b.sellOrderCount));(!S||!M||!E)&&(i+=1),b&&(js({...g,displayName:b.displayName||g.displayName,imageUrl:b.imageUrl||g.imageUrl,sellOrderCount:b.sellOrderCount,metadataObservedAt:b.observedAt,currencyId:d}).ok||(c=!0))}let h=u();if(sr(),r!==Qe)return;!h.ok||c?V("价格已读取,但部分本地数据保存失败;损坏的存储未被覆盖","err"):i>0?V(`刷新完成;${i} 项缺少现价、销量或在售数量`,"warn"):V(`刷新完成:${t.length} 项`)}catch(d){r===Qe&&V(d?.message||"刷新价格失败","err")}finally{if(!l&&o.length>0){let d=u();sr(),r===Qe&&!d.ok&&V("已完成的价格已读取,但部分本地数据保存失败","err")}s.stop(),pt===s&&(pt=null),r===Qe&&(a.historyRefreshing=!1,Ks(!1),R())}}function Ws(){let e=document.getElementById("stch-tab-history");if(!e||e.dataset.ready==="1")return;e.dataset.ready="1",document.getElementById("stch-history-source")?.addEventListener("change",r=>{a.historySource=r.currentTarget.value,a.historyMarketHashName="",V(""),zi()}),document.getElementById("stch-history-card")?.addEventListener("change",r=>{a.historyMarketHashName=r.currentTarget.value}),document.getElementById("stch-history-add")?.addEventListener("click",qi),document.getElementById("stch-history-manual")?.addEventListener("keydown",r=>{r.key==="Enter"&&qi()}),document.getElementById("stch-history-refresh")?.addEventListener("click",r=>{if(a.historyRefreshing){Mn();return}r.currentTarget.classList.contains("disabled")||Cd()}),e.querySelectorAll("[data-history-range]").forEach(r=>{r.addEventListener("click",()=>{a.historyRange=r.dataset.historyRange,sr()})}),Vs?.disconnect();let t=document.getElementById("stch-history-list");t&&typeof ResizeObserver=="function"&&(Vs=new ResizeObserver(()=>{e.classList.contains("active")&&Ui()}),Vs.observe(t))}function ji(){Ws(),zi(),Gi(),sr()}function Vi(){Qe+=1,pt?.stop(),pt=null,a.historySource="scan",a.historyMarketHashName="",a.historyRange="7d",a.historyRefreshing=!1,Bt&&cancelAnimationFrame(Bt),Bt=0}var wd=Object.freeze({amp:"&",apos:"'",gt:">",lt:"<",nbsp:" ",quot:'"'});function Ki(e){return String(e??"").replace(/&(#(?:x[0-9a-f]+|\d+)|[a-z]+);/gi,(t,r)=>{if(r[0]!=="#")return wd[r.toLowerCase()]??t;let n=r[1]?.toLowerCase()==="x",s=Number.parseInt(r.slice(n?2:1),n?16:10);if(!Number.isSafeInteger(s)||s<0||s>1114111)return t;try{return String.fromCodePoint(s)}catch{return t}})}function En(e){return Ki(String(e??"").replace(/<[^>]*>/g," ")).replace(/\s+/g," ").trim()}function Lr(e,t){return new RegExp(`<([a-z][\\w:-]*)\\b[^>]*class=["'][^"']*\\b${t}\\b[^"']*["'][^>]*>([\\s\\S]*?)<\\/\\1>`,"i").exec(e)?.[2]??""}function Wi(e,t){let r=new RegExp(`\\b${t}\\s*=\\s*(["'])([\\s\\S]*?)\\1`,"i").exec(e);return r?Ki(r[2]):""}function kd(e){let t=e.match(/]*>/gi)||[];for(let r of t){let n=Wi(r,"href");if(/\/market\/listings\/\d+\//i.test(n))return n}return""}function Id(e){let t=/\/market\/listings\/(\d+)\/([^?#]+)/i.exec(e);if(!t)return null;let r;try{r=decodeURIComponent(t[2])}catch{return null}return r?{appid:t[1],marketHashName:r}:null}function Md(e){let t=String(e??"").trim();if(!/^\d+$/.test(t))return null;let r=Number(t);return Number.isSafeInteger(r)&&r>0?r:null}function Ed(e,t,r){let n=kd(e),s=Id(n);if(!s)return{error:"missing-listing-identity"};let o=Md(En(Lr(e,"market_listing_buyorder_qty")));if(!o)return{error:"invalid-remaining-quantity",identity:s};let i=Lr(e,"market_listing_inline_buyorder_qty"),c=Lr(e,"market_listing_my_price"),l=En(c.replace(i,"")),u=yr(l,r.minorDigits);if(!Number.isSafeInteger(u)||u<=0)return{error:"invalid-unit-price",identity:s};let d=Lr(e,"market_listing_item_name"),m=En(d)||s.marketHashName,p=/]*class=["'][^"']*\bmarket_listing_item_img\b[^"']*["'][^>]*>/i.exec(e)?.[0]||"";return{order:{orderId:t,...s,displayName:m,gameName:En(Lr(e,"market_listing_game_name")),imageUrl:Wi(p,"src"),listingUrl:n,remainingQuantity:o,unitPriceMinor:u,frozenMinor:u*o}}}function Nd(e,t={}){let r=String(e??""),n=/]*\bid=["']mybuyorder_(\d+)["'][^>]*>/gi,s=[],o;for(;o=n.exec(r);)s.push({index:o.index,orderId:o[1]});let i=[],c=[],l=new Set;for(let u=0;ur.gameName.localeCompare(n.gameName,"zh-CN")||r.displayName.localeCompare(n.displayName,"zh-CN")||r.marketHashName.localeCompare(n.marketHashName))}function Yi(e,t){return!e||!t||typeof t!="object"||Array.isArray(t)?!1:t.success===1}var{log:Ys,setStatus:Js}=ct,Xi="STCH_NO_BUY_ORDERS";function Zi(){let e=new Error("当前没有可用的最高求购价格");return e.code=Xi,e}function Ji(e){return e?.code===Xi}var{setStatus:Tr}=Nr;function De(){let e=he();if(Number.isInteger(e?.currencyId)&&e.currencyId>0)return e;let t=Number(a.cfg.currencyId);if(Number.isInteger(t)&&t>0)return xt(t);throw new Error("无法确认 Steam 钱包币种")}function ar(e,t=De().currencyId){return JSON.stringify([String(t),String(e||"")])}async function ec(){if(J(a.orderActionRunning))return;let e=document.getElementById("stch-order-appid"),t=String(e?.value||"").trim();if(!/^\d+$/.test(t)){Tr("请输入有效的 AppID,例如 4761370",!1);return}let r=!!document.getElementById("stch-order-manual-foil")?.checked,n=gn({appid:t,isFoil:r});a.orderActionRunning=!0,R();let s=a.cfg,o=new G(s.requestInterval,a,Tr,lt,{stopPredicate:()=>!1});try{Tr(`读取 ${t}${r?" 闪卡":""}`),lt(`[${t}] 开始读取${r?"闪卡":"普通卡"}卡牌页并查价`,"info");let i=await fn({appid:t,isFoil:r,gameName:n?.gameName||""},o);Kt(i,{select:!0,render:!0}),e&&(e.value=""),lt(`[${t}] ${i.gameName||""}: 已加入订购缓存,补全 ${i.hasIncompletePricing?"-":w(i.cheapestSetCostCents)} | 全套 ${i.hasIncompletePricing?"-":w(i.fullSetCostCents)} | 满级 ${i.hasIncompletePricing?"-":w(i.level5CostCents)}`,i.hasIncompletePricing?"warn":"ok")}catch(i){lt(`[${t}] 加入失败: ${i?.message||i}`,"err")}finally{o.stop(),a.orderActionRunning=!1,Tr(null),R()}}async function Xs(e=null){let t=e?null:new G(a.cfg.requestInterval,a,null,null,{stopPredicate:()=>!1}),r=e||t,n;try{n=(await r.fetch("https://steamcommunity.com/market/mylistings?start=0&count=100&l=english",{requestPolicy:"default"}))?.data}finally{t?.stop()}return Qi(n,{minorDigits:De().minorDigits})}async function Ad(e=null){let t=await Xs(e);if(t.diagnostics.length>0)throw new Error(`无法完整解析现有 Steam 订购单(${t.diagnostics.length} 项)`);let r=new Map;return t.orders.filter(n=>n.appid==="753").forEach(n=>{let s=r.get(n.marketHashName)||{quantity:0,orderIds:[]};s.quantity+=n.remainingQuantity,s.orderIds.push(n.orderId),r.set(n.marketHashName,s)}),r}function Rd(e){let t=ar(e),r=a.pendingOrderQuantities.get(t);return r?Date.now()-r.createdAt>120*1e3?(a.pendingOrderQuantities.delete(t),0):r.expectedQuantity:0}function Fr(e){return e==="conservative"?"保守":e==="balanced"?"平衡":e==="aggressive"?"抢单":e==="median"?"平均价格":e==="highest"?"求购最高":"在售最低"}function tc(e,t){if(Number.isInteger(e?.currency)&&e.currency>0&&e.currency!==t)throw new Error(`商品页币种不一致 (${e.currency}/${t})`);if(Number.isInteger(e?.currency)&&e.currency>0&&!(Number.isFinite(e.highestBuyCents)&&e.highestBuyCents>0))throw Zi()}async function Nn(e,t=null,r={}){let n=De(),s=ar(e,n.currencyId),o=a.highestBuyPrices.get(s);if(Number.isFinite(o?.priceCents)&&o.priceCents>0&&Date.now()-o.fetchedAt<3e4)return typeof r.onCache=="function"&&r.onCache(o),typeof r.onMetadata=="function"&&r.onMetadata({displayName:o.displayName||"",imageUrl:o.imageUrl||"",sellOrderCount:o.sellOrderCount??null,observedAt:o.fetchedAt}),o.priceCents;let i=t?null:new G(a.cfg.requestInterval,a,null,null,{stopPredicate:()=>!1}),c=t||i,l=u=>{if(u&&(typeof r.onRecord=="function"&&r.onRecord(u),r.persistMarketCache!==!1)){let d=ee(u);typeof r.onPersist=="function"&&r.onPersist(d)}};try{let u=Sr(e),m=(await c.fetch(u,{requestPolicy:"default"}))?.text||"",p=pn(m,e,{includeHistory:!1}),h=Date.now();p&&typeof r.onMetadata=="function"&&r.onMetadata({displayName:p.displayName||"",imageUrl:p.imageUrl||"",sellOrderCount:p.sellOrderCount,observedAt:h}),tc(p,n.currencyId);let f=p?.highestBuyCents!==null?p:null;if(f){if(f.currency!=null&&f.currency!==n.currencyId)throw new Error(`商品页币种不一致 (${f.currency}/${n.currencyId})`);if(f.highestBuyCents<=0)throw Zi();let g=Date.now();return l(cs(f,{appid:"753",marketHashName:e,currencyId:n.currencyId,currencyCode:n.code,observedAt:g})),a.highestBuyPrices.set(s,{currencyId:n.currencyId,priceCents:f.highestBuyCents,fetchedAt:g,displayName:p?.displayName||"",imageUrl:p?.imageUrl||"",sellOrderCount:p?.sellOrderCount??null}),f.highestBuyCents}throw new Error("商品页缺少可用的 SSR 订单簿数据")}finally{i?.stop()}}async function rc(e,t=null,r={}){let n=De(),s=ar(e,n.currencyId),o=a.marketOrderDepths.get(s);if(o?.depth&&Date.now()-o.fetchedAt<3e4)return o.depth;let i=t?null:new G(a.cfg.requestInterval,a,null,null,{stopPredicate:()=>!1}),c=t||i;try{let l=Sr(e),d=(await c.fetch(l,{requestPolicy:"default"}))?.text||"",{snapshot:m,depth:p}=Fo(d,e,{includeHistory:!1});if(!p)throw tc(m,n.currencyId),new Error("商品页缺少有效的完整买单深度");if(p.currencyId!==n.currencyId)throw new Error(`商品页币种不一致 (${p.currencyId}/${n.currencyId})`);let h=Date.now(),f=cs({eCurrency:p.currencyId,amtMaxBuyOrder:p.highestBuyMinor,amtMinSellOrder:p.lowestSellMinor},{appid:"753",marketHashName:e,currencyId:n.currencyId,currencyCode:n.code,observedAt:h});return f&&typeof r.onRecord=="function"&&r.onRecord(f),a.highestBuyPrices.set(s,{currencyId:n.currencyId,priceCents:p.highestBuyMinor,fetchedAt:h,displayName:m?.displayName||"",imageUrl:m?.imageUrl||"",sellOrderCount:p.sellOrderCount??m?.sellOrderCount??null}),a.marketOrderDepths.set(s,{depth:p,fetchedAt:h}),p}finally{i?.stop()}}async function _d(e,t,r){if(!a.cfg.parallelOrderPricingEnabled||!t.automatic&&t.priceSource!=="highest")return null;let n=[...new Set(e.map(({card:o})=>o.marketHashName))],s=new Map;return await Y(n,U(a.cfg),async o=>{try{let i=t.automatic?await rc(o,null,{onRecord:c=>r.push(c)}):await Nn(o,null,{persistMarketCache:!1,onRecord:c=>r.push(c)});s.set(o,{value:i})}catch(i){s.set(o,{error:i})}}),s}async function $d(e,t,r={}){let n=r.setStatus||Js,s=r.log||Ys,o=qt(a.cfg,a.automaticPricingDraft),i=o.priceSource,c=o.adjustment,l=Math.round((Number.isFinite(c)?c:0)*100),u=De(),d=Ae(u);if(!Number.isSafeInteger(d)||d<=0)throw new Error("无法确认当前币种的 Steam 市场最低价");let m=[],p={covered:0,missingPrice:0,missingHash:0,clamped:0,minimumClamped:0,sellGuardClamped:0,minimumPriceFallback:0},h=[],f=[];for(let y of e)for(let b of y.cards){if(!b.marketHashName){p.missingHash++;continue}let S=Bs(a.cfg.buyMode||"complete1",y.level,b.owned,ae(y));if(S<=0)continue;let M=t.get(b.marketHashName)?.quantity||0,E=Rd(b.marketHashName),x=Math.max(M,E),I=Math.max(0,S-x);if(I<=0){p.covered++;continue}h.push({info:y,card:b,quantity:I,reservedQuantity:x,targetQuantity:S})}let g=await _d(h,o,f);for(let y=0;yf.push(D)});A=un(z,{strategy:i,strategyRule:o.strategyRule,adjustmentMinor:l,minimumPriceMinor:d}),I=A?A.wallReferencePriceMinor??A.effectiveHighestBuyMinor??null:null,N=A?.finalPriceMinor??null,A||(B=new Error("无法根据订单簿计算智能定价"))}catch(L){B=L}}else if(i==="lowest"&&S.priceSource==="lowest"&&Number.isFinite(S.lowestCents)&&S.lowestCents>0)I=S.lowestCents;else if(i==="median"&&Number.isFinite(S.medianCents)&&S.medianCents>0)I=S.medianCents;else if(i==="highest"){n(`读取求购最高 ${y+1}/${h.length}: ${S.name}`);try{let L=g?.get(S.marketHashName);if(L?.error)throw L.error;I=g?L?.value??null:await Nn(S.marketHashName,r.queue||null,{persistMarketCache:!1,onRecord:z=>f.push(z)})}catch(L){B=L}}if(I==null)if(a.cfg.minimumPriceFallback&&(!B||Ji(B))){I=d,T=Ji(B)?"no-buy-orders":"missing-price",p.minimumPriceFallback++;let z=T==="no-buy-orders"?"当前无买单":"缺少所选价格";s(` ${b.gameName} · ${S.name}: ${z},使用市场最低价 ${w(d)}`,"warn")}else{B&&s(` ${b.gameName} · ${S.name}: ${B?.message||B},已跳过`,"warn"),p.missingPrice++;continue}if(N==null){let L=I+l;N=Math.max(d,L),N!==L&&(p.clamped++,p.minimumClamped++)}else A?.wasMinimumClamped&&(p.clamped++,p.minimumClamped++),A?.wasSellGuardClamped&&(p.clamped++,p.sellGuardClamped++);m.push({appid:b.appid,gameName:b.gameName,cardName:S.name,marketHashName:S.marketHashName,quantity:M,reservedQuantity:E,targetQuantity:x,basePriceCents:I,unitPriceCents:N,automaticPricing:o.automatic,strategyOffsetCents:A&&I!=null?A.strategyBasePriceMinor-I:0,wallClassification:T||A?.classification||null,isolatedHighPrice:A?.detection?.isolation?.classification==="isolated-high",originalHighestBuyCents:A?.highestBuyMinor??null,effectiveHighestBuyCents:A?.effectiveHighestBuyMinor??null,minimumPriceFallback:T!==null,minimumFallbackReason:T,totalPriceCents:N*M})}return ee(f),{plan:m,skipped:p,priceSource:i,adjustmentCents:l,minimumCents:d,automaticPricing:o.automatic,strategyRule:o.strategyRule||null}}function Pd(e,t){return new Promise(r=>{let{plan:n,skipped:s,priceSource:o,adjustmentCents:i,minimumCents:c,automaticPricing:l,strategyRule:u}=e,d=document.createElement("div");d.id="stch-order-dialog-backdrop";let m=n.reduce((x,I)=>x+I.quantity,0),p=n.reduce((x,I)=>x+I.totalPriceCents,0),h=new Set(n.map(x=>`${x.appid}:${x.gameName}`)).size,f=i>=0?`+${w(i)}`:w(i),g=x=>x>=0?`+${w(x)}`:w(x),y=l?`价格基准 智能定价 · ${Fr(o)} · 有墙调整 ${g(u?.wallOffsetMinor||0)} · 无墙调整 ${g(u?.noWallOffsetMinor||0)}`:`价格基准 ${Fr(o)} · 买价调整 ${f}`;d.innerHTML=`

确认提交长期订购单

游戏 ${h}/${t} 个 · 卡牌种类 ${n.length} · 数量 ${m} 张 · 新增最高占用 ${w(p)}
${y}
取消
提交订购单
`;let b=d.querySelector(".stch-order-list");n.forEach(x=>{let I=document.createElement("div");I.className="stch-order-item",I.title=`${x.gameName} · ${x.marketHashName}`,I.appendChild(P("",`${x.gameName} · ${x.cardName}`)),I.appendChild(P("",`${x.quantity} 张`));let N=x.minimumPriceFallback?x.minimumFallbackReason==="no-buy-orders"?"无买单 · 最低价回退":"缺价 · 最低价回退":x.automaticPricing?`${x.isolatedHighPrice?"孤立价已排除 · ":""}${x.wallClassification==="near-wall"?"有墙":"无墙"}`:"";I.appendChild(P("stch-order-price-basis",`${N?`${N} · `:""}基准 ${w(x.basePriceCents)}${x.automaticPricing?` · 调整 ${g(x.strategyOffsetCents)}`:""}`)),I.appendChild(P("",w(x.unitPriceCents))),b.appendChild(I)});let S=[];s.covered&&S.push(`${s.covered} 种卡牌已被现有订购单覆盖`),s.missingPrice&&S.push(`${s.missingPrice} 种卡牌缺少所选价格,已跳过`),s.missingHash&&S.push(`${s.missingHash} 种卡牌缺少市场标识,已跳过`),s.minimumPriceFallback&&S.push(`${s.minimumPriceFallback} 种卡牌缺少可用价格,已使用市场最低价 ${w(c)}`);let M=n.reduce((x,I)=>x+Number(I.isolatedHighPrice),0);M&&S.push(`${M} 种卡牌已排除顶部孤立高价`),s.minimumClamped&&S.push(`${s.minimumClamped} 种卡牌低于 Steam 最低价,已调整为 ${w(c)}`),s.sellGuardClamped&&S.push(`${s.sellGuardClamped} 种卡牌已限制在最低卖价以下`),d.querySelector(".stch-order-note").textContent=[...S,"订单长期有效"].join(";")+"。";let E=x=>{d.remove(),r(x)};d.querySelector('[data-action="cancel"]').addEventListener("click",()=>E(!1)),d.querySelector('[data-action="confirm"]').addEventListener("click",()=>E(!0)),d.addEventListener("click",x=>{x.target===d&&E(!1)}),document.body.appendChild(d)})}async function Od(e,t={}){let r=t.setStatus||Js,n=t.log||Ys,s=Pe();if(!s)throw new Error("未找到 Steam sessionid");if(Ce.g_bRequiresBillingInfo===!0)throw new Error("Steam 要求补充账单信息,请先在市场页面手动提交一次订单");let o=0;for(let i=0;i<41;i++){let c=new URLSearchParams({sessionid:s,currency:String(De().currencyId),appid:"753",market_hash_name:e.marketHashName,price_total:String(e.totalPriceCents),quantity:String(e.quantity),first_name:"",last_name:"",billing_address:"",billing_address_two:"",billing_country:"",billing_city:"",billing_state:"",billing_postal_code:"",save_my_address:"0",confirmation:String(o||0)}),l=await window.fetch("https://steamcommunity.com/market/createbuyorder/",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},body:c.toString()}),u=await l.text(),d=null;try{d=JSON.parse(u)}catch{}if(d?.success===1)return d;if(d?.need_confirmation&&d?.confirmation?.confirmation_id){o=d.confirmation.confirmation_id,i===0&&(n(` ${e.cardName}: 等待 Steam 移动确认`,"warn"),r(`请在 Steam 移动应用中确认: ${e.cardName}`)),await new Promise(m=>setTimeout(m,1500));continue}throw new Error(d?.message||`提交失败 (${l.status})`)}throw new Error("等待 Steam 移动确认超时")}async function nc(e="scan"){let t=e==="order",r=t?Tr:Js,n=t?lt:Ys,s=t?nt():rt();if(a.orderSubmissionRunning)return;if(s.length===0){r("请先勾选要提交订购单的卡组",!1);return}let o=new G(a.cfg.requestInterval,a,r,n,{stopPredicate:()=>!1}),i={setStatus:r,log:n,queue:o};a.orderSubmissionRunning=!0,R();let c=0,l=0,u=null;try{r("读取现有订购单");let d=await Ad(o),m=await $d(s,d,i);if(m.plan.length===0){u=`无需提交订购单:已有订单已覆盖,或没有可用的${Fr(m.priceSource)}`,n(u,"warn");return}if(!await Pd(m,s.length)){u="已取消提交订购单";return}for(let h=0;hsetTimeout(g,500))}u=`长期订购单提交结束: 成功 ${c}, 失败 ${l}`,n(u,l?"warn":"ok")}catch(d){u=`无法提交长期订购单: ${d?.message||d}`,n(u,"err")}finally{o.stop(),a.orderSubmissionRunning=!1,t&&u?r(u,!1):r(null),R()}}async function sc(){return nc("scan")}async function ac(){return nc("order")}var Bd=600*1e3;function K(e,t="",r=""){let n=document.createElement(e);return t&&(n.className=t),r&&(n.textContent=r),n}function Re(e,t=""){let r=document.getElementById("stch-active-orders-status");r&&(r.textContent=e||"",r.className=`stch-status-text${t?` ${t}`:""}`,r.style.display=e?"":"none")}function oc(e,t=""){let r=document.getElementById("stch-active-orders-log");if(!r)return;r.style.display="";let n=K("div",t,e);r.appendChild(n),r.scrollTop=r.scrollHeight}function Ld(){try{let e=De(),t=Ae(e);if(!Number.isInteger(e?.currencyId)||!Number.isSafeInteger(t)||t<=0)return null;let r=qt({...a.cfg,automaticPricingEnabled:!0},a.cfg.automaticPricingEnabled?a.automaticPricingDraft:null),n=Number(r.adjustment);return{currencyId:e.currencyId,minimumPriceMinor:t,strategy:r.priceSource,strategyRule:r.strategyRule,adjustmentMinor:Math.round((Number.isFinite(n)?n:0)*100)}}catch{return null}}function Td(e,t){if(e.appid!=="753")return{available:!1,label:"非社区物品,暂无定价缓存",className:"unavailable"};if(!t)return{available:!1,label:"无法确认钱包币种",className:"unavailable"};let r=ar(e.marketHashName,t.currencyId),n=a.marketOrderDepths.get(r)?.depth;if(!n)return{available:!1,label:"暂无智能定价缓存",className:"unavailable"};let s=un(n,{strategy:t.strategy,strategyRule:t.strategyRule,adjustmentMinor:t.adjustmentMinor,minimumPriceMinor:t.minimumPriceMinor});if(!s?.finalPriceMinor)return{available:!1,label:"缓存无法生成建议价",className:"unavailable"};let i=(e.remainingQuantity>0?Math.round(e.frozenMinor/e.remainingQuantity):e.minPriceMinor)-s.finalPriceMinor,c=i>0?"+":"−";return{available:!0,suggestedMinor:s.finalPriceMinor,deltaMinor:i,label:i===0?`与建议价 ${w(s.finalPriceMinor)} 一致`:`${i>0?"高于":"低于"}建议价 ${c}${w(Math.abs(i))}`,className:i>0?"high":i<0?"low":"matched"}}function ea(){return a.activeOrdersGameFilter==="all"?a.activeBuyOrderGroups:a.activeBuyOrderGroups.filter(e=>(e.gameName||`App ${e.appid}`)===a.activeOrdersGameFilter)}function ic(e){let t=Date.now(),r=De().currencyId;e.forEach(n=>{let s=a.activeOrderLowestPrices.get(n.key);if(!s||s.currencyId!==r||t-s.fetchedAt>Bd){s&&a.activeOrderLowestPrices.delete(n.key);return}n.lowestSellMinor=s.lowestSellMinor,n.lowestSellState="ready"})}function cc(e=ea()){let t=document.getElementById("stch-active-orders-select-all");if(!t)return;let r=e.filter(n=>a.selectedActiveBuyOrderGroups.has(n.key)).length;t.checked=e.length>0&&r===e.length,t.indeterminate=r>0&&rs.gameName||`App ${s.appid}`))].sort((s,o)=>s.localeCompare(o,"zh-CN"));a.activeOrdersGameFilter!=="all"&&!t.includes(a.activeOrdersGameFilter)&&(a.activeOrdersGameFilter="all");let r=document.createDocumentFragment(),n=document.createElement("option");n.value="all",n.textContent=`全部游戏 (${t.length})`,r.appendChild(n),t.forEach(s=>{let o=document.createElement("option");o.value=s,o.textContent=s,r.appendChild(o)}),e.replaceChildren(r),e.value=a.activeOrdersGameFilter}function Dd(e){return e.minPriceMinor===e.maxPriceMinor?w(e.minPriceMinor):`${w(e.minPriceMinor)}–${w(e.maxPriceMinor)}`}function lc(e){return Number.isSafeInteger(e.lowestSellMinor)&&e.lowestSellMinor>0?w(e.lowestSellMinor):e.lowestSellState==="loading"?"查询中":e.lowestSellState==="missing"?"无数据":e.lowestSellState==="failed"?"失败":"—"}function Hd(e){let t=e._lowestSellCell;t?.isConnected&&(t.className=`stch-active-order-value stch-active-order-lowest ${e.lowestSellState||"idle"}`,t.textContent=lc(e))}function uc(e=ea()){let t=a.activeBuyOrderGroups,r=t.reduce((c,l)=>c+l.remainingQuantity,0),n=t.reduce((c,l)=>c+l.frozenMinor,0),s=t.filter(c=>a.selectedActiveBuyOrderGroups.has(c.key)),o=s.reduce((c,l)=>c+l.frozenMinor,0),i=document.getElementById("stch-active-orders-summary");i&&(i.textContent=`${t.length} 项 · 剩余 ${r} 件 · 冻结 ${w(n)}${e.length===t.length?"":` · 当前显示 ${e.length} 项`}${s.length?` · 已选冻结 ${w(o)}`:""}`),cc(e),R()}var Zs=0;function qd(){Zs||(Zs=requestAnimationFrame(()=>{Zs=0,uc()}))}function zd(e,t){let r=K("div","stch-active-order-row");r.dataset.groupKey=e.key,r.classList.toggle("selected",a.selectedActiveBuyOrderGroups.has(e.key));let n=K("a","stch-active-order-item");if(n.href=e.listingUrl,n.target="_blank",n.rel="noopener noreferrer",e.imageUrl){let h=K("img","stch-active-order-image");h.src=e.imageUrl,h.alt="",n.appendChild(h)}let s=K("span","stch-active-order-names");s.appendChild(K("span","stch-active-order-name",e.displayName)),s.appendChild(K("span","stch-active-order-game",e.gameName||e.marketHashName)),n.appendChild(s),r.appendChild(n);let o=K("div","stch-active-order-metric");o.appendChild(K("span","stch-active-order-value",Dd(e))),r.appendChild(o);let i=K("div",`stch-active-order-value stch-active-order-lowest ${e.lowestSellState||"idle"}`,lc(e));e._lowestSellCell=i,r.appendChild(i);let c=K("div","stch-active-order-metric");c.appendChild(K("span","stch-active-order-value",String(e.remainingQuantity))),r.appendChild(c);let l=K("div","stch-active-order-metric");l.appendChild(K("span","stch-active-order-value",w(e.frozenMinor))),r.appendChild(l);let u=Td(e,t),d=K("div",`stch-active-order-smart ${u.className}`,u.label);u.available&&(d.title=`使用当前智能定价设置与已缓存订单簿计算;建议价 ${w(u.suggestedMinor)}`),r.appendChild(d);let m=K("label","stch-active-order-select"),p=K("input","stch-active-order-cb");return p.type="checkbox",p.checked=a.selectedActiveBuyOrderGroups.has(e.key),p.setAttribute("aria-label",`选择 ${e.displayName}`),m.appendChild(p),r.appendChild(m),p.addEventListener("change",()=>{p.checked?a.selectedActiveBuyOrderGroups.add(e.key):a.selectedActiveBuyOrderGroups.delete(e.key),r.classList.toggle("selected",p.checked),qd()}),r}function ft(){let e=document.getElementById("stch-active-orders-list");if(!e)return;Fd();let t=ea();if(e.innerHTML="",t.length===0)e.appendChild(K("div","stch-active-orders-empty",a.activeBuyOrderGroups.length?"当前筛选没有结果":"暂无已下订购单"));else{let r=document.createDocumentFragment(),n=Ld(),s=K("div","stch-active-order-header");["物品","买价","最低售价","剩余","冻结金额","智能定价"].forEach(l=>{s.appendChild(K("span","",l))});let o=K("label","stch-active-order-select-all-wrap"),i=K("input","stch-active-order-select-all");i.id="stch-active-orders-select-all",i.type="checkbox",i.setAttribute("aria-label","全选当前游戏的订购单"),o.appendChild(i),s.appendChild(o),i.addEventListener("change",()=>{t.forEach(l=>{i.checked?a.selectedActiveBuyOrderGroups.add(l.key):a.selectedActiveBuyOrderGroups.delete(l.key)}),ft()}),r.appendChild(s);let c=null;t.forEach(l=>{let u=l.gameName||`App ${l.appid}`;u!==c&&(r.appendChild(K("div","stch-active-order-game-separator",u)),c=u),r.appendChild(zd(l,n))}),e.appendChild(r)}uc(t)}async function dc(){if(ut(a.activeOrdersLoading||a.activeOrderPriceQueryRunning))return;a.activeOrdersLoading=!0,R(),Re("正在读取 Steam 市场订购单…");let e=new G(a.cfg.requestInterval,a,null,null,{stopPredicate:()=>!1});try{let t=await Xs(e);a.activeBuyOrders=t.orders,a.activeBuyOrderGroups=Qs(t.orders),ic(a.activeBuyOrderGroups),a.activeOrdersLoadedAt=t.observedAt;let r=new Set(a.activeBuyOrderGroups.map(n=>n.key));a.selectedActiveBuyOrderGroups.forEach(n=>{r.has(n)||a.selectedActiveBuyOrderGroups.delete(n)}),ft(),Re(t.diagnostics.length?`已读取 ${t.orders.length} 笔;另有 ${t.diagnostics.length} 行无法确认,未纳入操作`:`已读取 ${t.orders.length} 笔订购单`,t.diagnostics.length?"warn":"ok")}catch(t){Re(`读取失败:${t?.message||t}`,"err")}finally{e.stop(),a.activeOrdersLoading=!1,cc(),R()}}async function Gd(){if(J(a.activeOrdersLoading||a.activeOrderPriceQueryRunning))return;let e=a.activeBuyOrderGroups.filter(o=>a.selectedActiveBuyOrderGroups.has(o.key));if(e.length===0)return;a.activeOrderPriceQueryRunning=!0,e.forEach(o=>{o.lowestSellState="loading"}),ft(),R();let t=oe(U(a.cfg),()=>new G(a.cfg.requestInterval,a,o=>Re(o||"正在查询最低售价"),null,{stopPredicate:()=>!1})),r=0,n=0,s=[];try{let o=De().currencyId,i=0;await Y(e,U(a.cfg),async(c,l)=>{Re(`正在查询最低售价 ${l+1}/${e.length}:${c.displayName}`);let u=await me(c.marketHashName,t,{appid:c.appid,currencyId:o,preferListing:!0,persistMarketCache:!1});u?.record&&s.push(u.record);let d=Number(u?.record?.lowestSellMinor);Ie(u)&&Number.isSafeInteger(d)&&d>0?(c.lowestSellMinor=d,c.lowestSellState="ready",a.activeOrderLowestPrices.set(c.key,{lowestSellMinor:d,currencyId:o,fetchedAt:Date.now()}),r+=1):(c.lowestSellMinor=null,c.lowestSellState=je(u)||!Cr(u)?"missing":"failed",n+=1),Hd(c),i++,Re(`正在查询最低售价 ${i}/${e.length}`)}),Re(n?`最低售价查询完成:成功 ${r} 项,缺失或失败 ${n} 项`:`最低售价查询完成:${r} 项`,n?"warn":"ok")}catch(o){Re(`最低售价查询中断:${o?.message||o}`,"err")}finally{t.stop(),s.length>0&&ee(s),e.forEach(o=>{o.lowestSellState==="loading"&&(o.lowestSellState="failed")}),a.activeOrderPriceQueryRunning=!1,ft(),R()}}async function Ud(e){let t=Pe();if(!t)throw new Error("未找到 Steam sessionid");let r=await window.fetch("https://steamcommunity.com/market/cancelbuyorder/",{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8"},body:new URLSearchParams({sessionid:t,buy_orderid:e.orderId}).toString()}),n=await r.text(),s=null;try{s=n?JSON.parse(n):null}catch{}if(!Yi(r.ok,s))throw new Error(`Steam 返回未确认结果(HTTP ${r.status})`)}async function jd(e){if(xe()||e.length===0)return;let t=e.flatMap(l=>l.orders),r=t.reduce((l,u)=>l+u.frozenMinor,0),n=t.reduce((l,u)=>l+u.remainingQuantity,0);if(!confirm(`撤销 ${e.length} 项(${n} 件,冻结 ${w(r)})?`))return;a.activeOrdersCancelling=!0,R();let s=document.getElementById("stch-active-orders-log");s&&(s.innerHTML="",s.style.display="");let o=new Set,i=[];for(let l=0;lsetTimeout(d,450))}a.activeBuyOrders=a.activeBuyOrders.filter(l=>!o.has(l.orderId)),a.activeBuyOrderGroups=Qs(a.activeBuyOrders),ic(a.activeBuyOrderGroups);let c=new Set(a.activeBuyOrderGroups.map(l=>l.key));if(a.selectedActiveBuyOrderGroups.forEach(l=>{c.has(l)||a.selectedActiveBuyOrderGroups.delete(l)}),a.activeOrdersCancelling=!1,ft(),R(),i.length){let l=i.slice(0,3).map(u=>`${u.order.displayName}: ${u.message}`).join(";");Re(`撤单完成:成功 ${o.size},失败 ${i.length}。${l}`,"warn")}else Re(`撤单完成:成功 ${o.size} 笔`,"ok")}function ta(){let e=document.getElementById("stch-active-orders-list");!e||e.dataset.ready==="1"||(e.dataset.ready="1",ot(e,{checkboxSelector:".stch-active-order-cb",activationSelector:".stch-active-order-select"}),document.getElementById("stch-active-orders-game")?.addEventListener("change",t=>{a.activeOrdersGameFilter=t.currentTarget.value,ft()}),document.getElementById("stch-active-orders-refresh")?.addEventListener("click",()=>{dc()}),document.getElementById("stch-active-orders-query-prices")?.addEventListener("click",()=>{Gd()}),document.getElementById("stch-active-orders-cancel-selected")?.addEventListener("click",()=>{let t=a.activeBuyOrderGroups.filter(r=>a.selectedActiveBuyOrderGroups.has(r.key));jd(t)}),ft())}function mc(){ta(),!a.activeOrdersLoadedAt&&!a.activeOrdersLoading?dc():ft()}function pc(){a.activeBuyOrders=[],a.activeBuyOrderGroups=[],a.selectedActiveBuyOrderGroups=new Set,a.activeOrdersLoading=!1,a.activeOrderPriceQueryRunning=!1,a.activeOrdersCancelling=!1,a.activeOrdersLoadedAt=0,a.activeOrdersGameFilter="all",a.activeOrderLowestPrices=new Map}var{log:X,setStatus:Dr,setProgress:Rn,hideProgress:fc}=di;function hc(){return a.craftResults.filter(e=>e.selected&&e.maxCraftable>0).map(e=>({result:e,count:a.cfg.craftMode==="max"?e.maxCraftable:Math.max(0,Math.min(e.maxCraftable,parseInt(e.craftCount,10)||0))})).filter(e=>e.count>0)}function An(){let e=document.getElementById("stch-craft-summary-row"),t=document.getElementById("stch-craft-summary");if(!e||!t)return;if(a.craftResults.length===0){e.style.display="none",t.textContent="";return}let r=hc(),n=r.reduce((o,i)=>o+i.count,0),s=a.craftResults.reduce((o,i)=>o+i.maxCraftable,0);t.innerHTML=`共 ${a.craftResults.length} 个可合成徽章 · 可合成 ${s} 次 · 已选择 ${r.length} 个 / ${n} 次`,e.style.display=""}function _e(){let e=document.getElementById("stch-craft-list");if(!e)return;if(ot(e,{checkboxSelector:".stch-result-cb",activationSelector:".stch-result-cb, .stch-check-hit, .stch-check",rowSelector:".stch-craft-row",excludeSelector:"#stch-craft-select-all"}),e.innerHTML="",a.craftResults.length===0){let o=document.createElement("div");o.className="stch-game-row",o.textContent=a.craftScanning?"正在读取可合成徽章...":"尚未扫描可合成徽章",e.appendChild(o),An(),Nt();return}let t=document.createElement("div");t.className="stch-game-row stch-craft-row stch-row-header",t.innerHTML=` 游戏ID 游戏名 当前 可合成 本次 目标 状态 `,e.appendChild(t);let r=t.querySelector("#stch-craft-select-all"),n=a.craftResults.filter(o=>o.selected).length;r.checked=n===a.craftResults.length,r.indeterminate=n>0&&n{a.craftResults.forEach(i=>{i.maxCraftable<=0||(i.selected=o,o&&i.craftCount<=0&&(i.craftCount=i.maxCraftable))}),_e()};r.addEventListener("change",o=>{o.stopPropagation(),s(o.target.checked)}),r.closest(".stch-check").addEventListener("click",o=>{o.stopPropagation(),!(o.target===r||r.disabled)&&(r.checked=!r.checked,s(r.checked))}),a.craftResults.forEach(o=>{let i=document.createElement("div");i.className="stch-game-row stch-craft-row",i.dataset.key=te(o);let c=P("stch-appid",o.appid),l=P("stch-name",`${o.gameName}${o.isFoil?"(闪亮)":""}`);l.title=o.gameName;let u=P("stch-level",`Lv${o.level}`),d=P("stch-craft-available",`${o.maxCraftable} 次`),m=document.createElement("span");m.className="stch-craft-count";let p=document.createElement("input");p.className="stch-input",p.type="number",p.min="0",p.max=String(o.maxCraftable),p.step="1";let h=a.cfg.craftMode==="max"?o.maxCraftable:Math.max(0,Math.min(o.maxCraftable,o.craftCount||0));p.value=String(h),p.title=a.cfg.craftMode==="max"?"一次提交当前可合成最大次数":"输入本次要逐级合成的次数",p.disabled=a.craftScanning||a.craftActionRunning||a.surplusActionRunning||a.surplusScanning||a.grindScanning||a.cfg.craftMode==="max"||o.maxCraftable<=0,m.appendChild(p);let f=P("stch-craft-target",`Lv${o.level+(parseInt(p.value,10)||0)}`),g=P(`stch-craft-status ${o.statusType||""}`.trim(),o.status||"待合成"),y=document.createElement("span");y.className="stch-check";let b=document.createElement("input");b.className="stch-result-cb",b.type="checkbox",b.checked=!!o.selected,b.setAttribute("aria-label",`选择 ${o.gameName||o.appid}`),b.disabled=a.craftScanning||a.craftActionRunning||a.surplusActionRunning||a.surplusScanning||a.grindScanning||o.maxCraftable<=0,y.appendChild(yn(b));let S=M=>{o.selected=M,o.selected&&o.craftCount<=0&&(o.craftCount=o.maxCraftable,p.value=String(o.craftCount),f.textContent=`Lv${o.level+o.craftCount}`),An(),Nt()};b.addEventListener("change",M=>{M.stopPropagation(),S(b.checked)}),y.addEventListener("click",M=>{M.stopPropagation(),!(M.target===b||b.disabled)&&(b.checked=!b.checked,S(b.checked))}),p.addEventListener("input",()=>{let M=Math.max(0,Math.min(o.maxCraftable,parseInt(p.value,10)||0));o.craftCount=M,o.selected=M>0,b.checked=o.selected,f.textContent=`Lv${o.level+M}`,An(),Nt()}),p.addEventListener("change",()=>{p.value=String(o.craftCount)}),i.append(c,l,u,d,m,f,g,y),e.appendChild(i)}),An(),Nt()}function _n(e){ut(a.craftScanning||a.craftActionRunning)||e==="one"&&a.cfg.craftMode==="max"||(a.craftResults.forEach(t=>{e==="clear"?(t.craftCount=0,t.selected=!1):t.maxCraftable>0&&(t.craftCount=e==="one"?1:t.maxCraftable,t.selected=!0)}),_e())}async function gc(){if(ut(a.craftScanning))return;let e=Q();if(!e){X("未找到 Steam 个人资料地址","err");return}a.craftScanning=!0,a.craftStopRequested=!1,a.craftResults=[];let t=document.getElementById("stch-craft-log");t&&(t.innerHTML=""),_e(),R(),Dr("扫描可合成徽章");let r=a.cfg,n=U(r),s=oe(n,()=>new G(r.requestInterval,a,null,X,{stopPredicate:u=>!!u?.craftStopRequested}));a.craftQueue=s;let o=Math.max(1,parseInt(document.getElementById("stch-craft-max-pages")?.value,10)||r.maxBadgePages),i=[],c=new Set,l=new Set((r.blacklist||"").split(",").map(u=>u.trim()).filter(Boolean));try{for(let m=1;m<=o&&!a.craftStopRequested;m++){Rn(m-1,o,`读取徽章页 ${m}/${o}`);let p=await s.fetch(`${e}/badges/?sort=p&p=${m}`),h=to(p.text||"");for(let y of h){let b=te(y);if(!c.has(b)){if(c.add(b),l.has(String(y.appid))){X(`[${y.appid}] ${y.gameName}: 位于游戏/AppID黑名单,跳过`,"info");continue}i.push(y)}}if(X(`徽章页 ${m}: 找到 ${h.length} 个可合成入口`,"info"),!new DOMParser().parseFromString(p.text||"","text/html").querySelector(`a.pagebtn[href*="p=${m+1}"]`))break}if(a.craftStopRequested){X("已停止扫描","warn");return}if(i.length===0){X("没有找到可立即合成的徽章","warn");return}X(`找到 ${i.length} 个候选徽章,开始读取卡组数量`);let u=new Array(i.length),d=0;if(await Y(i,n,async(m,p)=>{if(!a.craftStopRequested){Rn(d,i.length,`读取卡组 ${d+1}/${i.length} · ${m.gameName}`),Dr(`读取卡组: ${m.gameName}`);try{let h=await s.fetch(Ze(e,m.appid,m,{language:"english"})),f=ro(h.text||"",m);if(f.maxCraftable<=0){X(`[${m.appid}] ${m.gameName}: 页面已不可合成,跳过`,"warn");return}u[p]=f,X(`[${f.appid}] ${f.gameName}: Lv${f.level},可合成 ${f.maxCraftable} 次`,"ok")}catch(h){a.craftStopRequested||X(`[${m.appid}] ${m.gameName}: 读取失败 ${h?.message||h?.status||h}`,"err")}finally{d++,Rn(d,i.length,`读取卡组 ${d}/${i.length}`)}}}),a.craftResults.push(...u.filter(Boolean)),a.craftResults.sort((m,p)=>m.gameName.localeCompare(p.gameName,"zh-CN")),_e(),a.craftStopRequested)X("已停止扫描","warn");else{let m=a.craftResults.reduce((p,h)=>p+h.maxCraftable,0);X(`扫描完成:${a.craftResults.length} 个徽章,可合成 ${m} 次`,"ok")}}catch(u){a.craftStopRequested||X(`扫描中断: ${u?.message||u?.status||u}`,"err")}finally{s.stop(),a.craftQueue=null,a.craftScanning=!1,a.craftStopRequested=!1,fc(),Dr(null),_e(),R()}}function Vd(e,t){return new Promise(r=>{let n=e.reduce((l,u)=>l+u.count,0),s=t==="max"?"一次升满":"逐级升级",o=document.createElement("div");o.id="stch-order-dialog-backdrop",o.innerHTML=`

确认批量合成徽章

游戏 ${e.length} 个 · 合成 ${n} 次 · 预计增加 ${n*100} XP · 模式 ${s}
${t==="max"?"每个游戏一次请求":"每级一次请求"};结果不明时停止。
取消
开始合成
`;let i=o.querySelector(".stch-order-list");e.forEach(l=>{let u=document.createElement("div");u.className="stch-order-item stch-craft-dialog-item",u.appendChild(P("",l.result.gameName)),u.appendChild(P("",`Lv${l.result.level}`)),u.appendChild(P("",`${l.count} 次`)),u.appendChild(P("",`Lv${l.result.level+l.count}`)),i.appendChild(u)});let c=l=>{o.remove(),r(l)};o.querySelector('[data-action="cancel"]').addEventListener("click",()=>c(!1)),o.querySelector('[data-action="confirm"]').addEventListener("click",()=>c(!0)),o.addEventListener("click",l=>{l.target===o&&c(!1)}),document.body.appendChild(o)})}async function Kd(e,t=1){let r=Q(),n=Pe();if(!r)throw new Error("未找到 Steam 个人资料地址");if(!n)throw new Error("未找到 Steam sessionid");let s=Math.max(1,parseInt(t,10)||1);if(s>e.maxCraftable)throw new Error("合成次数超过 Steam 当前允许的最大值");let o=new URLSearchParams({appid:String(e.appid),series:"1",border_color:e.isFoil?"1":"0",levels:String(s),sessionid:n}),i=new AbortController,c=setTimeout(()=>i.abort(),15e3),l;try{l=await window.fetch(`${r}/ajaxcraftbadge/`,{method:"POST",credentials:"include",headers:{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8","X-Requested-With":"XMLHttpRequest"},body:o.toString(),signal:i.signal})}catch(p){clearTimeout(c);let h=p?.name==="AbortError"?"请求超时":`网络错误: ${p?.message||p}`,f=new Error(h);throw f.uncertain=!0,f}let u;try{u=await l.text()}catch(p){let h=new Error(`响应读取失败: ${p?.message||p}`);throw h.uncertain=!0,h}finally{clearTimeout(c)}let d=null;try{d=JSON.parse(u)}catch{let h=new Error(`Steam 返回了无法识别的响应 (${l.status})`);throw h.status=l.status,h.uncertain=l.ok||l.status>=500,h}if(l.ok&&d?.success===1)return d;let m=new Error(d?.message||`合成失败 (${l.status||"unknown"})`);throw m.status=l.status,m.uncertain=l.status>=500,m}async function bc(){if(ut(a.craftScanning||a.craftActionRunning))return;let e=hc();if(e.length===0)return;let t=a.cfg.craftMode==="max"?"max":"step";if(!await Vd(e,t))return;a.craftActionRunning=!0,a.craftStopRequested=!1,R(),_e();let n=e.reduce((c,l)=>c+l.count,0),s=0,o=0,i=!1;try{for(let c of e){if(a.craftStopRequested||i)break;let l=c.result,u=0;for(l.status="合成中",l.statusType="warn",_e();uh.title).filter(Boolean);X(`✓ ${l.gameName}: 已合成 ${d} 次,至 Lv${l.level}${p.length?`,获得 ${p.join("、")}`:""}`,"ok"),Rn(s,n,`已合成 ${s}/${n} 次`)}catch(m){o++,l.status=m.uncertain?"结果不确定":"失败",l.statusType="err",X(`✗ ${l.gameName}: ${m?.message||m}`,"err"),m.uncertain?(i=!0,a.craftStopRequested=!0,X("请求可能已经被 Steam 执行,已停止后续合成;请刷新或重新扫描确认实际等级","warn")):m.status===429&&(a.craftStopRequested=!0,X("Steam 返回 429,已停止后续合成;建议等待至少半小时或者更换 IP 后再继续","warn"));break}ssetTimeout(m,Math.max(200,a.cfg.craftInterval)))}l.selected=!1,l.craftCount=0,(!l.statusType||l.statusType!=="err")&&(u===c.count?(l.status="已完成",l.statusType="ok"):u>0?(l.status="部分完成",l.statusType="warn"):a.craftStopRequested&&(l.status="已停止",l.statusType="warn")),_e()}a.craftStopRequested&&!i&&X("已按请求停止后续合成","warn"),X(`批量合成结束:成功 ${s}/${n} 次,失败 ${o} 个游戏`,o||a.craftStopRequested?"warn":"ok")}finally{a.craftActionRunning=!1,a.craftStopRequested=!1,fc(),Dr(null),_e(),R()}}function yc(){!a.craftScanning&&!a.craftActionRunning||(a.craftStopRequested=!0,a.craftQueue?.stop(),X(a.craftActionRunning?"已请求停止,将在当前合成请求结束后停止":"已请求停止扫描","warn"),Nt())}function or(e){let t=String(e?.market_hash_name||"").trim(),r=String(e?.name||"").trim();return t===Zr||/sack of gems/i.test(r)||/宝石袋|袋装宝石/.test(r)}function zr(e){let t=String(e?.market_hash_name||"").trim(),r=String(e?.name||"").trim(),n=String(e?.type||"").trim();return or(e)?!1:t==="Gems"||/^gems$/i.test(r)||/^宝石$/.test(r)||/steam gems?/i.test(n)||/^宝石$/.test(n)}function $e(e){return`${e?.classid||""}_${e?.instanceid||""}`}function Wd(e){return Array.isArray(e?.tags)?e.tags:[]}function Tt(e,t,r=null){return Wd(e).find(n=>String(n?.category||"")!==t?!1:r==null||String(n?.internal_name||"")===r)||null}function ra(e,t="96fx96f"){let r=String(e?.icon_url_large||e?.icon_url||"").trim();if(!r)return"";if(/^https?:\/\//i.test(r))return r;let n=t?`/${t}`:"";return`https://community.fastly.steamstatic.com/economy/image/${r}${n}`}function Hr(e,t){let r=String(e?.[t]||"").trim();return/^[0-9a-f]{6}$/i.test(r)?`#${r}`:""}function na(e){return!!Tt(e,"item_class","item_class_2")}function Qd(e){return!!Tt(e,"item_class","item_class_3")}function Yd(e){return!!Tt(e,"item_class","item_class_4")}function sa(e){return na(e)?"card":Qd(e)?"background":Yd(e)?"emoticon":"other"}function vc(e){let t=sa(e);return["background","emoticon"].includes(t)&&Number(e?.marketable)!==1&&Number(e?.tradable)!==1}function $n(e){let t=String(e?.market_fee_app||"").trim();if(/^\d+$/.test(t))return t;let r=Tt(e,"Game"),n=String(r?.internal_name||"").match(/^app_(\d+)$/);return n?n[1]:""}function qr(e){let t=Tt(e,"Game");return String(t?.localized_tag_name||"").trim()}function xc(e){return!!Tt(e,"cardborder","cardborder_1")}function Sc(e){return String(e||"").replace(/\s+/g," ").trim().toLowerCase()}function ht(e){let t=Number(e?.amount);return Number.isSafeInteger(t)&&t>0?t:0}function Cc(e,t,r){if(!r||!na(r))return!1;let n=String(r.market_hash_name||"").trim(),s=$n(r);if(!n||!s)return!1;let o=xc(r),i=`${s}_${o?1:0}`,c=e.get(i);c||(c={appid:s,isFoil:o,gameName:qr(r),cardsByHash:new Map,cardsByName:new Map,totalCount:0},e.set(i,c)),c.gameName||(c.gameName=qr(r));let l=aa(r),u=c.cardsByHash.get(n);if(u)!u.gemValue&&l&&(u.gemValue=l);else{u={appid:s,isFoil:o,gameName:c.gameName,name:String(r.name||n).trim(),marketHashName:n,imageUrl:ra(r),nameColor:Hr(r,"name_color"),backgroundColor:Hr(r,"background_color"),gemValue:l,totalCount:0,assets:[]},c.cardsByHash.set(n,u);let m=Sc(u.name);m&&!c.cardsByName.has(m)&&c.cardsByName.set(m,u)}let d=ht(t);return u.totalCount+=d,c.totalCount+=d,u.assets.push({assetid:String(t.assetid||""),contextid:String(t.contextid||"6"),classid:String(t.classid||""),instanceid:String(t.instanceid||""),amount:d,gemValue:l,marketable:Number(r.marketable)===1,tradable:Number(r.tradable)===1}),!0}function wc(e,t){if(t.marketHashName&&e.cardsByHash.has(t.marketHashName))return e.cardsByHash.get(t.marketHashName);let r=Sc(t.name);return r&&e.cardsByName.get(r)||null}function kc(e,t){let r=[...e].sort((o,i)=>{let c=Number(i.marketable)-Number(o.marketable);if(c)return c;let l=Number(i.tradable)-Number(o.tradable);return l||String(o.assetid).localeCompare(String(i.assetid),"en")}),n=[],s=t;for(let o of r){if(s<=0)break;let i=Math.min(o.amount,s);n.push({...o,selectedAmount:i}),s-=i}return n}function Pn(e){let t=e.map(n=>n.selectedAmount>1?`${n.assetid}x${n.selectedAmount}`:n.assetid),r=t.slice(0,3).join(", ");return{text:t.length>3?`${r} ...`:r,title:t.join(` `)}}function Jd(e){let t=document.createElement("div");return t.innerHTML=String(e??"").replace(//gi," "),on(t.textContent||t.innerText||String(e||"")).replace(/\u00a0/g," ").replace(/\s+/g," ").trim()}function Xd(e){let t=Jd(e).replace(/[,,]/g,"");if(!t)return 0;let n=t.match(/(?:turn(?:ed)?\s+into|convert(?:ed)?\s+into|worth|可分解为|可转换为|可转化为|转换为|转化为|分解为|分解成)[^\d]{0,40}(\d+)\s*(?:gems?|宝石)/i)||t.match(/(\d+)\s*(?:gems?|宝石)/i);return n?Math.max(0,parseInt(n[1],10)||0):0}function aa(e){let t=[];return["owner_descriptions","descriptions","owner_actions","actions"].forEach(r=>{(Array.isArray(e?.[r])?e[r]:[]).forEach(s=>{t.push(s?.value,s?.name,s?.link)})}),t.reduce((r,n)=>n==null?r:Math.max(r,Xd(n)),0)}function Ic(e){let t=[];["owner_actions","actions"].forEach(r=>{(Array.isArray(e?.[r])?e[r]:[]).forEach(s=>{s?.link&&t.push(String(s.link))})});for(let r of t){let n=r.match(/GetGooValue\s*\(([^)]*)\)/i);if(!n)continue;let s=n[1].split(",").map(l=>l.trim().replace(/^['"]|['"]$/g,""));if(s.length<5)continue;let o=s[s.length-3],i=s[s.length-2],c=s[s.length-1];if(/^\d+$/.test(o)&&/^\d+$/.test(i)&&/^\d+$/.test(c))return{appid:o,itemType:i,borderColor:c}}return null}function Mc(e){if(na(e))return xc(e)?"闪亮卡牌":"卡牌";let t=Tt(e,"item_class");return String(e?.type||t?.localized_tag_name||"物品").replace(/\s+/g," ").trim()}var{setStatus:Zd,log:em}=Et;async function Ec(e,t){let r=new Map,n=Ce.g_strLanguage||"schinese",s="",o=0,i=0,c=0,l=0;do{o++;let d=new URLSearchParams({l:n,count:"2000"});s&&d.set("start_assetid",s);let m=`https://steamcommunity.com/inventory/${e}/753/6?${d.toString()}`;Zd(`读取库存第 ${o} 页`);let h=(await t.fetch(m))?.data||{};if(h?.success!==1&&h?.success!==!0)throw new Error(h?.Error||h?.error||"Steam 未返回可用库存数据");i=Number(h.total_inventory_count||i)||i;let f=new Map;(Array.isArray(h.descriptions)?h.descriptions:[]).forEach(y=>{f.set($e(y),y)});let g=Array.isArray(h.assets)?h.assets:[];c+=g.length;for(let y of g){let b=f.get($e(y));Cc(r,y,b)&&(l+=ht(y))}em(`库存第 ${o} 页:读取 ${g.length} 件,累计卡牌 ${l} 张`,"info"),s=h.more_items&&h.last_assetid?String(h.last_assetid):""}while(s&&!a.surplusStopRequested);let u=[...r.values()].sort((d,m)=>{let p=(d.gameName||"").localeCompare(m.gameName||"","zh-CN");return p||(d.appid!==m.appid?Number(d.appid)-Number(m.appid):Number(d.isFoil)-Number(m.isFoil))});return{groups:u,totalInventoryCount:i,totalAssetsSeen:c,totalCards:l,cardTypeCount:u.reduce((d,m)=>d+m.cardsByHash.size,0)}}async function On(e){if(typeof GM_xmlhttpRequest=="function")return new Promise((r,n)=>{GM_xmlhttpRequest({method:"GET",url:e,timeout:2e4,anonymous:!1,withCredentials:!0,onload:s=>{s.status>=200&&s.status<300?r(s.responseText||""):n(new Error(`HTTP ${s.status}`))},onerror:()=>n(new Error("网络请求失败")),ontimeout:()=>n(new Error("网络请求超时"))})});let t=await window.fetch(e,{credentials:"include"});if(!t.ok)throw new Error(`HTTP ${t.status}`);return t.text()}async function Nc(e){let t=await On(e);try{return JSON.parse(t||"{}")}catch{throw new Error("返回内容不是 JSON")}}var Bn=null;async function Ac(e){if(!e)throw new Error("未找到 SteamID,无法读取库存");let t=Ce.g_strLanguage||"schinese",r="",n=0,s=0,o=0;do{let i=new URLSearchParams({l:t,count:"2000"});r&&i.set("start_assetid",r);let c=await Nc(`https://steamcommunity.com/inventory/${e}/753/6?${i.toString()}`);if(c?.success!==1&&c?.success!==!0)throw new Error(c?.Error||c?.error||"Steam 未返回库存数据");o=Number(c.total_inventory_count||o)||o;let l=new Map;(Array.isArray(c.descriptions)?c.descriptions:[]).forEach(u=>{l.set($e(u),u)});for(let u of Array.isArray(c.assets)?c.assets:[]){let d=l.get($e(u)),m=ht(u);or(d)?s+=m:zr(d)&&(n+=m)}r=c.more_items&&c.last_assetid?String(c.last_assetid):""}while(r);return{looseGems:n,sackCount:s,totalGems:n+s*1e3,totalInventoryCount:o}}async function tm(e){let t=e?null:new G(a.cfg.requestInterval,a,null,null,{stopPredicate:()=>!1}),r=e||t;try{let n=await me(Zr,r,{preferListing:!0,requestPolicy:{base:"priceoverview",retry429:!1}}),s=Ie(n);return{priceCents:s&&n.lowestSellCents||0,medianCents:s&&n.medianCents||0,source:s&&n.priceSource==="lowest"?"在售最低":s&&n.priceSource==="median"?"平均价格":"暂无价格",volume:s&&n.volume||0,currencyId:n?.currencyId||a.currencyContext?.currencyId||a.cfg.currencyId,observedAt:n?.observedAt||Date.now(),record:n?.record||null}}finally{t?.stop()}}function ir(e=null){return Bn||(Bn=tm(e)),Bn}function Rc(){Bn=null}function Ft(...e){for(let t of e){if(t==null||t==="")continue;let r=Number(t);if(Number.isFinite(r))return r}return null}function Pc(e,t){let r=Ft(e);return r==null||r<0?t:r>1?r/100:r}function oa(e,t){let r=Ft(e);return r!=null&&r>=0?Math.floor(r):t}function Oc(e){let t=e??he();if(!t)return{steamFeeRate:.05,publisherFeeRate:.1,steamFeeMinimumMinor:1,publisherFeeMinimumMinor:1,steamFeeBaseMinor:0};let r=ze(t),n=t?.walletInfo||(Object.hasOwn(t,"wallet_currency")?t:{});return{steamFeeRate:Pc(Ft(t.steamFeeRate,n.wallet_fee_percent,r.steamFeeRate),.05),publisherFeeRate:Pc(Ft(t.publisherFeeRate,n.wallet_publisher_fee_percent_default,r.publisherFeeRate),.1),steamFeeMinimumMinor:oa(Ft(t.steamFeeMinimumMinor,n.wallet_fee_minimum,n.wallet_market_minimum,r.steamFeeMinimumMinor),1),publisherFeeMinimumMinor:oa(Ft(t.publisherFeeMinimumMinor,n.wallet_publisher_fee_minimum,n.wallet_fee_minimum,n.wallet_market_minimum,r.publisherFeeMinimumMinor),1),steamFeeBaseMinor:oa(Ft(t.steamFeeBaseMinor,n.wallet_fee_base,r.steamFeeBaseMinor),0)}}function Bc(e,t){let r=Math.floor(Math.max(e*t.steamFeeRate,t.steamFeeMinimumMinor)+t.steamFeeBaseMinor),n=Math.floor(Math.max(e*t.publisherFeeRate,t.publisherFeeMinimumMinor));return{steamFee:r,publisherFee:n,totalFees:r+n,buyerCents:e+r+n}}function rm(e,t){let r=Math.max(0,Math.floor(Number(e)||0));return r>0?Bc(r,t).buyerCents:0}function nm(e,t){let r=Math.max(0,Math.floor(Number(e)||0));return r<=0?{steamFee:0,publisherFee:0,totalFees:0,buyerCents:0}:Bc(r,Oc(t))}function ia(e,t){return nm(e,t).buyerCents}function Ur(e,t){let r=Math.max(0,Math.floor(Number(e)||0));if(r<=0)return 0;let n=Oc(t),s=0,o=r,i=0;for(;s<=o;){let c=Math.floor((s+o)/2);rm(c,n)<=r?(i=c,s=c+1):o=c-1}return i}function cr(e,t){return Ur(e,t)}function Ln(e,t,r){let n=cr(t,r);return n>0?n*Math.max(0,Number(e)||0)/1e3:0}function lr(e,t,r){let n=Math.ceil(Ln(e,t,r));return n>0?ia(n,r):0}function Tn(e,t){return e.gemSackPriceCents=t||0,e.gemValueNetCents=Ln(e.totalGems,t),e.unitGemValueNetCents=Ln(e.gemValue,t),e.breakEvenPriceCents=lr(e.gemValue,t),e.marketNetCents=e.priceCents?Ur(e.priceCents):0,t?!e.marketHashName||e.marketableCount<=0?(e.recommendationKey="grind",e.recommendationLabel="分解",e.recommendationClass="ok",e.recommendationReason="不可出售或缺少市场标识"):e.priceLookupFailed?(e.recommendationKey="unknown",e.recommendationLabel="缺市场价",e.recommendationClass="warn",e.recommendationReason="市场价格请求失败"):e.priceCents?e.marketNetCents<=e.unitGemValueNetCents?(e.recommendationKey="grind",e.recommendationLabel="分解",e.recommendationClass="ok",e.recommendationReason=`卖出税后约 ${w(e.marketNetCents)},低于分解宝石税后约 ${w(e.unitGemValueNetCents)}`):(e.recommendationKey="sell",e.recommendationLabel="出售",e.recommendationClass="info",e.recommendationReason=`卖出税后约 ${w(e.marketNetCents)},高于分解宝石税后约 ${w(e.unitGemValueNetCents)}`):(e.recommendationKey="grind",e.recommendationLabel="分解",e.recommendationClass="ok",e.recommendationReason="市场暂无可用价格"):(e.recommendationKey="unknown",e.recommendationLabel="缺宝石价",e.recommendationClass="warn",e.recommendationReason="宝石袋价格不可用"),e}function Lc(e){let t=ae(e),r=Math.max(0,Number(e?.level)||0);return e?.isUnlimitedLevelBadge?{targetLevel:t,level:r,eligible:!0,badgeMaxed:r>=1,reservePerCard:r>=1?0:1}:{targetLevel:t,level:r,eligible:!0,badgeMaxed:r>=t,reservePerCard:Math.max(0,t-r)}}var{log:re,setStatus:Fn,setProgress:Dn,hideProgress:sm}=Et;function am(e,t,r){let n=Ie(t),s=je(t),o=!n&&!s;e.priceCents=n&&t.lowestSellCents||0,e.medianCents=n&&t.medianCents||0,e.volume=o?null:t?.volume??null,e.priceSource=n?t.priceSource:s?"none":"failed",e.priceLookupFailed=o,Tn(e,r)}async function om(e,t,r){let n=await r.fetch(Ze(t,e.appid,e,{language:"english"}));if(!n?.text?.includes("badge_card_set_card"))throw new Error("未找到卡牌套组");let s=Ct(n.text,e.appid,e.isFoil);s.appid=e.appid,s.isFoil=e.isFoil,s.gameName=s.gameName||e.gameName||"";let o=Lc(s),{targetLevel:i,level:c,badgeMaxed:l,reservePerCard:u}=o;if(!o.eligible)return[];let d=[];for(let m of s.cards){let p=wc(e,m);if(!p)continue;let h=Math.max(0,p.totalCount-u);if(h<=0)continue;let f=kc(p.assets,h),g=f.reduce((M,E)=>M+(E.marketable?E.selectedAmount:0),0),y=f.reduce((M,E)=>M+(E.tradable?E.selectedAmount:0),0),b=Pn(f),S=f.reduce((M,E)=>M+(E.selectedAmount||0)*(E.gemValue||p.gemValue||0),0);d.push({category:"card",appid:e.appid,isFoil:e.isFoil,gameName:s.gameName||e.gameName||"",level:c,targetLevel:i,badgeMaxed:l,isUnlimitedLevelBadge:!!s.isUnlimitedLevelBadge,cardName:m.name||p.name,marketHashName:m.marketHashName||p.marketHashName,imageUrl:p.imageUrl||"",nameColor:p.nameColor||"",backgroundColor:p.backgroundColor||"",gemValue:p.gemValue||0,totalGems:S,inventoryCount:p.totalCount,reservedCount:u,surplusCount:h,marketableCount:g,tradableCount:y,assets:f,assetText:b.text,assetTitle:b.title})}return d}function la(){return(a.surplusResults||[]).filter(e=>!(Wt(e,"card")||a.cfg.surplusOnlyRecommended&&e.recommendationKey!=="grind"||a.cfg.surplusOnlyTradable&&e.tradableCount<=0))}function jr(e){let t=(e.assets||[]).map(r=>`${r.assetid||""}x${r.selectedAmount??r.amount??""}`).join(",");return["card",e.appid||"",e.isFoil?1:0,e.marketHashName||e.cardName||"",t].join("|")}function Hn(){let e=a.selectedSurplusResults||new Set;return(a.surplusResults||[]).filter(t=>e.has(jr(t))&&!Wt(t,"card"))}function Fc(e){a.selectedSurplusResults||(a.selectedSurplusResults=new Set);let t=la();for(let r of t){let n=jr(r);e?a.selectedSurplusResults.add(n):a.selectedSurplusResults.delete(n)}ce()}function im(e){let t=a.selectedSurplusResults||new Set,r=new Set(e.map(jr));for(let n of[...t])r.has(n)||t.delete(n)}function Tc(){a.surplusResults.sort((e,t)=>{let r=+(t.recommendationKey==="grind")-+(e.recommendationKey==="grind");if(r)return r;let n=(e.gameName||"").localeCompare(t.gameName||"","zh-CN");return n||(e.appid!==t.appid?Number(e.appid)-Number(t.appid):e.isFoil!==t.isFoil?Number(e.isFoil)-Number(t.isFoil):(e.cardName||"").localeCompare(t.cardName||"","zh-CN"))})}function ca(){let e=document.getElementById("stch-surplus-summary-row"),t=document.getElementById("stch-surplus-summary");if(!e||!t)return;let r=la();if(r.length===0){e.style.display="none",t.textContent="";return}let n=new Set(r.map(u=>`${u.appid}_${u.isFoil?1:0}`)).size,s=r.reduce((u,d)=>u+d.surplusCount,0),o=r.reduce((u,d)=>u+d.marketableCount,0),i=r.reduce((u,d)=>u+d.tradableCount,0),c=a.selectedSurplusResults||new Set,l=r.reduce((u,d)=>u+Number(c.has(jr(d))),0);t.innerHTML=`共 ${n} 个徽章 · ${r.length} 种卡牌 · 多余 ${s} 张 · 可出售 ${o} 张 · 可交易 ${i} 张 · 已选择 ${l} 项`,e.style.display=""}function ce(){let e=document.getElementById("stch-surplus-list");if(!e)return;Yt(e,{isSelected:r=>a.selectedSurplusResults?.has(r.dataset.key),setSelected:(r,n)=>{a.selectedSurplusResults||(a.selectedSurplusResults=new Set),n?a.selectedSurplusResults.add(r.dataset.key):a.selectedSurplusResults.delete(r.dataset.key)},onSelectionChange:()=>{ca(),Me()}}),e.innerHTML="",e.classList.add("stch-inventory-grid");let t=la();if(im(t),t.length===0){Mt(e,a.surplusScanning?"正在检测多余卡牌...":a.surplusResults.length>0?"当前筛选下没有多余卡牌":"尚未检测到多余卡牌"),ca(),Me();return}for(let r of t){let n=jr(r),s=document.createElement("div");s.className="stch-inv-tile";let o=r.volume===0;s.classList.toggle("stch-volume-zero",o),s.dataset.key=n,s.classList.toggle("selected",a.selectedSurplusResults?.has(n)),s.title=[`${r.gameName||"未知游戏"} · ${r.cardName||r.marketHashName||"未知卡牌"}`,r.isUnlimitedLevelBadge?`特卖徽章 Lv${r.level}(Lv1 后可处理多余卡牌)`:`徽章 Lv${r.level}/${r.targetLevel}`,`库存 ${r.inventoryCount},预留 ${r.reservedCount},多余 ${r.surplusCount}`,`可出售 ${r.marketableCount},可交易 ${r.tradableCount}`,r.volume===0?"市场成交量 0":Number.isFinite(r.volume)?`市场成交量 ${r.volume}`:"市场价格尚未读取",r.priceCents?`市场参考 ${w(r.priceCents)},出售税后约 ${w(r.marketNetCents)}`:"",r.gemValueNetCents?`${r.gemValue} 宝石/张,税后折算约 ${w(r.gemValueNetCents)}`:"",r.recommendationReason?`建议:${r.recommendationLabel||"—"},${r.recommendationReason}`:"","按住并拖动可连续选择或取消",r.assetTitle?`资产ID: ${r.assetTitle}`:""].filter(Boolean).join(` `),r.nameColor&&(s.style.borderColor=r.nameColor),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),Qt(s,r.imageUrl,r.cardName||r.marketHashName);let i=document.createElement("span");i.className="stch-inv-badge",i.textContent=`x${r.surplusCount}`,i.title="多余数量",s.appendChild(i);let c=document.createElement("span");c.className=`stch-inv-badge stch-inv-badge-left ${r.recommendationClass||""}`.trim(),c.textContent=r.recommendationLabel||"—",c.title=r.recommendationReason||"",s.appendChild(c);let l=document.createElement("div");l.className="stch-inv-name",l.textContent=r.cardName||r.marketHashName||"未知卡牌",s.appendChild(l),e.appendChild(s)}ca(),Me()}async function Dc(){if(J(a.surplusScanning||a.grindScanning))return;if(location.hostname!=="steamcommunity.com"){re("请在 Steam 社区徽章页或库存页使用多余物品处理","warn");return}let e=Q(),t=et();if(!e||!t){re("未找到 Steam 个人资料地址或 SteamID","err");return}a.surplusScanning=!0,a.surplusStopRequested=!1,a.surplusResults=[],a.selectedSurplusResults=new Set,a.surplusGemPrice=null;let r=document.getElementById("stch-surplus-log");r&&(r.innerHTML=""),ce(),R();let n=a.cfg,s=oe(U(n),()=>new G(n.requestInterval,a,Fn,re,{stopPredicate:i=>!!i?.surplusStopRequested}));a.surplusQueue=s;let o=[];try{re("【阶段 1/3】正在读取 Steam 社区库存"),Dn(0,1,"阶段1: 读取库存");let i=await Ec(t,s);if(a.surplusStopRequested){re("已停止检测","warn");return}if(i.groups.length===0){re("库存中没有检测到集换式卡牌","warn"),ce();return}re(`库存读取完成:库存 ${i.totalInventoryCount||i.totalAssetsSeen} 件,卡牌 ${i.totalCards} 张,${i.cardTypeCount} 种,${i.groups.length} 个徽章候选`,"ok"),re("【阶段 2/3】正在读取徽章等级并计算升满后剩余");let c=0,l=0,u=0;await Y(i.groups,U(n),async p=>{if(a.surplusStopRequested)return;c++;let h=`${p.gameName||p.appid}${p.isFoil?"(闪亮)":""}`;Dn(u,i.groups.length,`阶段2: ${u+1}/${i.groups.length} · ${h}`),Fn(`读取徽章: ${h}`);try{let f=await om(p,e,s);if(f.length===0){a.cfg.showNoResultLogs&&re(`[${p.appid}] ${h}: 没有升满后剩余`,"info");return}a.surplusResults.push(...f);let g=f.reduce((y,b)=>y+b.surplusCount,0);re(`[${p.appid}] ${h}: ${f.length} 种卡牌,多余 ${g} 张`,"ok")}catch(f){if(a.surplusStopRequested)return;l++,re(`[${p.appid}] ${h}: 读取失败 ${f?.message||f?.status||f}`,"warn")}finally{u++,Dn(u,i.groups.length,`阶段2: ${u}/${i.groups.length}`),(u===1||u%5===0)&&ce()}}),Tc(),ce();let d=0,m=0;if(!a.surplusStopRequested&&a.surplusResults.length>0){re("【阶段 3/3】正在查询市场成交量并计算宝石价值");try{a.surplusGemPrice=await ir(s),a.surplusGemPrice.priceCents&&re(`宝石袋 ${a.surplusGemPrice.source} ${w(a.surplusGemPrice.priceCents)}`,"info")}catch(f){re(`宝石袋价格读取失败: ${f?.message||f}`,"warn")}let p=new Map,h=0;await Y(a.surplusResults,U(n),async f=>{if(a.surplusStopRequested)return;Dn(h,a.surplusResults.length,`阶段3: ${h+1}/${a.surplusResults.length} · ${f.cardName||f.marketHashName}`),Fn(`查询市场: ${f.cardName||f.marketHashName}`);let g=null;if(f.marketHashName){let y=p.get(f.marketHashName),b=!1;y||(b=!0,y=me(f.marketHashName,s,{preferListing:!0,requireVolume:!0,persistMarketCache:!1}),p.set(f.marketHashName,y)),g=await y,b&&g?.record&&o.push(g.record)}am(f,g,a.surplusGemPrice?.priceCents||0),!Ie(g)&&!je(g)&&d++,f.volume===0&&m++,h++,(h===1||h%5===0)&&ce()}),Tc(),ce(),a.surplusStopRequested||re(`市场比较完成:成交量为 0 的卡牌 ${m} 种,查价失败 ${d} 种`,d?"warn":"ok")}if(a.surplusStopRequested)re("已停止检测","warn");else{let p=a.surplusResults.reduce((h,f)=>h+f.surplusCount,0);re(`检测完成:读取 ${c} 个徽章,失败 ${l} 个,找到 ${a.surplusResults.length} 种多余卡牌 / ${p} 张`,l?"warn":"ok")}}catch(i){a.surplusStopRequested||re(`检测中断: ${i?.message||i?.status||i}`,"err")}finally{s.stop(),ee(o),a.surplusQueue=null,a.surplusScanning=!1,a.surplusStopRequested=!1,sm(),Fn(null),ce(),R()}}function Hc(){a.surplusScanning&&(a.surplusStopRequested=!0,a.surplusQueue?.stop(),re("已请求停止检测","warn"),Me())}var{log:le,setStatus:qn,setProgress:ua,hideProgress:cm}=Ar,qc=null,zc=new Set;function lm(){let e=a.cfg.blacklist||"";return e!==qc&&(qc=e,zc=new Set(e.split(",").map(t=>t.trim()).filter(Boolean))),zc}function Gc(e){return!!e&&lm().has(String(e))}var Vr=new Map;async function um(e,t){let r=aa(e);if(r>0)return r;let n=Ic(e);if(!n)return 0;let s=`${n.appid}_${n.itemType}_${n.borderColor}`;if(Vr.has(s))return Vr.get(s);let o=(async()=>{try{let c=`https://steamcommunity.com/auction/ajaxgetgoovalueforitemtype/?appid=${encodeURIComponent(n.appid)}&item_type=${encodeURIComponent(n.itemType)}&border_color=${encodeURIComponent(n.borderColor)}`,l=await t.fetch(c);return Math.max(0,parseInt(l?.data?.goo_value,10)||0)}catch{return 0}})();Vr.set(s,o);let i=await o;return Vr.set(s,i),i}function dm(e,t,r,n,s,o,i=!1,c=""){if(!r||n<=0)return"skipped";if(or(r)||zr(r))return"gem";let l=Math.max(0,parseInt(o,10)||0);if(l<=0)return"noGemValue";let u=$n(r);if(Gc(u))return"blacklisted";let d=String(r.market_hash_name||"").trim(),m=[u||"0",d||$e(r),l,s].join("|"),p=e.get(m);p||(p={category:c,appid:u,gameName:qr(r),type:Mc(r),itemName:String(r.name||d||"未知物品").trim(),marketHashName:d,imageUrl:ra(r),nameColor:Hr(r,"name_color"),backgroundColor:Hr(r,"background_color"),gemValue:l,quantity:0,totalGems:0,marketableCount:0,tradableCount:0,pointsShopCount:0,source:s,descriptionKey:$e(r),assets:[]},e.set(m,p)),!p.category&&c&&(p.category=c),p.gameName||(p.gameName=qr(r));let h=Number(r.marketable)===1,f=Number(r.tradable)===1;return p.quantity+=n,p.totalGems+=n*l,h&&(p.marketableCount+=n),f&&(p.tradableCount+=n),i&&(p.pointsShopCount+=n),p.assets.push({assetid:String(t.assetid||""),contextid:String(t.contextid||"6"),amount:n,originalAmount:ht(t),marketable:h,tradable:f,pointsShop:i}),"added"}function mm(e,t){let r=(e.assets||[]).reduce((c,l)=>c+Math.max(0,Number(l.amount)||0),0),n=Math.min(r,Math.max(0,Math.floor(Number(t)||0))),s=Math.max(0,r-n);if(s<=0)return null;let o=[...e.assets||[]].sort((c,l)=>{let u=Number(l.marketable)-Number(c.marketable);if(u)return u;let d=Number(l.tradable)-Number(c.tradable);if(d)return d;let m=Number(c.pointsShop)-Number(l.pointsShop);return m||String(c.assetid||"").localeCompare(String(l.assetid||""),"en")}).flatMap(c=>{if(s<=0)return[];let l=Math.min(Math.max(0,Number(c.amount)||0),s);return s-=l,l>0?[{...c,amount:l}]:[]}),i=o.reduce((c,l)=>c+l.amount,0);return{...e,inventoryCount:r,reservedCount:n,quantity:i,totalGems:i*e.gemValue,marketableCount:o.reduce((c,l)=>c+(l.marketable?l.amount:0),0),tradableCount:o.reduce((c,l)=>c+(l.tradable?l.amount:0),0),pointsShopCount:o.reduce((c,l)=>c+(l.pointsShop?l.amount:0),0),assets:o}}async function pm(e,t){let r=new Map,n=Ce.g_strLanguage||"schinese",s=Math.max(0,Math.floor(Number(a.cfg.grindReserveCopies)||0)),o=!!a.cfg.grindIncludePointsShopItems,i=["background","emoticon"].includes(a.cfg.surplusItemMode)?a.cfg.surplusItemMode:"background",c="",l=0,u=0,d=0,m={noGemValue:0,blacklisted:0,gems:0,pointsShop:0,reserved:0};do{l++;let h=new URLSearchParams({l:n,count:"2000"});c&&h.set("start_assetid",c);let f=`https://steamcommunity.com/inventory/${e}/753/6?${h.toString()}`;qn(`读取库存第 ${l} 页`);let y=(await t.fetch(f))?.data||{};if(y?.success!==1&&y?.success!==!0)throw new Error(y?.Error||y?.error||"Steam 未返回可用库存数据");u=Number(y.total_inventory_count||u)||u;let b=new Map;(Array.isArray(y.descriptions)?y.descriptions:[]).forEach(E=>{b.set($e(E),E)});let S=Array.isArray(y.assets)?y.assets:[];d+=S.length;let M=[];for(let E of S){if(a.grindStopRequested)break;let x=b.get($e(E));if(!x)continue;let I=ht(E);if(or(x)||zr(x)){m.gems+=I;continue}if(Gc($n(x))){m.blacklisted+=I;continue}if(sa(x)!==i)continue;let N=vc(x);if(N&&!o){m.pointsShop+=I;continue}M.push({asset:E,description:x,assetAmount:I,pointsShop:N})}await Y(M,jt(a.cfg),async({asset:E,description:x,assetAmount:I,pointsShop:N})=>{if(a.grindStopRequested)return;let A=await um(x,t),B=dm(r,E,x,I,"item",A,N,i);B==="noGemValue"?m.noGemValue+=I:B==="blacklisted"?m.blacklisted+=I:B==="gem"&&(m.gems+=I)}),le(`库存第 ${l} 页:读取 ${S.length} 件,累计候选 ${r.size} 种`,"info"),c=y.more_items&&y.last_assetid?String(y.last_assetid):""}while(c&&!a.grindStopRequested);return{items:[...r.values()].flatMap(h=>{let f=mm(h,s);return m.reserved+=f?f.reservedCount:h.quantity,f?[f]:[]}).sort((h,f)=>{let g=Number(f.totalGems)-Number(h.totalGems);if(g)return g;let y=(h.gameName||"").localeCompare(f.gameName||"","zh-CN");return y||(h.itemName||"").localeCompare(f.itemName||"","zh-CN")}),totalInventoryCount:u,totalAssetsSeen:d,skipped:m}}function fm(e,t){return Tn(e,t)}function ma(){return(a.grindResults||[]).filter(e=>{let t=e.category||a.cfg.surplusItemMode;return!(Wt(e,t)||a.cfg.surplusOnlyRecommended&&e.recommendationKey!=="grind"||a.cfg.surplusOnlyTradable&&e.tradableCount<=0)})}function Kr(e){let t=(e.assets||[]).map(r=>`${r.assetid||""}x${r.amount??""}`).join(",");return["item",e.appid||"",e.marketHashName||e.itemName||"",e.gemValue||0,e.source||"",t].join("|")}function zn(){let e=a.selectedGrindResults||new Set;return(a.grindResults||[]).filter(t=>e.has(Kr(t))&&!Wt(t,t.category||a.cfg.surplusItemMode))}function Uc(e){a.selectedGrindResults||(a.selectedGrindResults=new Set);let t=ma();for(let r of t){let n=Kr(r);e?a.selectedGrindResults.add(n):a.selectedGrindResults.delete(n)}pe()}function hm(e){let t=a.selectedGrindResults||new Set,r=new Set(e.map(Kr));for(let n of[...t])r.has(n)||t.delete(n)}function da(){let e=document.getElementById("stch-grind-summary-row"),t=document.getElementById("stch-grind-summary");if(!e||!t)return;let r=ma();if(r.length===0){e.style.display="none",t.textContent="";return}let n=(a.grindResults||[]).filter(m=>m.recommendationKey==="grind"),s=r.reduce((m,p)=>m+p.quantity,0),o=n.reduce((m,p)=>m+p.quantity,0),i=n.reduce((m,p)=>m+p.totalGems,0),c=a.selectedGrindResults||new Set,l=r.reduce((m,p)=>m+Number(c.has(Kr(p))),0),u=a.grindGemPrice||{},d=u.priceCents?`宝石袋 ${w(u.priceCents)} / 税后 ${w(cr(u.priceCents))}`:"暂无宝石袋价格";t.innerHTML=`显示 ${r.length} 种 / ${s} 件 · 建议分解 ${n.length} 种 / ${o} 件 · 预计 ${ie(i)} 宝石 · 已选择 ${l} 项 · ${d}`,e.style.display=""}function pe(){let e=document.getElementById("stch-grind-list");if(!e)return;Yt(e,{isSelected:r=>a.selectedGrindResults?.has(r.dataset.key),setSelected:(r,n)=>{a.selectedGrindResults||(a.selectedGrindResults=new Set),n?a.selectedGrindResults.add(r.dataset.key):a.selectedGrindResults.delete(r.dataset.key)},onSelectionChange:()=>{da(),Me()}}),e.innerHTML="",e.classList.add("stch-inventory-grid");let t=ma();if(hm(t),t.length===0){Mt(e,a.grindScanning?"正在扫描可分解物品...":a.grindResults.length>0?"当前筛选下没有建议分解物品":"尚未扫描可分解物品"),da(),Me();return}for(let r of t){let n=Kr(r),s=Pn(r.assets.map(h=>({assetid:h.assetid,selectedAmount:h.amount}))),o=r.priceCents?w(r.priceCents):r.marketHashName&&r.marketableCount>0?"无价":"不可售",i=r.priceCents?`${r.priceSource||"市场价"};卖出税后约 ${w(r.marketNetCents)}`:r.recommendationReason||"",c=r.breakEvenPriceCents?w(r.breakEvenPriceCents):"—",l=document.createElement("div");l.className="stch-inv-tile",l.classList.toggle("stch-volume-zero",r.volume===0),l.dataset.key=n,l.classList.toggle("selected",a.selectedGrindResults?.has(n)),l.title=[`${r.gameName||"未知游戏"} · ${r.itemName||r.marketHashName||"未知物品"}`,`类型 ${r.type||"物品"};库存 ${r.inventoryCount},保留 ${r.reservedCount},多余 ${r.quantity}`,r.pointsShopCount?`多余数量中含点数商店类副本 ${r.pointsShopCount} 件`:"",`${r.gemValue} 宝石/件,共 ${ie(r.totalGems)} 宝石`,`市场 ${o}${i?`;${i}`:""}`,`分解临界 ${c}`,r.recommendationReason?`建议:${r.recommendationLabel||"—"},${r.recommendationReason}`:"","按住并拖动可连续选择或取消",s.title?`资产ID: ${s.title}`:""].filter(Boolean).join(` `),r.nameColor&&(l.style.borderColor=r.nameColor),r.backgroundColor&&(l.style.backgroundColor=r.backgroundColor),Qt(l,r.imageUrl,r.itemName||r.marketHashName);let u=document.createElement("span");u.className="stch-inv-badge",u.textContent=r.priceCents?w(r.priceCents):`x${r.quantity}`,u.title=i||"数量",l.appendChild(u);let d=document.createElement("span");d.className=`stch-inv-badge stch-inv-badge-left ${r.recommendationClass||""}`.trim(),d.textContent=r.recommendationLabel||"—",d.title=r.recommendationReason||"",l.appendChild(d);let m=document.createElement("span");m.className="stch-inv-gems",m.textContent=`${ie(r.totalGems)} 宝石`,m.title=`${r.gemValue} 宝石/件`,l.appendChild(m);let p=document.createElement("div");p.className="stch-inv-name",p.textContent=r.itemName||r.marketHashName||"未知物品",l.appendChild(p),e.appendChild(l)}da(),Me()}async function jc(){if(J(a.surplusScanning||a.grindScanning))return;if(location.hostname!=="steamcommunity.com"){le("请在 Steam 社区徽章页或库存页使用多余物品处理","warn");return}let e=et();if(!e){le("未找到 SteamID,无法读取库存","err");return}a.grindScanning=!0,a.grindStopRequested=!1,a.grindResults=[],a.selectedGrindResults=new Set,a.grindGemPrice=null,Vr.clear();let t=document.getElementById("stch-grind-log");t&&(t.innerHTML=""),pe(),R();let r=a.cfg,n=()=>new G(r.requestInterval,a,qn,le,{stopPredicate:l=>!!l?.grindStopRequested}),s=oe(U(r),n),o=oe(jt(r),n),i=()=>{s.stop(),o.stop()};a.grindQueue={stop:i};let c=[];try{le("【阶段 1/3】读取宝石袋市场价格"),ua(0,1,"阶段1: 读取宝石价格");let l=await ir(s);if(a.grindGemPrice=l,l.priceCents){let g=cr(l.priceCents),y=lr(10,l.priceCents);le(`宝石袋 ${l.source} ${w(l.priceCents)},税后到手约 ${w(g)};10宝石临界价 ${w(y)}`,"ok")}else le("宝石袋价格不可用;继续检测,但不会给出分解或出售建议","warn");let u=a.cfg.surplusItemMode==="emoticon"?"表情":"背景";le(`本次只分析${u}类社区物品`,"info"),le("【阶段 2/3】读取社区库存并识别可分解物品"),ua(0,1,"阶段2: 读取库存");let d=await pm(e,o);if(a.grindStopRequested){le("已停止扫描","warn");return}if(le(`库存读取完成:库存 ${d.totalInventoryCount||d.totalAssetsSeen} 件,候选 ${d.items.length} 种;跳过无宝石值 ${d.skipped.noGemValue} 件,默认保留 ${d.skipped.reserved} 件,点数商店类 ${d.skipped.pointsShop} 件,游戏黑名单 ${d.skipped.blacklisted} 件`,"ok"),d.items.length===0){pe(),le("没有找到可用于分解建议的物品","warn");return}le("【阶段 3/3】查询市场价格并计算建议");let m=d.items.filter(g=>g.marketHashName&&g.marketableCount>0),p=0,h=0,f=0;if(await Y(d.items,U(r),async g=>{if(!a.grindStopRequested){if(ua(f,d.items.length,`阶段3: ${f+1}/${d.items.length} · ${g.itemName||g.marketHashName}`),qn(`查询价格: ${g.itemName||g.marketHashName}`),g.marketHashName&&g.marketableCount>0){let y=await me(g.marketHashName,s,{preferListing:!0,requireVolume:!0,persistMarketCache:!1});y?.record&&c.push(y.record),Ie(y)?(g.priceCents=y.lowestSellCents,g.medianCents=y.medianCents,g.volume=y.volume,g.priceSource=y.priceSource==="lowest"?"在售最低":"平均价格",p++):je(y)?(g.volume=0,g.priceSource="无可用价格",g.priceLookupFailed=!1):Cr(y)&&(h++,g.priceSource="查价失败",g.priceLookupFailed=!0)}else g.priceSource="缺少市场信息",g.priceLookupFailed=!0;fm(g,l.priceCents),a.grindResults.push(g),f++,(f===1||f%5===0)&&pe()}}),a.grindResults.sort((g,y)=>{let b=+(y.recommendationKey==="grind")-+(g.recommendationKey==="grind");if(b)return b;let S=y.totalGems-g.totalGems;if(S)return S;let M=(g.gameName||"").localeCompare(y.gameName||"","zh-CN");return M||(g.itemName||"").localeCompare(y.itemName||"","zh-CN")}),pe(),a.grindStopRequested)le("已停止扫描","warn");else{let g=a.grindResults.filter(S=>S.recommendationKey==="grind"),y=g.reduce((S,M)=>S+M.quantity,0),b=g.reduce((S,M)=>S+M.totalGems,0);le(`扫描完成:查价 ${p}/${m.length} 种,失败 ${h} 种;建议分解 ${g.length} 种 / ${y} 件 / ${ie(b)} 宝石`,h?"warn":"ok")}}catch(l){a.grindStopRequested||le(`扫描中断: ${l?.message||l?.status||l}`,"err")}finally{i(),ee(c),a.grindQueue=null,a.grindScanning=!1,a.grindStopRequested=!1,cm(),qn(null),pe(),R()}}function Vc(){a.grindScanning&&(a.grindStopRequested=!0,a.grindQueue?.stop(),le("已请求停止扫描","warn"),Me())}function pa(){let e=document.getElementById("stch-surplus-item-mode")?.value||a.cfg.surplusItemMode||"card";return["card","background","emoticon"].includes(e)?e:"card"}function Kc(e=pa()){return e==="card"?{log:Et.log,setStatus:Et.setStatus,emptySell:"请先选择要出售的卡牌",emptyGem:"请先选择要转化宝石的卡牌"}:{log:Ar.log,setStatus:Ar.setStatus,emptySell:"请先选择要出售的物品",emptyGem:"请先选择要转化宝石的物品"}}function gm(){let e=document.getElementById("stch-surplus-sell-price-source")?.value||a.cfg.surplusSellPriceSource||"lowest",t=["lowest","median","highest"].includes(e)?e:"lowest",r=document.getElementById("stch-surplus-sell-adjustment"),n=r?parseFloat(r.value):a.cfg.surplusSellPriceAdjustment,s=Math.round((Number.isFinite(n)?n:0)*100);return{priceSource:t,adjustmentCents:s}}function Wc(e){let t=a.cfg;return new G(t.requestInterval,a,e.setStatus,e.log,{stopPredicate:()=>!1})}function Qc(e){return new Promise(t=>setTimeout(t,e))}function ur(e,t="amount"){let r=Number(e?.[t]);return Number.isSafeInteger(r)&&r>0?r:null}function Un(e){return e==="card"?Hn():zn()}function Yc(e){e==="card"?(a.selectedSurplusResults=new Set,ce()):(a.selectedGrindResults=new Set,pe())}function bm(e){let t=Un(e),r=0;return e==="card"?{groups:t.map(o=>{let i=(o.assets||[]).filter(c=>c.assetid&&c.marketable).flatMap(c=>{let l=ur(c,"selectedAmount");return l==null?(r++,[]):[{assetid:String(c.assetid||""),contextid:String(c.contextid||"6"),amount:l}]});return{gameName:o.gameName||"",itemName:o.cardName||o.marketHashName||"未知卡牌",marketHashName:o.marketHashName||"",quantity:i.reduce((c,l)=>c+l.amount,0),assets:i}}),invalidQuantity:r}:{groups:t.map(s=>{let o=(s.assets||[]).filter(i=>i.assetid&&i.marketable).flatMap(i=>{let c=ur(i,"amount");return c==null?(r++,[]):[{assetid:String(i.assetid||""),contextid:String(i.contextid||"6"),amount:c}]});return{gameName:s.gameName||"",itemName:s.itemName||s.marketHashName||"未知物品",marketHashName:s.marketHashName||"",quantity:o.reduce((i,c)=>i+c.amount,0),assets:o}}),invalidQuantity:r}}function ym(e){let t=Un(e),r=0;return e==="card"?{candidates:t.flatMap(o=>(o.assets||[]).flatMap(i=>{let c=ur(i,"selectedAmount"),l=ur(i,"amount");return c==null||l==null?(r++,[]):[{appid:String(o.appid||""),gameName:o.gameName||"",itemName:o.cardName||o.marketHashName||"未知卡牌",assetid:String(i.assetid||""),contextid:String(i.contextid||"6"),selectedAmount:c,assetAmount:l,estimatedGems:(i.gemValue||o.gemValue||0)*c}]})),invalidQuantity:r}:{candidates:t.flatMap(s=>(s.assets||[]).flatMap(o=>{let i=ur(o,"amount"),c=ur(o,"originalAmount");return i==null||c==null?(r++,[]):[{appid:String(s.appid||""),gameName:s.gameName||"",itemName:s.itemName||s.marketHashName||"未知物品",assetid:String(o.assetid||""),contextid:String(o.contextid||"6"),selectedAmount:i,assetAmount:c,estimatedGems:(s.gemValue||0)*i}]})),invalidQuantity:r}}async function vm(e,t,r,n,s,o,i,c){if(i.has(e.marketHashName))return i.get(e.marketHashName);let l=(async()=>{let d=null;if(t==="highest")n.setStatus(`读取求购最高 ${s+1}/${o}: ${e.itemName}`),d=await Nn(e.marketHashName,r,{persistMarketCache:!1,onRecord:m=>c.push(m)});else{n.setStatus(`读取出售参考价 ${s+1}/${o}: ${e.itemName}`);let m=await me(e.marketHashName,r,{preferListing:!0,requireMedian:t==="median",persistMarketCache:!1});m?.record&&c.push(m.record),Ie(m)&&(d=t==="lowest"?m.priceSource==="lowest"?m.lowestSellCents:null:Number.isFinite(m.medianCents)&&m.medianCents>0?m.medianCents:null)}return Number.isFinite(d)&&d>0?d:null})();i.set(e.marketHashName,l);let u=await l;return i.set(e.marketHashName,u),u}async function xm(e,t,r){let{priceSource:n,adjustmentCents:s}=gm(),o=Ae();if(!Number.isSafeInteger(o)||o<=0)throw new Error("无法确认 Steam 钱包币种,已停止生成出售计划");let i=new Map,c=[],l={missingHash:0,unmarketable:0,missingPrice:0,clamped:0,failedPrice:0},u=bm(e);l.invalidQuantity=u.invalidQuantity;let d=u.groups.filter(p=>p.marketHashName?!p.assets.length||p.quantity<=0?(l.unmarketable++,!1):!0:(l.missingHash++,!1)),m=new Array(d.length);return await Y(d,U(a.cfg),async(p,h)=>{let f=null;try{f=await vm(p,n,r,t,h,d.length,i,c)}catch(M){l.failedPrice++,t.log(` ${p.itemName}: ${M?.message||M},已跳过`,"warn")}if(!f){l.missingPrice++;return}let g=f+s,y=Math.max(o,g);y!==g&&l.clamped++;let b=Ur(y);if(b<=0){l.missingPrice++;return}let S=ia(b);m[h]={...p,priceSource:n,basePriceCents:f,targetBuyerCents:g,unitBuyerCents:S,sellerReceiveCents:b,totalBuyerCents:S*p.quantity,totalReceiveCents:b*p.quantity}}),ee(c),{plan:m.filter(Boolean),skipped:l,priceSource:n,adjustmentCents:s,minimumBuyerCents:o}}function Jc(){let e=Q();if(e)return e.replace(/\/$/,"");let t=et();return t?`https://steamcommunity.com/profiles/${t}`:""}async function Sm(e,t,r,n,s){let o=Jc(),i=Pe();if(!o)throw new Error("未找到 Steam 个人资料地址");if(!i)throw new Error("未找到 Steam sessionid");r.setStatus(`读取宝石值 ${n+1}/${s}: ${e.itemName}`);let c=new URLSearchParams({sessionid:i,appid:e.appid,assetid:e.assetid,contextid:e.contextid||"6"}),u=(await t.fetch(`${o}/ajaxgetgoovalue/?${c.toString()}`))?.data||{},d=Math.max(0,parseInt(u.goo_value,10)||0);if(d<=0)throw new Error(u?.message||"Steam 未返回可分解宝石值");return d}async function Cm(e,t,r){let n=ym(e),s=n.candidates,o=new Array(s.length),i={missingAsset:0,missingAppid:0,partialStack:0,noGooValue:0,invalidQuantity:n.invalidQuantity};return await Y(s,jt(a.cfg),async(c,l)=>{if(!c.assetid){i.missingAsset++;return}if(!/^\d+$/.test(c.appid)){i.missingAppid++;return}if(c.selectedAmount{let r=document.createElement("div");r.id="stch-order-dialog-backdrop",r.innerHTML=`

${e.title}

取消
${e.confirmLabel}
`,r.querySelector(".stch-order-summary").innerHTML=e.summaryHtml;let n=r.querySelector(".stch-order-list");e.rows.forEach(o=>{let i=document.createElement("div");i.className=`stch-order-item stch-processing-dialog-item ${e.rowClass||""}`.trim(),o.forEach(c=>i.appendChild(P("",c))),n.appendChild(i)}),r.querySelector(".stch-order-note").textContent=e.note;let s=o=>{r.remove(),t(o)};r.querySelector('[data-action="cancel"]').addEventListener("click",()=>s(!1)),r.querySelector('[data-action="confirm"]').addEventListener("click",()=>s(!0)),r.addEventListener("click",o=>{o.target===r&&s(!1)}),document.body.appendChild(r)})}function Im(e){let{plan:t,skipped:r,priceSource:n,adjustmentCents:s,minimumBuyerCents:o}=e,i=t.reduce((m,p)=>m+p.quantity,0),c=t.reduce((m,p)=>m+p.totalBuyerCents,0),l=t.reduce((m,p)=>m+p.totalReceiveCents,0),u=s>=0?`+${w(s)}`:w(s),d=[];return r.missingHash&&d.push(`${r.missingHash} 项缺少市场标识`),r.unmarketable&&d.push(`${r.unmarketable} 项不可出售`),r.missingPrice&&d.push(`${r.missingPrice} 项缺少所选价格`),r.failedPrice&&d.push(`${r.failedPrice} 项查价失败`),r.invalidQuantity&&d.push(`${r.invalidQuantity} 个资产数量无效,已跳过`),r.clamped&&d.push(`${r.clamped} 项低于 Steam 最低售价,已调整到 ${w(o)}`),Zc({title:"确认上架出售",rowClass:"sell",confirmLabel:"上架出售",summaryHtml:`项目 ${t.length} 项 · 数量 ${i} 件 · 买家价格合计 ${w(c)} · 税后到手约 ${w(l)}
价格基准 ${Fr(n)} · 售价调整 ${u}`,rows:t.map(m=>[`${m.gameName?`${m.gameName} · `:""}${m.itemName}`,`${m.quantity} 件`,`买家 ${w(m.unitBuyerCents)}`,`到手 ${w(m.sellerReceiveCents)}`]),note:[...d,"可能需要手机确认"].join(";")+"。"})}function Mm(e){let{plan:t,skipped:r}=e,n=t.reduce((o,i)=>o+i.gooValueExpected,0),s=[];return r.missingAsset&&s.push(`${r.missingAsset} 项缺少资产 ID`),r.missingAppid&&s.push(`${r.missingAppid} 项缺少来源游戏 AppID`),r.partialStack&&s.push(`${r.partialStack} 项是部分堆叠资产,Steam 原生接口不支持只销毁一部分,已跳过`),r.noGooValue&&s.push(`${r.noGooValue} 项未读取到可分解宝石值`),r.invalidQuantity&&s.push(`${r.invalidQuantity} 个资产数量无效,已跳过`),Zc({title:"确认转化宝石",rowClass:"gem",confirmLabel:"转化宝石",danger:!0,summaryHtml:`资产 ${t.length} 个 · 预计获得 ${ie(n)} 宝石`,rows:t.map(o=>[`${o.gameName?`${o.gameName} · `:""}${o.itemName}`,o.assetid,`${ie(o.gooValueExpected)} 宝石`]),note:[...s,"不可逆销毁物品"].join(";")+"。"})}async function el(){let e=pa(),t=Kc(e);if(J(a.surplusActionRunning))return;if(!at()){t.log("收藏数据已损坏,为保护物品已停止出售","err");return}if(Un(e).length===0){t.log(t.emptySell,"warn");return}a.surplusActionRunning=!0,R();let r=oe(U(a.cfg),()=>Wc(t)),n=null,s=0,o=0;try{t.log("开始生成出售计划","info");let i=await xm(e,t,r);if(i.plan.length===0){n="没有可上架出售的选中项目",t.log(n,"warn");return}if(!await Im(i)){n="已取消上架出售";return}let l=i.plan.flatMap(u=>u.assets.map(d=>({...d,item:u})));for(let u=0;u0&&Yc(e)}catch(i){n=`无法上架出售: ${i?.message||i}`,t.log(n,"err")}finally{r.stop(),a.surplusActionRunning=!1,t.setStatus(n&&o?n:null,!1),R()}}async function tl(){let e=pa(),t=Kc(e);if(xe())return;if(!at()){t.log("收藏数据已损坏,为保护物品已停止分解","err");return}if(Un(e).length===0){t.log(t.emptyGem,"warn");return}a.surplusActionRunning=!0,R();let r=oe(jt(a.cfg),()=>Wc(t)),n=null,s=0,o=0;try{t.log("开始读取选中资产的可分解宝石值","info");let i=await Cm(e,t,r);if(i.plan.length===0){n="没有可转化宝石的选中项目",t.log(n,"warn");return}if(!await Mm(i)){n="已取消转化宝石";return}for(let l=0;l0&&Yc(e)}catch(i){n=`无法转化宝石: ${i?.message||i}`,t.log(n,"err")}finally{r.stop(),a.surplusActionRunning=!1,t.setStatus(n&&o?n:null,!1),R()}}var rl={card:"卡牌",background:"背景",emoticon:"表情"};function Em(){let e=document.getElementById("stch-surplus-item-mode")?.value||a.cfg.surplusItemMode||"card";return["card","background","emoticon"].includes(e)?e:"card"}function jn(e,t=""){let r=document.getElementById("stch-collection-status");r&&(r.textContent=e||"",r.className=`stch-status-text ${t}`.trim(),r.style.display=e?"":"none")}function sl(){let e=Em(),t=e==="card"?Hn():zn();if(t.length===0)return;let r=ei(t.map(n=>({...n,category:e,itemName:n.itemName||n.cardName||n.marketHashName})));if(!r.ok){jn(r.error,"err");return}a.selectedSurplusResults=new Set,a.selectedGrindResults=new Set,ce(),pe(),dr(),jn(`已收藏 ${r.added} 项,共 ${r.total} 项`,"ok"),R()}function al(){let e=a.selectedItemCollection||new Set;if(e.size===0)return;let t=ti(e);if(!t.ok){jn(t.error,"err");return}a.selectedItemCollection=new Set,dr(),ce(),pe(),jn(`已移除 ${t.removed} 项收藏`,"ok"),R()}function ol(e){a.selectedItemCollection=new Set(e?(a.itemCollectionItems||[]).map(t=>t.key):[]),dr()}function dr(){let e=document.getElementById("stch-collection-list");if(!e)return;a.selectedItemCollection||(a.selectedItemCollection=new Set);let t=a.itemCollectionItems||[],r=new Set(t.map(n=>n.key));for(let n of[...a.selectedItemCollection])r.has(n)||a.selectedItemCollection.delete(n);if(Yt(e,{isSelected:n=>a.selectedItemCollection.has(n.dataset.key),setSelected:(n,s)=>{s?a.selectedItemCollection.add(n.dataset.key):a.selectedItemCollection.delete(n.dataset.key)},onSelectionChange:nl}),e.innerHTML="",e.classList.add("stch-inventory-grid"),!at())Mt(e,"收藏数据已损坏;为保护物品,出售和分解已停用");else if(t.length===0)Mt(e,"暂无收藏");else for(let n of t){let s=document.createElement("div");s.className="stch-inv-tile stch-collection-tile",s.dataset.key=n.key,s.classList.toggle("selected",a.selectedItemCollection.has(n.key)),s.title=[n.gameName,n.itemName||n.marketHashName,`类型:${rl[n.category]||"物品"}`,"收藏中的物品不会出现在出售或分解候选中"].filter(Boolean).join(` `),Qt(s,n.imageUrl,n.itemName||n.marketHashName);let o=document.createElement("span");o.className="stch-inv-badge stch-inv-badge-left",o.textContent=rl[n.category]||"物品",s.appendChild(o);let i=document.createElement("div");i.className="stch-inv-name",i.textContent=n.itemName||n.marketHashName||"未知物品",s.appendChild(i),e.appendChild(s)}nl()}function nl(){let e=a.itemCollectionItems?.length||0,t=a.selectedItemCollection?.size||0,r=document.getElementById("stch-collection-summary");r&&(r.textContent=`已收藏 ${e} 项 · 已选择 ${t} 项`);let n=document.getElementById("stch-collection-select-all");n&&(n.textContent=e>0&&t===e?"取消全选":"全选",n.classList.toggle("disabled",e===0)),document.getElementById("stch-collection-remove")?.classList.toggle("disabled",t===0||!at())}function il(){dr()}function cl(e){let t=0;for(let r=0;r(\d{17})<\/steamID64>/);return s?s[1]:""}catch{return""}}function Am(e,t,r,n){let s=(e.body?.innerText||e.body?.textContent||"").replace(/\u00a0/g," "),i=(vn(e,[".profile_small_header_name > a",".profile_small_header_name",".profile_header .persona_name .actual_persona_name",".profile_header .persona_name_text_content",".actual_persona_name","#global_actions .persona"])||vn(document,["#global_actions .persona"])).replace(/\s*».*$/,"").trim(),c=[".profile_small_header_avatar > .playerAvatar > picture img",".profile_small_header_avatar > .playerAvatar > img",".profile_header .playerAvatar > picture img",".profile_header .playerAvatar > img",".playerAvatarAutoSizeInner > img","#global_actions a.user_avatar > img"],l=Es(e,c)||Es(document,c)||Er(Ms(e,["meta[property='og:image']","meta[name='twitter:image']","link[rel='image_src']"],"content")||Ms(e,["link[rel='image_src']"],"href")),u=St(vn(e,[".profile_xp_block .friendPlayerLevelNum",".friendPlayerLevelNum"])),d=[...s.matchAll(/([\d,,]+)\s*(?:点经验值|XP)/gi)].map(S=>St(S[1])).filter(Boolean),m=d.length>0?Math.max(...d):0,p=u?u+1:0,h=0,f=s.match(/升到\s*(\d+)\s*级还需\s*([\d,,]+)\s*点经验值/i),g=s.match(/([\d,,]+)\s*XP\s*(?:needed|required).*?Level\s*(\d+)/i);f?(p=St(f[1])||p,h=St(f[2])):g?(h=St(g[1]),p=St(g[2])||p):u&&m&&(h=Math.max(0,cl(u+1)-m));let y=u?ll(u):0,b=y?Math.max(0,y-h):0;return{avatar:l,name:i||"Steam 用户",level:u,totalXp:m,nextLevel:p,remainingXp:h,stepXp:y,earnedThisLevel:b,profileUrl:r,steamId:n,html:t}}async function ul(){let e=Q();if(!e)throw new Error("未找到个人资料地址");let t="";location.hostname==="steamcommunity.com"&&location.pathname.includes("/badges")?t=document.documentElement.outerHTML:t=await On(`${e}/badges/`);let r=await Nm(e,t),n=new DOMParser().parseFromString(t,"text/html");return Am(n,t,e,r)}var Wr=!1,Ne={profile:null,gems:null,gemPrice:null,error:""};function mr(e,t,r=""){let n=document.getElementById(e);n&&(n.textContent=t,n.title=r||t)}function Vn(){let e=Ne.profile||{},t=Ne.gems||{},r=Ne.gemPrice||{},n=document.getElementById("stch-sidebar-avatar");n&&e.avatar&&(n.src=e.avatar);let s=Number.isFinite(Number(e.remainingXp))&&Number.isFinite(Number(e.stepXp))&&Number(e.stepXp)>0;mr("stch-sidebar-name",e.name||"Steam 用户"),mr("stch-sidebar-level",e.level?`Lv ${ie(e.level)}`:"—"),mr("stch-sidebar-xp",e.totalXp?`${ie(e.totalXp)} 点`:"—"),mr("stch-sidebar-next",s?`${ie(e.remainingXp)} / ${ie(e.stepXp)}`:"—");let o=document.getElementById("stch-sidebar-progress-bar");if(o){let f=e.stepXp?Math.min(100,Math.max(0,e.earnedThisLevel/e.stepXp*100)):0;o.style.width=`${f}%`}let i=Number.isFinite(t.totalGems)?`${ie(t.totalGems)} 宝石${t.sackCount?`(${ie(t.sackCount)} 宝石袋)`:""}`:"—";mr("stch-sidebar-gems",i);let c=document.getElementById("stch-sidebar-gem-price");if(c)if(c.replaceChildren(),r.priceCents){let f=Number(r.previousPriceCents)||0;if(f>0){let g=r.priceCents-f,y=document.createElement("span");y.className=g>0?"stch-sidebar-price-rise":g<0?"stch-sidebar-price-fall":"stch-sidebar-price-flat",y.textContent=g===0?`(±${w(0)}) `:`(${g>0?"+":""}${w(g)}) `,c.appendChild(y)}c.appendChild(document.createTextNode(`${1e3}宝石/${w(r.priceCents)}`))}else c.textContent="—";let l=r.priceCents?cr(r.priceCents):0,u=r.priceCents?`${r.source}${r.volume?`,成交量 ${ie(r.volume)}`:""},税后到手约 ${w(l)}`:"暂无宝石袋市场价格";c&&(c.title=u);let d=r.priceCents?lr(10,r.priceCents):0,m=d?`按宝石袋税后到手 ${w(l)} 计算;物品卖出税后低于该值时,分解成宝石更值`:"暂无宝石袋市场价格";mr("stch-sidebar-grind-threshold",d?`10宝石/${w(d)}`:"—",m);let p=document.getElementById("stch-sidebar-status");p&&(p.textContent=Wr?"正在刷新账号信息、库存宝石和市场价格...":Ne.error||(e.name?"已同步当前账号信息":"鼠标移入侧栏后可查看信息"));let h=document.getElementById("stch-sidebar-refresh");h&&(h.disabled=Wr)}async function Kn({forceGemPrice:e=!1}={}){if(!J(Wr||a.sidebarPriceRefreshing)){e&&Rc(),Wr=!0,a.sidebarPriceRefreshing=!0,Ne.error="",Vn(),R();try{let t=await ul();Ne.profile=t,Vn();let[r,n]=await Promise.allSettled([Ac(t.steamId),ir()]);if(r.status==="fulfilled"?Ne.gems=r.value:Ne.error=r.reason?.message||"库存宝石读取失败",n.status==="fulfilled"){let s=Number(n.value?.priceCents)||0,o=Number(n.value?.currencyId||a?.currencyContext?.currencyId||a?.cfg?.currencyId||23),i=GM_getValue(Qn,null),c=typeof i=="object"?Number(i?.currencyId||23):23,l=Number(c===o&&typeof i=="object"?i?.priceCents:c===o?i:0)||0;Ne.gemPrice={...n.value,previousPriceCents:l},s>0&&GM_setValue(Qn,{schemaVersion:2,currencyId:o,priceCents:s,observedAt:Date.now()})}else Ne.error||(Ne.error=n.reason?.message||"宝石价格读取失败")}catch(t){Ne.error=t?.message||"侧栏信息读取失败"}finally{Wr=!1,a.sidebarPriceRefreshing=!1,Vn(),R()}}}function fa(e){let t=document.getElementById("stch-sidebar");if(!t)return;t.classList.toggle("pinned",e),GM_setValue(Wn,!!e);let r=document.getElementById("stch-sidebar-pin");r&&(r.textContent=e?"收起":"固定")}function dl(e){if(!e){document.getElementById("stch-sidebar")?.remove();return}ha()}function ha(){if(document.getElementById("stch-sidebar"))return;let e=document.createElement("aside");e.id="stch-sidebar",e.innerHTML=`
Steam 用户
当前等级
当前经验值
距离下一级
当前宝石
宝石价格参考
分解临界点
正在准备侧栏信息...
`,document.body.appendChild(e);let t=!!GM_getValue(Wn,!1);fa(t),document.getElementById("stch-sidebar-pin")?.addEventListener("click",r=>{r.stopPropagation(),fa(!e.classList.contains("pinned"))}),document.getElementById("stch-sidebar-handle")?.addEventListener("click",r=>{r.stopPropagation(),fa(!e.classList.contains("pinned"))}),document.getElementById("stch-sidebar-refresh")?.addEventListener("click",r=>{r.stopPropagation(),Kn({forceGemPrice:!0})}),Vn(),Kn()}function ga(e){return fr([...e?.querySelectorAll?.(".stch-tab[data-tab]")||[]].map(t=>t.dataset.tab))}function ba(e){let t=[...e.querySelectorAll(".stch-tab[data-tab]")];for(let n of t)n.classList.remove("stch-tab-right");let r=t.at(-1);r?.dataset.tab==="settings"&&r.classList.add("stch-tab-right")}function ml(e,t){if(!e)return[];let r=new Map([...e.querySelectorAll(".stch-tab[data-tab]")].map(s=>[s.dataset.tab,s])),n=fr(t);for(let s of n){let o=r.get(s);o&&e.appendChild(o)}return ba(e),ga(e)}function ya(e,t){let r=Ht(t);for(let n of e?.querySelectorAll?.(".stch-tab[data-tab]")||[]){let s=r[n.dataset.tab]||"";n.classList.toggle("stch-tab-custom-color",!!s),s?n.style.setProperty("--stch-tab-label-color",s):n.style.removeProperty("--stch-tab-label-color")}return r}function pl(e,t){if(!e||e.dataset.dragReordering==="1")return;e.dataset.dragReordering="1";let r=null,n=0,s=()=>{if(!r)return;let{tab:i,initialOrder:c,active:l}=r;if(r=null,document.removeEventListener("mousemove",o),document.removeEventListener("mouseup",s),window.removeEventListener("blur",s),i.classList.remove("stch-tab-dragging"),e.classList.remove("stch-tabs-dragging"),!l)return;n=Date.now()+250;let u=ga(e);ba(e),u.join(",")!==c&&t?.(u)},o=i=>{if(!r)return;if(!r.active){if(Math.hypot(i.clientX-r.startX,i.clientY-r.startY)<5)return;r.active=!0,r.tab.classList.add("stch-tab-dragging"),e.classList.add("stch-tabs-dragging")}let c=document.elementFromPoint(i.clientX,i.clientY)?.closest?.(".stch-tab[data-tab]");if(c&&c!==r.tab&&e.contains(c)){let l=c.getBoundingClientRect(),u=i.clientX{if(i.button!==0)return;let c=i.target instanceof Element?i.target.closest(".stch-tab[data-tab]"):null;!c||!e.contains(c)||(s(),r={tab:c,startX:i.clientX,startY:i.clientY,initialOrder:ga(e).join(","),active:!1},document.addEventListener("mousemove",o,{passive:!1}),document.addEventListener("mouseup",s),window.addEventListener("blur",s))}),e.addEventListener("click",i=>{if(Date.now()>n)return;let c=i.target instanceof Element?i.target.closest(".stch-tab[data-tab]"):null;!c||!e.contains(c)||(i.preventDefault(),i.stopImmediatePropagation())},!0)}var va="steam-trading-card-helper-backup";var xa=Object.freeze(["stch_config","stch_order_cache","stch_market_cache","stch_market_history","stch_market_watchlist","stch_item_collection","stch_sidebar_gem_price","stch_sidebar_pinned","stch_onboarding_seen"]);function fl(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sa(e){if(!fl(e)||e.format!==va||Number(e.backupVersion)!==1||!fl(e.storage))throw new Error("不是受支持的 Steam 卡牌助手备份");let t=Object.keys(e.storage).filter(n=>!xa.includes(n));if(t.length)throw new Error(`备份包含未知数据项:${t.join(", ")}`);let r={};for(let n of xa)Object.prototype.hasOwnProperty.call(e.storage,n)&&(r[n]=e.storage[n]);if(!Object.keys(r).length)throw new Error("备份中没有可导入的数据");return{format:va,backupVersion:1,exportedAt:String(e.exportedAt||""),storage:r}}function hl(e,t=Date.now()){if(typeof e!="function")throw new TypeError("缺少数据读取函数");let r={};for(let n of xa)r[n]=e(n,null);return{format:va,backupVersion:1,exportedAt:new Date(t).toISOString(),storage:r}}function gl(e){return JSON.stringify(Sa(e),null,2)}function bl(e){let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{throw new Error("备份文件不是有效 JSON")}return Sa(t)}function yl(e,{getValue:t,setValue:r}){if(typeof t!="function"||typeof r!="function")throw new TypeError("缺少数据读写函数");let n=Sa(e),s=Object.keys(n.storage),o=new Map(s.map(c=>[c,t(c,null)])),i=[];try{for(let c of s)r(c,n.storage[c]),i.push(c)}catch(c){for(let l of i.reverse())try{r(l,o.get(l))}catch{}throw new Error(`导入失败,已尝试恢复原数据:${c?.message||c}`)}return{restored:s.length,keys:s}}function vl(e=Date.now()){return`steam-card-helper-backup-${new Date(e).toISOString().replace(/[:.]/g,"-")}.json`}var Dt=null;function Rm(e){return e?.source==="walletInfo"?"Steam 钱包识别":e?.source==="application_config"?"Steam 页面钱包识别":e?.source==="page"?"市场页面识别":e?.isFallback||e?.source==="configured"?"用户设置回退":"未识别"}function Ca(e=he()){return e?.currencyId?`${e.code} (${e.symbol}) · ${Rm(e)}${e.verified?"":" · 格式/费用规则未验证"}`:"未识别币种"}var _m=[["lowest","在售最低"],["median","平均价格"],["highest","求购最高"]],$m=[["conservative","保守"],["balanced","平衡"],["aggressive","抢单"]],Pm=Object.freeze({conservative:"保守",balanced:"平衡",aggressive:"抢单"}),wa=Object.entries(vt).map(([e,t])=>({id:e,label:Pm[e],...t}));function xl(e,t){return(e?$m:_m).map(([n,s])=>``).join("")}function pr(e,t=!1){let r=["conservative","balanced","aggressive"].includes(e)?e:O.automaticPriceStrategy;return(t||!a.automaticPricingDraft||a.automaticPricingDraft.strategy!==r)&&(a.automaticPricingDraft=Da(a.cfg,r)),a.automaticPricingDraft}function Om(){a.results=[],a.selectedResults=new Set,a.orderResults=hn(),a.selectedOrderResults=new Set,a.pendingOrderQuantities=new Map,a.highestBuyPrices=new Map,a.marketOrderDepths=new Map,pc(),Vi(),a.surplusResults=[],a.selectedSurplusResults=new Set,a.surplusGemPrice=null,a.grindResults=[],a.selectedGrindResults=new Set,a.grindGemPrice=null}function Sl(e){let t=he();if(t&&!t.isFallback&&t.source!=="unresolved")return a.currencyContext=t,!1;let r=Wa(we(e,{source:"configured",isFallback:!0}));return a.currencyContext=r,t?.currencyId!==r?.currencyId?(Om(),!0):!1}function Cl(e){if(!e)return 0;let t=getComputedStyle(e);return t.display==="none"?0:e.getBoundingClientRect().height+(parseFloat(t.marginTop)||0)+(parseFloat(t.marginBottom)||0)}function Bm(e){e.querySelectorAll(".stch-log-resizer").forEach(t=>{let r=document.getElementById(t.dataset.log);if(!r||t.dataset.ready==="1")return;t.dataset.ready="1";let n=t.dataset.content?document.getElementById(t.dataset.content):null;t.addEventListener("pointerdown",s=>{if(s.button!==0)return;s.preventDefault();let o=t.closest(".stch-tab-content")||e,i=o.getBoundingClientRect().height||window.innerHeight,c=s.clientY,l=r.getBoundingClientRect().height||160,u=82,d=n?82:42,m=[...o.children].reduce((g,y)=>y===r||y===t||y===n?g:g+Cl(y),0),p=Math.max(u,i-m-Cl(t)-d-12);n&&(n.style.flex="1 1 0",n.style.maxHeight="none",n.style.minHeight=`${d}px`),r.style.minHeight=`${u}px`;let h=g=>{let y=g.clientY-c,b=Math.max(u,Math.min(p,l-y));r.style.flex=`0 0 ${b}px`,r.style.height=`${b}px`},f=()=>{t.classList.remove("dragging"),document.body.classList.remove("stch-log-resizing"),document.removeEventListener("pointermove",h),document.removeEventListener("pointerup",f),document.removeEventListener("pointercancel",f)};t.classList.add("dragging"),document.body.classList.add("stch-log-resizing"),document.addEventListener("pointermove",h),document.addEventListener("pointerup",f),document.addEventListener("pointercancel",f)})})}function kl(){if(Dt){Dt.style.display="";let e=document.getElementById("stch-backdrop");e&&(e.style.display="block");return}ka()}function ka(e={}){let t=e.initialTab||"scan",r=v=>t===v?"active":"",n=he(),s=n?.symbol||"¤",o=Ca(n),i=a.cfg.automaticPricingEnabled===!0,c=i?a.cfg.automaticPriceStrategy:a.cfg.orderPriceSource,l=i?pr(c):null,u=i?l.noWallOffsetMinor/100:a.cfg.priceAdjustment,d=l?.wallOffsetMinor/100||0,m=xl(i,c),p=i?"stch-auto-pricing-active":"",h=wa.map(v=>`
${v.label}
`).join(""),f=tn.map(({id:v,label:C})=>` `).join(""),g=document.createElement("div");g.id="stch-backdrop",g.style.display="block",g.addEventListener("click",wl),document.body.appendChild(g);let y=document.createElement("div");y.id="stch-modal",y.addEventListener("click",v=>v.stopPropagation()),y.innerHTML=`

Steam 卡牌助手

价格扫描 订购卡牌 订购单 价格走势 徽章合成 黑名单 多余物品 物品收藏 设置
开始扫描
停止
跳过当前
重新计算
提交订购单
已保存 0 项
范围
加入
重新计算
提交订购单
尚未读取订购单 已选 0 项
扫描
停止
全部 1 次
全部最大
全部清零
确认合成
查询游戏
一键清理过期
开始检测
停止
全选
收藏选中
出售
转化宝石
已收藏 0 项 · 已选择 0 项
全选
移除选中
全局设定
当前使用:${o}
购买价格
${h}
* 订单墙是靠近有效最高买价、订单数量相对前面邻近价位显著增加的连续区域;墙顶是该区域最高价,墙底是最低价。
卡牌价格扫描
游戏/AppID 黑名单
徽章合成
多余物品处理
Tab 标签颜色
${f}
留空恢复默认
使用说明
导出文件
导入数据
清除缓存
恢复默认设定
`,document.body.appendChild(y);let b=y.querySelector(".stch-tabs");a.cfg.tabOrder=ml(b,a.cfg.tabOrder),a.cfg.tabColors=ya(b,a.cfg.tabColors),pl(b,v=>{a.cfg.tabOrder=v,ue(a.cfg)}),Dt=y,Bm(y),y.querySelector(".stch-close").addEventListener("click",wl);let S=v=>{y.querySelectorAll("[data-settings-page]").forEach(C=>{C.classList.toggle("active",C.dataset.settingsPage===v)}),y.querySelectorAll("[data-settings-panel]").forEach(C=>{C.classList.toggle("active",C.dataset.settingsPanel===v)})};y.querySelectorAll("[data-settings-page]").forEach(v=>{v.addEventListener("click",()=>S(v.dataset.settingsPage))});let M=document.getElementById("stch-personalization-status"),E=(v,C)=>{let k=v.dataset.tabColor,$=v.value.trim(),_=Xn($),se=$===""||!!_;if(v.classList.toggle("invalid",!se),!se){M&&(M.textContent="请输入六位 HEX 色值");return}let H={...a.cfg.tabColors||{}};_?H[k]=_:delete H[k],a.cfg.tabColors=Ht(H),ya(b,a.cfg.tabColors),M&&(M.textContent=""),C&&(v.value=_,ue(a.cfg),M&&(M.textContent=_?"颜色已保存":"已恢复默认颜色"))};y.querySelectorAll(".stch-tab-color-input[data-tab-color]").forEach(v=>{v.addEventListener("input",()=>E(v,!1)),v.addEventListener("blur",()=>E(v,!0)),v.addEventListener("keydown",C=>{C.key==="Enter"&&v.blur()})});let x=(v,C,k={})=>{let $=document.getElementById(v)?.value,_=k.integer?parseInt($,10):parseFloat($);return Number.isFinite(_)?(k.integer&&(_=Math.floor(_)),Number.isFinite(k.min)&&(_=Math.max(k.min,_)),Number.isFinite(k.max)&&(_=Math.min(k.max,_)),_):C},I=()=>{let v=document.getElementById("stch-surplus-item-mode")?.value||a.cfg.surplusItemMode||O.surplusItemMode;return["card","background","emoticon"].includes(v)?v:"card"},N=()=>{let v=I(),C=document.getElementById("stch-surplus-card-panel"),k=document.getElementById("stch-surplus-grind-panel");C?.classList.toggle("active",v==="card"),k?.classList.toggle("active",v!=="card"),ce(),pe(),Me()},A=v=>{let C=a.cfg.surplusItemMode||O.surplusItemMode;a.cfg.threshold=x("stch-threshold",a.cfg.threshold??O.threshold,{min:0}),a.cfg.requestInterval=x("stch-req-interval",a.cfg.requestInterval??O.requestInterval,{integer:!0,min:0}),a.cfg.maxBadgePages=x("stch-max-pages",a.cfg.maxBadgePages??O.maxBadgePages,{integer:!0,min:1}),a.cfg.includeDrops=!!document.getElementById("stch-include-drops")?.checked,a.cfg.foilScanMode=!!document.getElementById("stch-foil-scan-mode")?.checked,a.cfg.showScanCompletionColumn=!!document.getElementById("stch-show-scan-completion-column")?.checked,a.cfg.showScanSellSetColumn=!!document.getElementById("stch-show-scan-sell-set-column")?.checked,a.cfg.showNoResultLogs=!!document.getElementById("stch-show-no-result-logs")?.checked,a.cfg.showAdvancedSettings=!!document.getElementById("stch-show-advanced-settings")?.checked,a.cfg.sidebarDisabled=!!document.getElementById("stch-sidebar-disabled")?.checked,a.cfg.parallelOrderPricingEnabled=!!document.getElementById("stch-parallel-order-pricing")?.checked,a.cfg.parallelOrderPricingConcurrency=x("stch-parallel-order-pricing-concurrency",a.cfg.parallelOrderPricingConcurrency??O.parallelOrderPricingConcurrency,{integer:!0,min:1,max:20}),a.cfg.parallelOtherRequestsEnabled=!!document.getElementById("stch-parallel-other-requests")?.checked,a.cfg.parallelOtherRequestsConcurrency=x("stch-parallel-other-requests-concurrency",a.cfg.parallelOtherRequestsConcurrency??O.parallelOtherRequestsConcurrency,{integer:!0,min:1,max:20});let k=document.getElementById("stch-buy-mode");a.cfg.foilScanMode?a.cfg.buyMode=k?.dataset.normalValue||a.cfg.buyMode||O.buyMode:(a.cfg.buyMode=k?.dataset.normalValue||k?.value||a.cfg.buyMode,k&&delete k.dataset.normalValue),a.cfg.earlyPricePrediction=!!document.getElementById("stch-early-price-prediction")?.checked,a.cfg.minimumPriceFallback=!!document.getElementById("stch-minimum-price-fallback")?.checked,wa.forEach(_=>{let se=document.getElementById(`stch-auto-${_.id}-wall-anchor`)?.value;a.cfg[_.anchorKey]=["top","bottom"].includes(se)?se:a.cfg[_.anchorKey],a.cfg[_.wallOffsetKey]=x(`stch-auto-${_.id}-wall-offset`,a.cfg[_.wallOffsetKey]??O[_.wallOffsetKey]),a.cfg[_.noWallOffsetKey]=x(`stch-auto-${_.id}-no-wall-offset`,a.cfg[_.noWallOffsetKey]??O[_.noWallOffsetKey])}),a.cfg.earlyPredictionAutoBlacklist=!!document.getElementById("stch-settings-early-prediction-auto-blacklist")?.checked,a.cfg.orderCacheDays=x("stch-order-cache-days",a.cfg.orderCacheDays??O.orderCacheDays,{integer:!0,min:0}),a.cfg.skipCachedOrderResults=!!document.getElementById("stch-skip-cached-orders")?.checked,a.cfg.surplusOnlyTradable=!!document.getElementById("stch-surplus-only-tradable")?.checked,a.cfg.surplusOnlyRecommended=!!document.getElementById("stch-surplus-only-recommended")?.checked,a.cfg.surplusItemMode=I(),a.cfg.surplusSellPriceSource=document.getElementById("stch-surplus-sell-price-source")?.value||a.cfg.surplusSellPriceSource||O.surplusSellPriceSource,a.cfg.surplusSellPriceAdjustment=x("stch-surplus-sell-adjustment",a.cfg.surplusSellPriceAdjustment??O.surplusSellPriceAdjustment),a.cfg.grindReserveCopies=x("stch-grind-reserve-copies",a.cfg.grindReserveCopies??O.grindReserveCopies,{integer:!0,min:0}),a.cfg.grindIncludePointsShopItems=!!document.getElementById("stch-grind-include-points-shop")?.checked,a.cfg.craftInterval=x("stch-craft-interval",a.cfg.craftInterval??O.craftInterval,{integer:!0,min:200}),a.cfg.craftMode=document.getElementById("stch-craft-mode")?.value||a.cfg.craftMode,ue(a.cfg);let $=document.getElementById("stch-craft-max-pages");$&&($.value=String(a.cfg.maxBadgePages)),tr(),kn(),Ot(),v==="stch-order-cache-days"&&(Le(!0),ge()),v==="stch-craft-mode"&&_e(),v==="stch-sidebar-disabled"&&dl(!a.cfg.sidebarDisabled),v==="stch-show-advanced-settings"&&document.getElementById("stch-tab-settings")?.classList.toggle("stch-show-advanced",a.cfg.showAdvancedSettings),["stch-surplus-only-tradable","stch-surplus-only-recommended"].includes(v)&&(ce(),pe()),v==="stch-surplus-item-mode"&&(a.cfg.surplusItemMode!==C&&(a.grindResults=[],a.selectedGrindResults=new Set,a.grindGemPrice=null),N()),["stch-grind-reserve-copies","stch-grind-include-points-shop"].includes(v)&&(a.grindResults=[],a.selectedGrindResults=new Set,a.grindGemPrice=null),v?.startsWith("stch-grind-")&&pe(),v?.startsWith("stch-auto-")&&v!=="stch-auto-pricing"&&(dt(),$r())};["stch-threshold","stch-req-interval","stch-max-pages","stch-include-drops","stch-foil-scan-mode","stch-parallel-order-pricing","stch-parallel-order-pricing-concurrency","stch-parallel-other-requests","stch-parallel-other-requests-concurrency","stch-show-scan-completion-column","stch-show-scan-sell-set-column","stch-show-no-result-logs","stch-show-advanced-settings","stch-sidebar-disabled","stch-buy-mode","stch-early-price-prediction","stch-minimum-price-fallback","stch-settings-early-prediction-auto-blacklist","stch-order-cache-days","stch-skip-cached-orders","stch-craft-interval","stch-craft-mode","stch-surplus-item-mode","stch-surplus-only-tradable","stch-surplus-only-recommended","stch-surplus-sell-price-source","stch-surplus-sell-adjustment","stch-grind-reserve-copies","stch-grind-include-points-shop",...wa.flatMap(v=>[`stch-auto-${v.id}-wall-anchor`,`stch-auto-${v.id}-wall-offset`,`stch-auto-${v.id}-no-wall-offset`])].forEach(v=>{let C=document.getElementById(v);C&&(C.addEventListener("input",()=>A(v)),C.addEventListener("change",()=>A(v)))});let T=["stch-order-price-source","stch-order-page-price-source"],L=["stch-price-adjustment","stch-order-page-price-adjustment"],z=["stch-price-wall-adjustment","stch-order-page-price-wall-adjustment"],D=["stch-auto-pricing","stch-order-page-auto-pricing"],q=()=>{Rt(),ge(),dt(),$r()},be=(v="")=>{let C=a.cfg.automaticPricingEnabled===!0,k=C?a.cfg.automaticPriceStrategy||O.automaticPriceStrategy:a.cfg.orderPriceSource||O.orderPriceSource,$=C?pr(k):null,_=C?$.noWallOffsetMinor/100:a.cfg.priceAdjustment??O.priceAdjustment,se=$?.wallOffsetMinor/100||0;T.forEach(H=>{let W=document.getElementById(H);W&&(W.innerHTML=xl(C,k),W.value=k)}),L.forEach(H=>{if(H===v)return;let W=document.getElementById(H);W&&(W.value=String(_))}),z.forEach(H=>{if(H!==v){let $a=document.getElementById(H);$a&&($a.value=String(se))}let W=document.getElementById(`${H}-label`);W&&(W.style.display=C?"":"none")}),["stch-price-adjustment-text","stch-order-page-price-adjustment-text"].forEach(H=>{let W=document.getElementById(H);W&&(W.textContent=C?"无墙调整":"买价调整")}),D.forEach(H=>{let W=document.getElementById(H);W&&(W.checked=C)}),["stch-order-price-label","stch-price-wall-adjustment-label","stch-price-adjustment-label","stch-order-page-price-label","stch-order-page-price-wall-adjustment-label","stch-order-page-price-adjustment-label"].forEach(H=>{document.getElementById(H)?.classList.toggle("stch-auto-pricing-active",C)}),y.querySelectorAll(".stch-auto-pricing-toggle").forEach(H=>{H.classList.toggle("stch-auto-pricing-active",C)})};T.forEach(v=>{document.getElementById(v)?.addEventListener("change",C=>{a.cfg.automaticPricingEnabled?(a.cfg.automaticPriceStrategy=C.currentTarget.value,pr(a.cfg.automaticPriceStrategy,!0)):a.cfg.orderPriceSource=C.currentTarget.value,be(),ue(a.cfg),q()})});let gt=(v,C=!1)=>{let k=parseFloat(v.currentTarget.value),$=Number.isFinite(k)?k:0;if(a.cfg.automaticPricingEnabled){let _=pr(a.cfg.automaticPriceStrategy);_.noWallOffsetMinor=Math.round($*100)}else a.cfg.priceAdjustment=$;be(C?"":v.currentTarget.id),a.cfg.automaticPricingEnabled||ue(a.cfg),q()};L.forEach(v=>{let C=document.getElementById(v);C?.addEventListener("input",k=>gt(k,!1)),C?.addEventListener("change",k=>gt(k,!0))});let He=(v,C=!1)=>{let k=parseFloat(v.currentTarget.value),$=Number.isFinite(k)?k:0,_=pr(a.cfg.automaticPriceStrategy);_.wallOffsetMinor=Math.round($*100),be(C?"":v.currentTarget.id),q()};z.forEach(v=>{let C=document.getElementById(v);C?.addEventListener("input",k=>He(k,!1)),C?.addEventListener("change",k=>He(k,!0))}),D.forEach(v=>{document.getElementById(v)?.addEventListener("change",C=>{a.cfg.automaticPricingEnabled=C.currentTarget.checked,a.cfg.automaticPricingEnabled&&pr(a.cfg.automaticPriceStrategy,!0),be(),ue(a.cfg),q()})}),be();let Ye=v=>{v!=="history"&&Mn({silent:!0}),y.querySelectorAll(".stch-tab").forEach(C=>{C.classList.toggle("active",C.dataset.tab===v)}),y.querySelectorAll(".stch-tab-content").forEach(C=>{C.classList.toggle("active",C.id===`stch-tab-${v}`)}),v==="blacklist"&&Fe(),v==="orders"&&ge(),v==="active-orders"&&mc(),v==="history"&&ji(),v==="surplus"&&N(),v==="collection"&&il()},Se=()=>{GM_setValue(Yn,!0),Ye("scan");let v=document.getElementById("stch-onboarding");v&&(v.style.display="flex")},bt=()=>{let v=document.getElementById("stch-onboarding");v&&(v.style.display="none")},Je=null,ne=v=>{let C=document.getElementById("stch-settings-action-status");C&&(C.textContent=v,Je&&clearTimeout(Je),Je=v?setTimeout(()=>{C.textContent=""},3500):null)},Qr=()=>gl(hl((v,C)=>GM_getValue(v,C))),Nl=async v=>{if(!v.currentTarget.classList.contains("disabled"))try{let C=Qr(),k=vl(),$=window.showSaveFilePicker;if(typeof $=="function")try{let W=await(await $.call(window,{suggestedName:k,types:[{description:"Steam 卡牌助手备份",accept:{"application/json":[".json"]}}]})).createWritable();await W.write(C),await W.close(),ne("已导出");return}catch(H){if(H?.name==="AbortError")throw H;console.warn("[STCH] File picker unavailable; falling back to download:",H)}let _=URL.createObjectURL(new Blob([C],{type:"application/json"})),se=document.createElement("a");se.href=_,se.download=k,se.click(),setTimeout(()=>URL.revokeObjectURL(_),1e3),ne("已导出")}catch(C){if(C?.name==="AbortError"){ne("已取消导出");return}ne(`导出失败:${C?.message||C}`)}},Al=async v=>{let C=v.currentTarget,k=C.files?.[0];if(C.value="",!!k){if(xe()||a.sidebarPriceRefreshing){ne("请先停止当前操作,再导入数据");return}try{let $=bl(await k.text()),_=Object.keys($.storage).length;if(!confirm(`将覆盖本机 ${_} 项设置与缓存,确定导入?`))return;let se=yl($,{getValue:(H,W)=>GM_getValue(H,W),setValue:(H,W)=>GM_setValue(H,W)});ne(`已导入 ${se.restored} 项数据,请刷新页面`)}catch($){ne(`导入失败:${$?.message||$}`)}}};document.getElementById("stch-currency-fallback")?.addEventListener("change",v=>{let C=v.currentTarget,k=Number(a.cfg.currencyId||O.currencyId);if(xe()){C.value=String(k),ne("请先停止当前操作,再修改回退币种");return}let $=Number(C.value);if(![1,23,29].includes($)){C.value=String(k),ne("不支持的回退币种");return}if(a.cfg.currencyId=$,ue(a.cfg),!Sl($)){ne(`回退币种已保存;当前仍使用 ${Ca()}`);return}y.remove(),document.getElementById("stch-backdrop")?.remove(),Dt=null,ka({initialTab:"settings",suppressOnboarding:!0});let se=document.getElementById("stch-settings-action-status");se&&(se.textContent=`已切换到 ${Ca()},请重新查价`),document.getElementById("stch-sidebar")&&Kn().catch(H=>{console.warn("[STCH] Sidebar refresh after currency change failed:",H)})});let Rl=v=>{if(v.currentTarget.classList.contains("disabled"))return;let C=Ko().length;if(C===0){xs(),ge(),R(),ne("订购缓存为空");return}confirm(`将移除 ${C} 项订购卡牌缓存,确定?`)&&(xs(),ge(),R(),ne(`已移除 ${C} 项缓存`))},_l=v=>{if(v.currentTarget.classList.contains("disabled")||xe()||a.sidebarPriceRefreshing){ne("请先停止当前操作,再恢复默认设置"),R();return}if(!confirm("将恢复所有设置项为默认值。游戏/AppID黑名单和订购缓存会保留,确定?"))return;let k=Object.fromEntries(["blacklist","blacklistNames","blacklistSources","blacklistDates","blacklistFixed","blacklistPriceData"].map(_=>[_,a.cfg[_]??O[_]]));a.cfg={...O,...k},ue(a.cfg),Sl(a.cfg.currencyId),y.remove(),document.getElementById("stch-backdrop")?.remove(),Dt=null,ka({initialTab:"settings",suppressOnboarding:!0});let $=document.getElementById("stch-settings-action-status");$&&($.textContent="已恢复默认设定")};y.querySelectorAll(".stch-tab[data-tab]").forEach(v=>{v.addEventListener("click",()=>{Ye(v.dataset.tab)})}),document.getElementById("stch-onboarding-close").addEventListener("click",bt),document.getElementById("stch-onboarding-open")?.addEventListener("click",Se),document.getElementById("stch-settings-import-data")?.addEventListener("click",()=>{document.getElementById("stch-settings-import-file")?.click()}),document.getElementById("stch-settings-export-data")?.addEventListener("click",Nl),document.getElementById("stch-settings-import-file")?.addEventListener("change",Al),document.getElementById("stch-settings-clear-cache")?.addEventListener("click",Rl),document.getElementById("stch-settings-reset")?.addEventListener("click",_l),document.getElementById("stch-scan-btn").addEventListener("click",Ei),document.getElementById("stch-stop-btn").addEventListener("click",Ni),document.getElementById("stch-skip-btn").addEventListener("click",Mi),document.getElementById("stch-recalculate-btn").addEventListener("click",Ri),document.getElementById("stch-submit-orders-btn").addEventListener("click",sc),document.getElementById("stch-order-add-btn").addEventListener("click",ec),document.getElementById("stch-order-recalculate-btn").addEventListener("click",_i),document.getElementById("stch-order-submit-orders-btn").addEventListener("click",ac),ta(),document.getElementById("stch-craft-scan-btn").addEventListener("click",gc),document.getElementById("stch-craft-stop-btn").addEventListener("click",yc),document.getElementById("stch-craft-one-btn").addEventListener("click",()=>_n("one")),document.getElementById("stch-craft-max-btn").addEventListener("click",()=>_n("max")),document.getElementById("stch-craft-clear-btn").addEventListener("click",()=>_n("clear")),document.getElementById("stch-craft-submit-btn").addEventListener("click",bc),document.getElementById("stch-surplus-scan-btn").addEventListener("click",v=>{v.currentTarget.classList.contains("disabled")||(I()==="card"?Dc():jc())}),document.getElementById("stch-surplus-stop-btn").addEventListener("click",v=>{v.currentTarget.classList.contains("disabled")||(a.surplusScanning?Hc():a.grindScanning&&Vc())}),document.getElementById("stch-surplus-select-all-btn").addEventListener("click",v=>{if(v.currentTarget.classList.contains("disabled"))return;let C=I(),k=document.getElementById(C==="card"?"stch-surplus-list":"stch-grind-list"),$=k?[...k.querySelectorAll(".stch-inv-tile")]:[],_=$.length>0&&$.every(se=>se.classList.contains("selected"));C==="card"?Fc(!_):Uc(!_),R()}),document.getElementById("stch-surplus-sell-btn").addEventListener("click",v=>{v.currentTarget.classList.contains("disabled")||(el(),R())}),document.getElementById("stch-surplus-collect-btn").addEventListener("click",v=>{v.currentTarget.classList.contains("disabled")||sl()}),document.getElementById("stch-surplus-gem-btn").addEventListener("click",v=>{v.currentTarget.classList.contains("disabled")||(tl(),R())}),document.getElementById("stch-collection-select-all").addEventListener("click",v=>{if(v.currentTarget.classList.contains("disabled"))return;let C=a.itemCollectionItems?.length||0,k=a.selectedItemCollection?.size||0;ol(!(C>0&&k===C))}),document.getElementById("stch-collection-remove").addEventListener("click",v=>{v.currentTarget.classList.contains("disabled")||al()});let Ia=v=>{a.cfg.maxBadgePages=Math.max(1,parseInt(v.target.value,10)||O.maxBadgePages);let C=document.getElementById("stch-max-pages");C&&(C.value=String(a.cfg.maxBadgePages)),ue(a.cfg)},Ma=document.getElementById("stch-craft-max-pages");Ma.addEventListener("input",Ia),Ma.addEventListener("change",Ia);let Ea=["stch-auto-bl-enabled","stch-settings-auto-bl-enabled"],Na=["stch-auto-bl-threshold","stch-settings-auto-bl-threshold"],Aa=["stch-blacklist-expiry-days","stch-settings-blacklist-expiry-days"],Yr=(v="")=>{Ea.forEach(k=>{if(k===v)return;let $=document.getElementById(k);$&&($.checked=!!a.cfg.autoBlackEnabled)}),Na.forEach(k=>{if(k===v)return;let $=document.getElementById(k);$&&($.value=String(a.cfg.autoBlackThreshold??0))}),Aa.forEach(k=>{if(k===v)return;let $=document.getElementById(k);$&&($.value=String(a.cfg.blacklistExpiryDays))});let C=document.getElementById("stch-bl-cleanup");C&&(C.title=`清理超过 ${a.cfg.blacklistExpiryDays} 天的普通黑名单;固定黑名单不会清理`)};Ea.forEach(v=>{document.getElementById(v)?.addEventListener("change",C=>{a.cfg.autoBlackEnabled=!!C.currentTarget.checked,Yr(),ue(a.cfg)})}),Ws();let Ra=(v,C=!1)=>{let k=parseFloat(v.currentTarget.value);a.cfg.autoBlackThreshold=Number.isFinite(k)?Math.max(0,k):0,Yr(C?"":v.currentTarget.id),ue(a.cfg)};Na.forEach(v=>{let C=document.getElementById(v);C?.addEventListener("input",k=>Ra(k,!1)),C?.addEventListener("change",k=>Ra(k,!0))});let _a=(v,C=!1)=>{let k=parseInt(v.currentTarget.value,10);a.cfg.blacklistExpiryDays=Number.isFinite(k)?Math.max(1,k):O.blacklistExpiryDays,Yr(C?"":v.currentTarget.id),ue(a.cfg)};Aa.forEach(v=>{let C=document.getElementById(v);C?.addEventListener("input",k=>_a(k,!1)),C?.addEventListener("change",k=>_a(k,!0))}),Yr(),Ot(),!e.suppressOnboarding&&!GM_getValue(Yn,!1)&&Se(),document.getElementById("stch-bl-lookup").addEventListener("click",()=>{let v=document.getElementById("stch-bl-appid").value.trim();if(!v||!/^\d+$/.test(v)){document.getElementById("stch-bl-result").textContent="请输入有效的 AppID";return}document.getElementById("stch-bl-result").textContent="查询中...",ui(v).then(C=>{a.blLookupAppid=v,a.blLookupName=C,document.getElementById("stch-bl-result").textContent=C?`${v} — ${C}`:"未找到该游戏",it()})}),document.getElementById("stch-bl-add").addEventListener("click",()=>{!a.blLookupAppid||!a.blLookupName||!Jt(a.blLookupAppid,a.blLookupName,0,0).ok||(document.getElementById("stch-bl-result").textContent=`${a.blLookupName} 已加入游戏黑名单`,document.getElementById("stch-bl-appid").value="",a.blLookupAppid="",a.blLookupName="",it(),Fe())}),document.getElementById("stch-bl-add-fixed").addEventListener("click",()=>{!a.blLookupAppid||!a.blLookupName||!Jt(a.blLookupAppid,a.blLookupName,0,1).ok||(document.getElementById("stch-bl-result").textContent=`${a.blLookupName} 已加入固定游戏黑名单`,document.getElementById("stch-bl-appid").value="",a.blLookupAppid="",a.blLookupName="",it(),Fe())}),document.getElementById("stch-bl-del-sel").addEventListener("click",()=>{let v=document.getElementById("stch-bl-list"),C=document.getElementById("stch-bl-list-fixed");if(!v)return;let k=[...v.querySelectorAll(".stch-bl-cb:checked")];C&&k.push(...C.querySelectorAll(".stch-bl-cb:checked")),!(k.length===0||!Ps(k.map(_=>_.dataset.appid)).ok)&&(it(),Fe())}),document.getElementById("stch-bl-fix-sel").addEventListener("click",()=>{let v=document.getElementById("stch-bl-list"),C=document.getElementById("stch-bl-list-fixed");if(!v)return;let k=[...v.querySelectorAll(".stch-bl-cb:checked")];C&&k.push(...C.querySelectorAll(".stch-bl-cb:checked")),!(k.length===0||!Os(k.map(_=>_.dataset.appid),!0).ok)&&(it(),Fe())}),document.getElementById("stch-bl-unfix-sel").addEventListener("click",()=>{let v=document.getElementById("stch-bl-list"),C=document.getElementById("stch-bl-list-fixed");if(!v)return;let k=[...v.querySelectorAll(".stch-bl-cb:checked")];C&&k.push(...C.querySelectorAll(".stch-bl-cb:checked")),!(k.length===0||!Os(k.map(_=>_.dataset.appid),!1).ok)&&(it(),Fe())}),document.getElementById("stch-bl-cleanup").addEventListener("click",()=>{let v=Math.max(1,Number(a.cfg.blacklistExpiryDays)||O.blacklistExpiryDays),C=li(v);if(!C.ok){Fe();return}let k=C.appids;if(k.length===0){document.getElementById("stch-bl-result").textContent="没有可清理的过期项";return}!confirm(`将清理 ${k.length} 项过期(>${v}天)游戏黑名单,确定?`)||!Ps(k).ok||(document.getElementById("stch-bl-result").textContent=`已清理 ${k.length} 项`,Fe())}),Fe(),N(),ce(),pe(),dr(),Le(!0),ge(),Rt(),R()}function wl(){Mn({silent:!0});let e=document.getElementById("stch-backdrop");e&&(e.style.display="none"),Dt&&(Dt.style.display="none")}function Lm(){let e=document.getElementById("stch-entry-btn");return e||(e=document.createElement("span"),e.id="stch-entry-btn",e.className="stch-btn-entry",e.textContent="Steam Trading Card Helper",e.addEventListener("click",kl),e)}function Tm(e){let t=document.querySelector(".inventory_rightnav");if(!t)return!1;let r=t.querySelector("#inventory_reload_button, .reload_inventory"),n=t.querySelector(".new_trade_offer_btn, a[href*='/tradeoffers/']");return!r&&!n?!1:(e.classList.add("stch-inventory-entry"),n?.parentElement===t?t.insertBefore(e,n):r?.parentElement===t&&r.nextSibling?t.insertBefore(e,r.nextSibling):t.appendChild(e),!0)}function Il(){let e=Lm();if(e.classList.remove("stch-inventory-entry"),Xa())return Tm(e);let t=document.querySelector(".profile_xp_block")||document.querySelector(".badges_header")||document.body;return t.classList.contains("profile_xp_block")?t.appendChild(e):t.insertBefore(e,t.firstChild),!0}function Ml(){if(Il())return;let e=0,t=new MutationObserver(()=>{e+=1,(Il()||e>=80)&&t.disconnect()});t.observe(document.documentElement,{childList:!0,subtree:!0}),setTimeout(()=>t.disconnect(),2e4)}GM_addStyle(Pa);a.currencyContext=Ka({configuredCurrencyId:a.cfg.currencyId});a.orderResults=hn();Le(!0);Zo();var Fm=window.location.href,El=e=>{document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()};Fm.includes("/market/multibuy")?El(()=>{if(!Jr){console.warn("[STCH] jQuery not found");return}hi()}):El(()=>{Ml(),a.cfg.sidebarDisabled||ha()});})();