import { itemDefinition, itemDisplayName, itemAssetPathForStack, formatQuantity } from "/shared/definitions/items.js"; import { insertStack } 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 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 sellSection = document.getElementById("shop-sell-section"); const sellList = document.getElementById("shop-sell-list"); const sellDetail = document.getElementById("shop-sell-detail"); const sellPrice = document.getElementById("shop-sell-price"); const sellFee = document.getElementById("shop-sell-fee"); const sellConfirm = document.getElementById("shop-sell-confirm"); const qtyBackdrop = document.getElementById("shop-qty-backdrop"); const qtyPanel = document.getElementById("shop-qty-panel"); 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"; 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(); }); 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()); document.getElementById("shop-qty-close")?.addEventListener("click", () => closeQtyModal()); document.getElementById("shop-qty-confirm")?.addEventListener("click", () => confirmQtyBuy()); qtyBackdrop?.addEventListener("click", () => closeQtyModal()); qtyInput?.addEventListener("keydown", (event) => { if (event.key === "Enter") { confirmQtyBuy(); } }); sellConfirm?.addEventListener("click", () => sellSelected()); 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; } closeQtyModal(); render(); 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"; 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) { 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) }, 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 () { const entry = selectedEntry(); if (!entry) { return; } const max = maxBuyable(entry); if (max < 1) { return; } qtyInput.value = String(Math.min(max, 1)); qtyHint.textContent = `Max ${max}`; qtyBackdrop.hidden = false; qtyPanel.hidden = false; suppressWorldClick(); qtyInput.focus(); qtyInput.select(); } function closeQtyModal () { qtyBackdrop.hidden = true; qtyPanel.hidden = true; } function confirmQtyBuy () { 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 sellSelected () { if (!npcEntityId || selectedSellSlotIndex == null || !selectedSellSlot()) { return; } socket.send({ type: MessageType.sellToShop, npcEntityId, slotIndex: selectedSellSlotIndex, quantity: 1 }); } function renderSellDetail () { if (!sellDetail || !sellPrice || !sellFee || !sellConfirm) { return; } const slot = selectedSellSlot(); if (!slot) { sellDetail.hidden = true; sellFee.hidden = true; return; } const quote = resolveShopSellQuote(slot, { quantity: 1 }); if (!quote) { sellDetail.hidden = true; sellFee.hidden = true; return; } sellDetail.hidden = false; sellPrice.textContent = quote.isCheque ? `You receive ${formatQuantity(quote.payout)} coins` : `${formatQuantity(quote.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 = ""; } sellConfirm.disabled = false; } function renderSellList () { if (!sellSection || !sellList) { return; } if (!buysItems) { sellSection.hidden = true; selectedSellSlotIndex = null; if (sellDetail) { sellDetail.hidden = true; } return; } sellSection.hidden = false; sellList.innerHTML = ""; const slots = getInventorySlots?.() ?? []; const sellableIndexes = []; slots.forEach((slot, slotIndex) => { if (!slot?.itemId || !canPlayerSellToNpc(slot)) { return; } sellableIndexes.push(slotIndex); }); if (selectedSellSlotIndex != null && !sellableIndexes.includes(selectedSellSlotIndex)) { selectedSellSlotIndex = null; } if (selectedSellSlotIndex == null && sellableIndexes.length) { selectedSellSlotIndex = sellableIndexes[0]; } if (!sellableIndexes.length) { sellList.textContent = `Nothing ${subjectPronoun(sex)} will buy in your bag.`; selectedSellSlotIndex = null; renderSellDetail(); return; } for (const slotIndex of sellableIndexes) { const slot = slots[slotIndex]; const row = document.createElement("button"); row.type = "button"; row.className = "shop-sell-row"; if (slotIndex === selectedSellSlotIndex) { row.classList.add("selected"); } row.textContent = `${itemDisplayName(slot)} ×${formatQuantity(slot.quantity)}`; row.addEventListener("click", () => { selectedSellSlotIndex = slotIndex; renderSellList(); }); sellList.append(row); } renderSellDetail(); } function render () { grid.innerHTML = ""; const coins = getCoinCount?.() ?? 0; coinsEl.textContent = `Coins: ${formatQuantity(coins)}`; if (!stock.length) { grid.textContent = buysItems ? "No stock for sale right now." : "Nothing for sale."; detail.hidden = true; bagWarn.hidden = true; renderSellList(); return; } for (const entry of stock) { const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId }); 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, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId })); btn.append(img); btn.addEventListener("click", () => { selectedListingId = entry.listingId; render(); }); grid.append(btn); } const entry = selectedEntry(); if (!entry) { detail.hidden = true; bagWarn.hidden = true; renderSellList(); return; } detail.hidden = false; const name = entry.displayName ?? itemDisplayName({ itemId: entry.itemId }); detailName.textContent = name; detailPrice.textContent = `${formatQuantity(entry.unitPrice)} coins each`; detailStock.textContent = entry.available == null ? "In stock" : `Stock: ${formatQuantity(entry.available)}`; applyItemIcon(detailIcon, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId })); 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); renderSellList(); } 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 }; }