import { itemDefinition, itemDisplayName, itemAssetPathForStack, formatQuantity } from "/shared/definitions/items.js"; import { insertStack, stackQuantity } from "/shared/items/inventory.js"; import { canPlayerSellToNpc, resolveShopSellQuote } from "/shared/shop/pricing.js"; import { subjectPronoun } from "/shared/speech/pronouns.js"; import { applyItemIcon } from "../render/potionIcon.js"; export function initShop ({ socket, MessageType, getCoinCount, getInventorySlots, onSuppressWorldClick }) { const backdrop = document.getElementById("shop-backdrop"); const panel = document.getElementById("shop-panel"); const title = document.getElementById("shop-title"); const tabBuy = document.getElementById("shop-tab-buy"); const tabSell = document.getElementById("shop-tab-sell"); const paneBuy = document.getElementById("shop-pane-buy"); const paneSell = document.getElementById("shop-pane-sell"); const grid = document.getElementById("shop-grid"); const detail = document.getElementById("shop-detail"); const detailIcon = document.getElementById("shop-detail-icon"); const detailName = document.getElementById("shop-detail-name"); const detailPrice = document.getElementById("shop-detail-price"); const detailStock = document.getElementById("shop-detail-stock"); const bagWarn = document.getElementById("shop-bag-warn"); const coinsEl = document.getElementById("shop-coins"); const sellGrid = document.getElementById("shop-sell-grid"); const sellDetail = document.getElementById("shop-sell-detail"); const sellIcon = document.getElementById("shop-sell-icon"); const sellName = document.getElementById("shop-sell-name"); const sellPrice = document.getElementById("shop-sell-price"); const sellFee = document.getElementById("shop-sell-fee"); const sellActions = document.getElementById("shop-sell-actions"); const sellEmpty = document.getElementById("shop-sell-empty"); const qtyBackdrop = document.getElementById("shop-qty-backdrop"); const qtyPanel = document.getElementById("shop-qty-panel"); const qtyTitle = document.getElementById("shop-qty-title"); const qtyConfirm = document.getElementById("shop-qty-confirm"); const qtyInput = document.getElementById("shop-qty-input"); const qtyHint = document.getElementById("shop-qty-hint"); let npcEntityId = null; let stock = []; let selectedListingId = null; let selectedSellSlotIndex = null; let buysItems = false; let displayName = "Shop"; let sex = "male"; /** @type {"buy"|"sell"} */ let activeTab = "buy"; /** @type {"buy"|"sell"|null} */ let qtyMode = null; function suppressWorldClick () { onSuppressWorldClick?.(); } document.getElementById("shop-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("mousedown", (event) => { event.preventDefault(); suppressWorldClick(); }); backdrop?.addEventListener("click", () => close()); panel?.addEventListener("mousedown", (event) => { event.stopPropagation(); suppressWorldClick(); }); qtyBackdrop?.addEventListener("mousedown", (event) => { event.preventDefault(); suppressWorldClick(); }); qtyPanel?.addEventListener("mousedown", (event) => { event.stopPropagation(); suppressWorldClick(); }); tabBuy?.addEventListener("click", () => setTab("buy")); tabSell?.addEventListener("click", () => setTab("sell")); document.getElementById("shop-buy-1")?.addEventListener("click", () => buy(1)); document.getElementById("shop-buy-5")?.addEventListener("click", () => buy(5)); document.getElementById("shop-buy-10")?.addEventListener("click", () => buy(10)); document.getElementById("shop-buy-x")?.addEventListener("click", () => openQtyModal("buy")); document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal()); qtyConfirm?.addEventListener("click", () => confirmQtyModal()); qtyBackdrop?.addEventListener("click", () => closeQtyModal()); qtyInput?.addEventListener("keydown", (event) => { if (event.key === "Enter") { confirmQtyModal(); } }); function setTab (tab) { if (tab === "sell" && !buysItems) { tab = "buy"; } activeTab = tab; const buyActive = tab === "buy"; if (tabBuy) { tabBuy.classList.toggle("active", buyActive); tabBuy.setAttribute("aria-selected", buyActive ? "true" : "false"); } if (tabSell) { tabSell.classList.toggle("active", !buyActive); tabSell.setAttribute("aria-selected", buyActive ? "false" : "true"); } if (paneBuy) { paneBuy.hidden = !buyActive; } if (paneSell) { paneSell.hidden = buyActive; } render(); } function open (payload) { npcEntityId = payload.npcEntityId | 0; displayName = payload.displayName || "Shop"; sex = payload.sex === "female" ? "female" : "male"; title.textContent = displayName; buysItems = !!payload.buysItems; stock = Array.isArray(payload.stock) ? payload.stock : []; if (selectedListingId == null || !stock.some((row) => row.listingId === selectedListingId)) { selectedListingId = stock[0]?.listingId ?? null; } if (tabSell) { tabSell.hidden = !buysItems; } closeQtyModal(); setTab(buysItems && activeTab === "sell" ? "sell" : "buy"); backdrop.hidden = false; panel.hidden = false; suppressWorldClick(); } function close ({ notifyServer = true } = {}) { const closingNpcId = npcEntityId; closeQtyModal(); backdrop.hidden = true; panel.hidden = true; npcEntityId = null; stock = []; selectedListingId = null; selectedSellSlotIndex = null; buysItems = false; sex = "male"; activeTab = "buy"; suppressWorldClick(); if (notifyServer && closingNpcId) { socket.send({ type: MessageType.closeShop, npcEntityId: closingNpcId }); } } function selectedEntry () { return stock.find((row) => row.listingId === selectedListingId) ?? null; } function maxBuyable (entry) { const price = Math.max(1, entry?.unitPrice | 0 || 1); const coins = getCoinCount?.() ?? 0; const affordable = Math.max(0, Math.floor(coins / price)); const available = entry?.available == null ? affordable : Math.max(0, entry.available | 0); return Math.min(affordable, available); } function inventoryFits (itemId, quantity, instance = null) { const def = itemDefinition(itemId); if (!def) { return false; } const slots = getInventorySlots?.() ?? []; const added = insertStack(slots.map((slot) => (slot ? structuredClone(slot) : null)), { itemId, quantity: Math.max(1, quantity | 0 || 1), instance: instance ? structuredClone(instance) : null }, def); return added.ok && added.remainder === 0; } function buy (quantity) { const entry = selectedEntry(); if (!npcEntityId || !entry) { return; } const qty = Math.max(1, quantity | 0 || 1); const max = maxBuyable(entry); if (qty > max) { return; } socket.send({ type: MessageType.buyFromShop, npcEntityId, itemId: entry.itemId, quantity: qty, listingId: entry.listingId, source: entry.source }); } function openQtyModal (mode) { qtyMode = mode; if (mode === "buy") { const entry = selectedEntry(); if (!entry) { return; } const max = maxBuyable(entry); if (max < 1) { return; } if (qtyTitle) { qtyTitle.textContent = "Buy quantity"; } if (qtyConfirm) { qtyConfirm.textContent = "Buy"; } qtyInput.min = "1"; qtyInput.max = String(max); qtyInput.value = String(Math.min(max, 1)); qtyHint.textContent = `Max ${max}`; } else { const slot = selectedSellSlot(); if (!slot) { return; } const max = Math.max(1, stackQuantity(slot.quantity)); if (max < 4) { return; } if (qtyTitle) { qtyTitle.textContent = "Sell quantity"; } if (qtyConfirm) { qtyConfirm.textContent = "Sell"; } qtyInput.min = "1"; qtyInput.max = String(max); qtyInput.value = "1"; qtyHint.textContent = `Max ${max}`; } qtyBackdrop.hidden = false; qtyPanel.hidden = false; suppressWorldClick(); qtyInput.focus(); qtyInput.select(); } function closeQtyModal () { qtyMode = null; qtyBackdrop.hidden = true; qtyPanel.hidden = true; } function confirmQtyModal () { if (qtyMode === "sell") { const slot = selectedSellSlot(); if (!slot) { closeQtyModal(); return; } const max = Math.max(1, stackQuantity(slot.quantity)); const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1)); closeQtyModal(); sellQuantity(qty); return; } const entry = selectedEntry(); if (!entry) { closeQtyModal(); return; } const max = maxBuyable(entry); const qty = Math.min(max, Math.max(1, Number(qtyInput.value) | 0 || 1)); closeQtyModal(); buy(qty); } function selectedSellSlot () { if (selectedSellSlotIndex == null) { return null; } const slots = getInventorySlots?.() ?? []; const slot = slots[selectedSellSlotIndex]; if (!slot?.itemId || !canPlayerSellToNpc(slot)) { return null; } return slot; } function sellQuantity (quantity) { if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot()) { return; } const slot = selectedSellSlot(); const max = Math.max(1, stackQuantity(slot.quantity)); const qty = Math.min(max, Math.max(1, quantity | 0 || 1)); socket.send({ type: MessageType.sellToShop, npcEntityId, slotIndex: selectedSellSlotIndex, quantity: qty }); } function renderSellActions (slot) { if (!sellActions) { return; } sellActions.replaceChildren(); const qty = Math.max(1, stackQuantity(slot.quantity)); const addBtn = (label, onClick) => { const btn = document.createElement("button"); btn.type = "button"; btn.textContent = label; btn.addEventListener("click", onClick); sellActions.append(btn); }; if (qty <= 1) { addBtn("Sell", () => sellQuantity(1)); return; } addBtn("Sell 1", () => sellQuantity(1)); if (qty === 2) { addBtn("Sell all", () => sellQuantity(qty)); return; } if (qty === 3) { addBtn("Sell 2", () => sellQuantity(2)); addBtn("Sell all", () => sellQuantity(qty)); return; } addBtn("Sell x", () => openQtyModal("sell")); addBtn("Sell all", () => sellQuantity(qty)); } function renderSellDetail () { if (!sellDetail || !sellPrice || !sellFee) { return; } const slot = selectedSellSlot(); if (!slot) { sellDetail.hidden = true; sellFee.hidden = true; if (sellActions) { sellActions.replaceChildren(); } return; } const quote = resolveShopSellQuote(slot, { quantity: Math.max(1, stackQuantity(slot.quantity)) }); const unitQuote = resolveShopSellQuote(slot, { quantity: 1 }); if (!quote || !unitQuote) { sellDetail.hidden = true; sellFee.hidden = true; return; } sellDetail.hidden = false; if (sellEmpty) { sellEmpty.hidden = true; } const name = itemDisplayName(slot); if (sellName) { sellName.textContent = name; } if (sellIcon) { applyItemIcon(sellIcon, slot, itemAssetPathForStack(slot)); } sellPrice.textContent = quote.isCheque ? `You receive ${formatQuantity(quote.payout)} coins` : `${formatQuantity(unitQuote.unitPrice)} coins each`; if (quote.isCheque) { sellFee.hidden = false; sellFee.textContent = `${formatQuantity(quote.adminFee)} coins charged as administrative fee`; } else { sellFee.hidden = true; sellFee.textContent = ""; } renderSellActions(slot); } function renderSellPane () { if (!sellGrid) { return; } sellGrid.replaceChildren(); if (!buysItems) { return; } const slots = getInventorySlots?.() ?? []; const sellableIndexes = []; slots.forEach((slot, slotIndex) => { if (slot?.itemId && canPlayerSellToNpc(slot)) { sellableIndexes.push(slotIndex); } }); if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex)) { selectedSellSlotIndex = null; } if (!sellableIndexes.length) { selectedSellSlotIndex = null; if (sellDetail) { sellDetail.hidden = true; } if (sellEmpty) { sellEmpty.hidden = true; } const note = document.createElement("p"); note.className = "hint"; note.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`; sellGrid.append(note); return; } if (sellEmpty) { sellEmpty.hidden = true; } if (selectedSellSlotIndex == null) { if (sellDetail) { sellDetail.hidden = false; if (sellName) { sellName.textContent = "Select an item"; } if (sellIcon) { sellIcon.removeAttribute("src"); sellIcon.alt = ""; } if (sellPrice) { sellPrice.textContent = ""; } if (sellFee) { sellFee.hidden = true; } if (sellActions) { sellActions.replaceChildren(); } } } slots.forEach((slot, slotIndex) => { const button = document.createElement("button"); button.type = "button"; button.className = "item-slot"; const sellable = !!slot?.itemId && canPlayerSellToNpc(slot); if (!slot) { button.disabled = true; sellGrid.append(button); return; } if (!sellable) { button.classList.add("disabled"); } if (slotIndex === selectedSellSlotIndex) { button.classList.add("selected"); } const img = document.createElement("img"); img.alt = itemDisplayName(slot); applyItemIcon(img, slot, itemAssetPathForStack(slot)); button.append(img); const qty = stackQuantity(slot.quantity); if (qty > 1) { const count = document.createElement("span"); count.className = "qty"; count.textContent = formatQuantity(qty); button.append(count); } button.title = itemDisplayName(slot); button.addEventListener("click", () => { if (!sellable) { return; } selectedSellSlotIndex = slotIndex; render(); }); sellGrid.append(button); }); if (selectedSellSlotIndex != null) { renderSellDetail(); } } function renderBuyPane () { grid.innerHTML = ""; if (!stock.length) { grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale."; detail.hidden = true; bagWarn.hidden = true; return; } for (const entry of stock) { const stack = { itemId: entry.itemId, instance: entry.instance ?? null }; const name = entry.displayName ?? itemDisplayName(stack); const btn = document.createElement("button"); btn.type = "button"; btn.className = "shop-cell"; if (entry.listingId === selectedListingId) { btn.classList.add("selected"); } btn.title = name; const img = document.createElement("img"); img.alt = name; applyItemIcon(img, stack, itemAssetPathForStack(stack)); btn.append(img); btn.addEventListener("click", () => { selectedListingId = entry.listingId; render(); }); grid.append(btn); } const entry = selectedEntry(); if (!entry) { detail.hidden = true; bagWarn.hidden = true; return; } detail.hidden = false; const detailStack = { itemId: entry.itemId, instance: entry.instance ?? null }; const name = entry.displayName ?? itemDisplayName(detailStack); detailName.textContent = name; detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`; detailStock.textContent = entry.available == null ? "In stock" : `Stock: ${formatQuantity(entry.available)}`; applyItemIcon(detailIcon, detailStack, itemAssetPathForStack(detailStack)); const max = maxBuyable(entry); const setBuy = (id, qty) => { const el = document.getElementById(id); if (!el) { return; } el.disabled = max < qty; }; setBuy("shop-buy-1", 1); setBuy("shop-buy-5", 5); setBuy("shop-buy-10", 10); const buyX = document.getElementById("shop-buy-x"); if (buyX) { buyX.disabled = max < 1; } bagWarn.hidden = inventoryFits(entry.itemId, 1, entry.instance ?? null); } function render () { const coins = getCoinCount?.() ?? 0; coinsEl.textContent = `Coins: ${formatQuantity(coins)}`; if (tabSell) { tabSell.hidden = !buysItems; } if (activeTab === "sell" && buysItems) { renderSellPane(); } else { renderBuyPane(); } } function handleShopOpen (message) { open(message); } function handleShopClosed (message) { if ((message?.npcEntityId | 0) === npcEntityId) { close({ notifyServer: false }); } } function refresh () { if (npcEntityId != null && !panel.hidden) { render(); } } return { handleShopOpen, handleShopClosed, refresh, close, isBlocking: () => !panel.hidden || !qtyPanel.hidden, isOpen: () => !panel.hidden }; }