function createRatecardController({ messageTypes, requestConsumerTokenServiceOnce, sendRuntimeMessage, appendBackgroundRequestLog, openRatecardDrawer, closePlanDetailPopover, environment }) { const pending = new Map(); async function request(planNumber) { const authorizations = await requestConsumerTokenServiceOnce(); const response = await sendRuntimeMessage({ type: messageTypes.requestRatecardByPlan, planNumber, authorization: authorizations && authorizations.accountPlans }); appendBackgroundRequestLog(response?.debugRequests); if (!response?.ok) throw new Error(response?.error || "Unable to load rate card."); return response.items; } async function showRatecard(plan, trigger) { closePlanDetailPopover(); const handle = openRatecardDrawer(plan, trigger); if (!handle) return; try { const planNumber = String(plan.subPlanNum ?? "").trim(); if (!planNumber) throw new Error("Plan number is unavailable for this account plan."); if (!pending.has(planNumber)) pending.set(planNumber, request(planNumber).finally(() => pending.delete(planNumber))); handle.showItems(await pending.get(planNumber)); } catch (error) { handle.showError(error.message || "Unable to load rate card."); } } function createRatecardButton(plan) { const button = environment.document.createElement("button"); button.type = "button"; button.className = "opportunities-extension-ratecard-button"; button.textContent = "Rate Card"; button.title = "View rate card"; button.setAttribute("aria-haspopup", "dialog"); button.addEventListener("click", () => showRatecard(plan, button)); return button; } return { createRatecardButton, showRatecard }; }