// The in-game browser can open the storefront or deep-link to a pack by its GUID. 'use strict'; const T = { zh: { store: '商城', toMarket: '交易所', account: '本地账号', eagles: '金鹰', lions: '银狮', premium: '高级账户', premiumOff: '未开通', premiumLeft: '剩余 {days} 天', tabPacks: '高级载具', tabEagles: '金鹰', tabPremium: '高级账户', tabRedeem: '兑换码', search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级', sort: '商品排序', sortBest: '最畅销', sortNewest: '最新上架', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低', containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户', buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号', redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品', featured: '推荐礼包', bestSeller: '畅销', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格', includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益', bonusText: '驾驶高级载具可在战斗中获得额外的研发点和银狮。', footer: '购买后关闭商城窗口,机库会自动刷新。', gallery: '礼包媒体', cover: '封面', screenshot: '截图 {index}', screenshotLoading: '正在加载官方截图…', screenshotUnavailable: '官方截图暂不可用,当前显示游戏载具图。', previousMedia: '上一项', nextMedia: '下一项', video: '演示视频', videoNumber: '演示视频 {index}', playVideo: '播放演示', videoLoading: '正在加载演示视频…', videoUnavailable: '暂时无法播放官方视频,可以继续浏览其他素材。', cart: '购物车', addCart: '加入购物车', inCart: '已在购物车', confirmPurchase: '确认购买', cartEmpty: '购物车里还没有商品。', remove: '移除', removeItem: '移除 {name}', unavailable: '商品已下架', total: '合计', balance: 'GJN 余额', payGjn: '用 GJN 结算', close: '关闭', keepShopping: '继续逛商城', cartBlocked: '移除已拥有或已下架的商品后即可结算。', lowBalance: 'GJN 余额不足。', buyFailed: '暂时无法确认结果,商城会重新读取账号状态。', loadFailed: '商城加载失败,请重新打开商城。', }, en: { store: 'Store', toMarket: 'Market', account: 'Local account', eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium', premiumOff: 'Inactive', premiumLeft: '{days} days left', tabPacks: 'Premium vehicles', tabEagles: 'Golden Eagles', tabPremium: 'Premium account', tabRedeem: 'Redeem code', search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}', sort: 'Sort products', sortBest: 'Top sellers', sortNewest: 'Newest', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low', containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account', buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first', redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters', featured: 'Featured packs', bestSeller: 'Top seller', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price', includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses', bonusText: 'Premium vehicles earn extra research points and Silver Lions in battle.', footer: 'Close the store window after buying to refresh the hangar.', gallery: 'Pack media', cover: 'Cover', screenshot: 'Screenshot {index}', screenshotLoading: 'Loading official screenshot…', screenshotUnavailable: 'The official screenshot is unavailable. Showing game artwork.', previousMedia: 'Previous item', nextMedia: 'Next item', video: 'Demo video', videoNumber: 'Demo video {index}', playVideo: 'Play demo', videoLoading: 'Loading demo video…', videoUnavailable: 'The official video is unavailable. You can still browse the other media.', cart: 'Cart', addCart: 'Add to cart', inCart: 'In cart', confirmPurchase: 'Confirm purchase', cartEmpty: 'Your cart is empty.', remove: 'Remove', removeItem: 'Remove {name}', unavailable: 'No longer available', total: 'Total', balance: 'GJN balance', payGjn: 'Pay with GJN', close: 'Close', keepShopping: 'Continue shopping', cartBlocked: 'Remove owned or unavailable products to check out.', lowBalance: 'Your GJN balance is too low.', buyFailed: 'The result could not be confirmed. The store will reload your account.', loadFailed: 'The store could not load. Reopen the store to retry.', }, }; const TAB_LABEL = { 'vehicle-pack': 'tabPacks', eagles: 'tabEagles', 'premium-gjn': 'tabPremium' }; const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X']; const t = (key, params) => WtoUi.tr(T, key, params); const $ = (id) => document.getElementById(id); let initialGuid = (WtoUi.query.get('item') || '').toUpperCase(); let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] }; let currentTab = 'vehicle-pack'; let detailId = ''; let catalogScroll = 0; let loadVersion = 0; let loading = true; const checkout = createStoreCheckout(loadState); function applyStaticTexts() { for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t); for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label)); $('searchInput').placeholder = t('search'); $('codeInput').placeholder = t('codePlaceholder'); $('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/'); } function setLoading(value) { loading = value; $('accountSelect').disabled = value || !state.accounts.length; $('redeemBtn').disabled = value || !state.activeUserId; checkout.setAccountLoading(value); } async function loadState(userId) { const version = ++loadVersion; setLoading(true); try { const next = await WtoUi.getJson('/store/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : '')); if (version !== loadVersion) return; if (!Array.isArray(next?.accounts) || !Array.isArray(next.products)) throw new Error('Invalid store state'); if (userId && !next.activeUserId) { WtoUi.clearSavedAccount(); return await loadState(''); } state = next; WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId); $('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents); $('goldVal').textContent = WtoUi.num(state.balance.goldenEagles); $('silverVal').textContent = WtoUi.num(state.balance.silverLions); $('premVal').textContent = state.premiumDays > 0 ? t('premiumLeft', { days: state.premiumDays }) : t('premiumOff'); if (initialGuid) { const wanted = state.products.find((p) => (p.guid || '').toUpperCase() === initialGuid); if (wanted) { detailId = wanted.id; currentTab = wanted.kind; } initialGuid = ''; } checkout.setState(state); renderFilters(); render(); } catch (error) { if (version !== loadVersion) return; $('accountSelect').value = state.activeUserId; WtoUi.showNotice($('notice'), t('loadFailed'), false); } finally { if (version === loadVersion) setLoading(false); } } function fillSelect(select, firstText, values, textOf) { const previous = select.value; select.replaceChildren(new Option(firstText, '')); for (const value of values) select.appendChild(new Option(textOf(value), String(value), false, String(value) === previous)); } function renderFilters() { const packs = state.products.filter((p) => p.kind === 'vehicle-pack'); const countries = packs.flatMap((p) => p.vehicles.map((vehicle) => vehicle.country)).filter(Boolean); const ranks = [...new Set(packs.flatMap((p) => p.ranks || []))].sort((a, b) => a - b); fillSelect($('countryFilter'), t('allCountries'), [...new Set(countries)], WtoUi.label); fillSelect($('rankFilter'), t('allRanks'), ranks, rankLabel); } function matchesPack(product) { const query = $('searchInput').value.trim().toLowerCase(); const country = $('countryFilter').value; const rank = $('rankFilter').value; if (country && !product.vehicles.some((vehicle) => vehicle.country === country)) return false; if (rank && !product.ranks.map(String).includes(rank)) return false; if (!query) return true; const terms = [product.title.zh, product.title.en]; for (const vehicle of product.vehicles) terms.push(vehicle.unitName, vehicle.title.zh, vehicle.title.en); return terms.some((term) => (term || '').toLowerCase().includes(query)); } function render() { stopStoreGallery($('detail')); for (const tab of $('tabs').querySelectorAll('[data-tab]')) tab.setAttribute('aria-pressed', String(tab.dataset.tab === currentTab)); const product = state.products.find((item) => item.id === detailId); const redeeming = currentTab === 'redeem'; $('catalog').hidden = redeeming || !!product; $('detail').hidden = !product; $('redeemPanel').hidden = !redeeming; if (!product) $('detail').replaceChildren(); if (redeeming) return renderRedeemHelp(); if (product) return renderPackDetail($('detail'), product, checkout, state.products, openProduct, backToCatalog); renderCatalog(); } function renderCatalog() { const isPacks = currentTab === 'vehicle-pack'; $('catalogTitle').textContent = t(TAB_LABEL[currentTab]); $('packFilters').hidden = !isPacks; const sort = $('sortSelect').value; const filtered = $('countryFilter').value || $('rankFilter').value || $('searchInput').value.trim(); const items = state.products.filter((p) => p.kind === currentTab && (!isPacks || matchesPack(p))); if (isPacks) sortPacks(items, sort); const cards = items.map((item) => productCard(item, checkout, openProduct)); if (isPacks && !filtered && sort === 'best' && items.length) { const featured = items.find((item) => item.id === 'wto_pack_f-4s') || items[0]; cards.unshift(featuredBanner(featured, openProduct)); } if (!cards.length) cards.push(makeElement('p', 'empty', t('empty'))); $('grid').replaceChildren(...cards); } function sortPacks(items, mode) { const ids = WtoUi.storeOrder(mode === 'newest' ? 'newest' : 'best'); const positions = new Map(ids.map((id, index) => [id, index])); items.sort((a, b) => (positions.get(a.id) ?? ids.length) - (positions.get(b.id) ?? ids.length)); if (mode === 'priceAsc') items.sort((a, b) => a.gjnCostCents - b.gjnCostCents); if (mode === 'priceDesc') items.sort((a, b) => b.gjnCostCents - a.gjnCostCents); } function openProduct(product) { if (!detailId) catalogScroll = window.scrollY; detailId = product.id; currentTab = product.kind; render(); window.scrollTo(0, 0); $('detail').querySelector('h1').focus({ preventScroll: true }); } function backToCatalog() { detailId = ''; render(); window.scrollTo(0, catalogScroll); $('catalogTitle').focus({ preventScroll: true }); } function selectTab(tab) { currentTab = tab; detailId = ''; render(); window.scrollTo(0, 0); } function renderRedeemHelp() { $('redeemHelp').replaceChildren(...state.redeemHelp.map((line) => makeElement('li', '', WtoUi.text(line)))); } async function redeem() { const userId = state.activeUserId; if (!userId || loading) return; $('redeemBtn').disabled = true; try { const result = await WtoUi.postJson('/store/api/redeem', { userId, code: $('codeInput').value }); if ($('accountSelect').value !== userId) return; WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok); if (result.ok) $('codeInput').value = ''; } catch (error) { if ($('accountSelect').value !== userId) return; WtoUi.showNotice($('notice'), t('buyFailed'), false); } if ($('accountSelect').value === userId) await loadState(userId); } $('accountSelect').onchange = (event) => { $('notice').className = 'notice'; WtoUi.saveAccount(event.target.value); void loadState(event.target.value); }; $('storeHome').onclick = () => selectTab('vehicle-pack'); $('searchInput').oninput = renderCatalog; for (const id of ['countryFilter', 'rankFilter', 'sortSelect']) $(id).onchange = renderCatalog; $('redeemBtn').onclick = redeem; $('tabs').onclick = (event) => { const tab = event.target.closest('[data-tab]'); if (tab) selectTab(tab.dataset.tab); }; window.addEventListener('pagehide', () => stopStoreGallery($('detail'))); applyStaticTexts(); render(); Promise.allSettled([WtoUi.loadLabels(), WtoUi.loadImageSources(true)]).then(() => loadState(WtoUi.savedAccount()));