import { listAllItemPickerEntries, itemDefinition, ItemId } from "/shared/definitions/items.js"; import { listRecipePaperPickerEntries, listPotionPickerEntries, potionKeyFromListingKey, potionKeyFromPotionListingKey } from "/shared/market/listingKey.js"; import { formatGiftLetterBody, QUESTWARD_GIFT_AUTHOR, QUESTWARD_GIFT_ORG } from "/shared/courier/giftLetters.js"; import { formatLetterSignature } from "/shared/courier/systemLetters.js"; function giftItemPickerEntries () { const recipes = listRecipePaperPickerEntries(); const potions = listPotionPickerEntries(); const base = listAllItemPickerEntries() .filter((item) => item.itemId !== ItemId.recipePaper && item.itemId !== ItemId.potion) .map((item) => ({ ...item, listingKey: null, potionKey: null })); return [...base, ...recipes, ...potions] .sort((a, b) => a.displayName.localeCompare(b.displayName) || (a.itemId - b.itemId)); } function giftRowKey (row) { const itemId = row?.itemId | 0; if (itemId === ItemId.recipePaper && row?.potionKey) { return `recipe:${row.potionKey}`; } if (itemId === ItemId.potion && row?.potionKey) { return `potion:${row.potionKey}`; } if (row?.listingKey) { return `listing:${row.listingKey}`; } return `item:${itemId}`; } export function initGiftsModal ({ socket, MessageType }) { const backdrop = document.getElementById("gifts-backdrop"); const modal = document.getElementById("gifts-modal"); const resultsEl = document.getElementById("gifts-results"); const detailEl = document.getElementById("gifts-detail"); const statusEl = document.getElementById("gifts-status"); const searchInput = document.getElementById("gifts-search-input"); const searchBtn = document.getElementById("gifts-search-btn"); let open = false; /** @type {any[]} */ let characters = []; /** @type {any|null} */ let selected = null; /** @type {Array<{ itemId: number, quantity: number, displayName: string, listingKey?: string|null, potionKey?: string|null }>} */ let giftItems = []; let messageText = ""; /** @type {null | { resultsEl: HTMLElement, inputEl: HTMLInputElement }} */ let itemPickContext = null; function show (visible) { open = visible; backdrop.hidden = !visible; modal.hidden = !visible; if (!visible) { closeInlineItemSearch(); return; } render(); } function setStatus (text, isError = false) { if (!statusEl) { return; } statusEl.textContent = text || ""; statusEl.classList.toggle("error", !!isError); } function closeInlineItemSearch () { if (itemPickContext?.resultsEl) { itemPickContext.resultsEl.replaceChildren(); } itemPickContext = null; } function addGiftItem (item) { if (!item?.itemId) { return; } const listingKey = item.listingKey ?? null; const potionKey = item.potionKey ?? potionKeyFromListingKey(listingKey) ?? potionKeyFromPotionListingKey(listingKey) ?? null; const key = giftRowKey({ itemId: item.itemId, listingKey, potionKey }); const existing = giftItems.find((row) => giftRowKey(row) === key); if (existing) { existing.quantity = Math.min(100000, (existing.quantity | 0) + 1); } else { giftItems.push({ itemId: item.itemId, quantity: 1, displayName: item.displayName || itemDefinition(item.itemId)?.displayName || `Item ${item.itemId}`, listingKey, potionKey }); } closeInlineItemSearch(); renderDetail(); } function filterItemMatches (query) { const q = String(query ?? "").trim().toLowerCase(); const taken = new Set(giftItems.map((row) => giftRowKey(row))); return giftItemPickerEntries().filter((item) => { if (taken.has(giftRowKey(item))) { return false; } if (!q) { return true; } return item.displayName.toLowerCase().includes(q) || item.key.toLowerCase().includes(q) || String(item.itemId).includes(q) || String(item.potionKey ?? "").toLowerCase().includes(q); }).slice(0, 40); } function renderInlineItemSearch (query) { if (!itemPickContext) { return; } const { resultsEl: pickResults } = itemPickContext; pickResults.replaceChildren(); const matches = filterItemMatches(query); if (!matches.length) { pickResults.textContent = "No matching items."; return; } for (const item of matches) { const row = document.createElement("button"); row.type = "button"; row.className = "shop-item-search-row"; const name = document.createElement("span"); name.className = "shop-item-search-row-name"; name.textContent = item.displayName; const key = document.createElement("span"); key.className = "shop-item-search-row-key"; key.textContent = item.listingKey ? `${item.key} (${item.listingKey})` : `${item.key} (#${item.itemId})`; row.append(name, key); row.addEventListener("click", () => addGiftItem(item)); pickResults.append(row); } } function characterLabel (row) { const name = `${row.firstName ?? ""} ${row.lastName ?? ""}`.trim(); const account = row.accountUsername ? ` · @${row.accountUsername}` : ""; return `${name}${account}`; } function renderResults () { resultsEl.replaceChildren(); if (!characters.length) { resultsEl.textContent = "No characters found."; return; } for (const row of characters) { const btn = document.createElement("button"); btn.type = "button"; btn.className = selected?.characterId === row.characterId ? "active" : ""; btn.textContent = characterLabel(row); btn.addEventListener("click", () => { selected = row; giftItems = []; messageText = ""; closeInlineItemSearch(); render(); }); resultsEl.append(btn); } } function renderPreview () { const preview = detailEl.querySelector("#gifts-letter-preview"); const signature = detailEl.querySelector("#gifts-letter-signature"); if (!preview || !selected) { return; } const displayName = `${selected.firstName} ${selected.lastName}`.trim(); preview.textContent = formatGiftLetterBody({ characterDisplayName: displayName, message: messageText, items: giftItems }); if (signature) { signature.textContent = formatLetterSignature({ authorDisplayName: QUESTWARD_GIFT_AUTHOR, authorOrganization: QUESTWARD_GIFT_ORG }); } } function renderDetail () { detailEl.replaceChildren(); if (!selected) { detailEl.textContent = "Search for a character, then select one to compose a gift."; return; } const heading = document.createElement("h3"); heading.textContent = `Gift to ${characterLabel(selected)}`; detailEl.append(heading); const messageLabel = document.createElement("label"); messageLabel.className = "gifts-message-label"; messageLabel.textContent = "Message"; const messageArea = document.createElement("textarea"); messageArea.id = "gifts-message"; messageArea.rows = 5; messageArea.placeholder = "Write the personal note included in the letter…"; messageArea.value = messageText; messageArea.addEventListener("input", () => { messageText = messageArea.value; renderPreview(); }); messageLabel.append(messageArea); detailEl.append(messageLabel); const itemsHeader = document.createElement("div"); itemsHeader.className = "gifts-items-header"; const itemsTitle = document.createElement("strong"); itemsTitle.textContent = "Items"; itemsHeader.append(itemsTitle); detailEl.append(itemsHeader); const itemSearch = document.createElement("input"); itemSearch.type = "search"; itemSearch.placeholder = "Search items to add…"; itemSearch.autocomplete = "off"; const itemResults = document.createElement("div"); itemResults.className = "gifts-item-search-results"; detailEl.append(itemSearch, itemResults); itemPickContext = { inputEl: itemSearch, resultsEl: itemResults }; itemSearch.addEventListener("input", () => renderInlineItemSearch(itemSearch.value)); itemSearch.addEventListener("search", () => renderInlineItemSearch(itemSearch.value)); itemSearch.addEventListener("keydown", (event) => { if (event.key !== "Enter") { return; } event.preventDefault(); event.stopPropagation(); const matches = filterItemMatches(itemSearch.value); if (matches[0]) { addGiftItem(matches[0]); } }); renderInlineItemSearch(itemSearch.value); const list = document.createElement("div"); list.className = "gifts-item-list"; if (!giftItems.length) { const empty = document.createElement("p"); empty.className = "hint"; empty.textContent = "No items yet — search above and click a result (or press Enter)."; list.append(empty); } else { for (let index = 0; index < giftItems.length; index++) { const entry = giftItems[index]; const row = document.createElement("div"); row.className = "gifts-item-row"; const name = document.createElement("span"); name.textContent = entry.displayName || itemDefinition(entry.itemId)?.displayName || `Item ${entry.itemId}`; const qty = document.createElement("input"); qty.type = "number"; qty.min = "1"; qty.max = "100000"; qty.value = String(entry.quantity); qty.addEventListener("change", () => { entry.quantity = Math.max(1, Math.min(100000, qty.valueAsNumber || 1)); qty.value = String(entry.quantity); renderPreview(); }); const remove = document.createElement("button"); remove.type = "button"; remove.textContent = "Remove"; remove.addEventListener("click", () => { giftItems.splice(index, 1); renderDetail(); }); row.append(name, qty, remove); list.append(row); } } detailEl.append(list); const previewWrap = document.createElement("div"); previewWrap.className = "gifts-preview-wrap"; const previewTitle = document.createElement("strong"); previewTitle.textContent = "Letter preview"; const preview = document.createElement("pre"); preview.id = "gifts-letter-preview"; preview.className = "gifts-letter-preview"; const signature = document.createElement("pre"); signature.id = "gifts-letter-signature"; signature.className = "gifts-letter-signature"; previewWrap.append(previewTitle, preview, signature); detailEl.append(previewWrap); const sendBtn = document.createElement("button"); sendBtn.type = "button"; sendBtn.id = "gifts-send"; sendBtn.textContent = "Send Gift"; sendBtn.addEventListener("click", () => { if (!selected) { return; } setStatus("Sending gift…"); socket.send({ type: MessageType.editorSendGift, characterId: selected.characterId, message: messageText, items: giftItems.map((row) => ({ itemId: row.itemId, quantity: row.quantity, listingKey: row.listingKey ?? null, potionKey: row.potionKey ?? null })) }); }); detailEl.append(sendBtn); renderPreview(); } function render () { renderResults(); renderDetail(); } function runSearch () { const query = searchInput.value.trim(); if (!query) { setStatus("Enter a character or account name.", true); return; } setStatus("Searching…"); socket.send({ type: MessageType.editorSearchGiftCharacters, query }); } document.getElementById("open-gifts").addEventListener("click", () => { setStatus(""); show(true); }); document.getElementById("gifts-close").addEventListener("click", () => show(false)); backdrop.addEventListener("click", () => show(false)); searchBtn.addEventListener("click", runSearch); searchInput.addEventListener("keydown", (event) => { if (event.key === "Enter") { event.preventDefault(); runSearch(); } }); return { isOpen: () => open, handleError (message) { setStatus(message || "Gift failed.", true); }, handleMessage (message) { if (message.type === MessageType.editorGiftCharacters) { characters = message.characters ?? []; if (selected && !characters.some((row) => row.characterId === selected.characterId)) { selected = null; } setStatus(characters.length ? `${characters.length} character(s)` : "No matches."); render(); return; } if (message.type === MessageType.editorGiftSent) { const name = `${message.firstName ?? ""} ${message.lastName ?? ""}`.trim(); setStatus(`Gift sent to ${name}.`); giftItems = []; messageText = ""; renderDetail(); } } }; }