import { itemDefinition, itemDisplayName, itemAssetPathForStack, formatQuantity } from "/shared/definitions/items.js"; import { applyItemIcon } from "../render/potionIcon.js"; export function initShop ({ socket, MessageType, getCoinCount, onError }) { const backdrop = document.getElementById("shop-backdrop"); const panel = document.getElementById("shop-panel"); const title = document.getElementById("shop-title"); const list = document.getElementById("shop-stock"); const statusEl = document.getElementById("shop-status"); let npcEntityId = null; let stock = []; document.getElementById("shop-close")?.addEventListener("click", () => close()); backdrop?.addEventListener("click", () => close()); function open (payload) { npcEntityId = payload.npcEntityId | 0; title.textContent = payload.displayName || "Shop"; stock = Array.isArray(payload.stock) ? payload.stock : []; statusEl.textContent = ""; render(); backdrop.hidden = false; panel.hidden = false; } function close () { backdrop.hidden = true; panel.hidden = true; npcEntityId = null; stock = []; } function render () { list.innerHTML = ""; if (!stock.length) { list.textContent = "Nothing for sale."; return; } const coins = getCoinCount?.() ?? 0; for (const entry of stock) { const def = itemDefinition(entry.itemId); const row = document.createElement("div"); row.className = "shop-row"; const img = document.createElement("img"); img.alt = entry.displayName ?? def?.displayName ?? "item"; applyItemIcon(img, { itemId: entry.itemId }, itemAssetPathForStack({ itemId: entry.itemId })); const meta = document.createElement("div"); meta.className = "shop-row-meta"; const name = document.createElement("strong"); name.textContent = entry.displayName ?? itemDisplayName({ itemId: entry.itemId }); const price = document.createElement("span"); price.className = "hint"; price.textContent = `${formatQuantity(entry.unitPrice)} coins`; meta.append(name, price); const buy = document.createElement("button"); buy.type = "button"; buy.textContent = "Buy"; buy.disabled = coins < (entry.unitPrice | 0); buy.addEventListener("click", () => { if (!npcEntityId) { return; } socket.send({ type: MessageType.buyFromShop, npcEntityId, itemId: entry.itemId, quantity: 1 }); }); row.append(img, meta, buy); list.append(row); } } function handleShopOpen (message) { open(message); } function refresh () { if (npcEntityId != null && !panel.hidden) { render(); } } return { handleShopOpen, refresh, close, isOpen: () => !panel.hidden }; }