Pith - fret
const BADGE_BG = "#486860";
const tallies = new Map();

chrome.action.setBadgeBackgroundColor({ color: BADGE_BG });
chrome.action.setBadgeTextColor?.({ color: "#ffffff" });

function render(tabId) {
  let total = 0;
  for (const n of tallies.get(tabId)?.values() ?? []) total += n;
  const text = !total ? "" : total > 999 ? "999+" : String(total);
  chrome.action.setBadgeText({ tabId, text }).catch(() => {});
}

chrome.runtime.onMessage.addListener((msg, sender) => {
  if (msg?.type !== "wb-count") return;
  const tabId = sender.tab?.id;
  if (tabId === undefined) return;
  if (!tallies.has(tabId)) tallies.set(tabId, new Map());
  tallies.get(tabId).set(sender.frameId ?? 0, msg.count | 0);
  render(tabId);
});

chrome.tabs.onUpdated.addListener((tabId, info) => {
  if (info.status !== "loading") return;
  tallies.delete(tabId);
  chrome.action.setBadgeText({ tabId, text: "" }).catch(() => {});
});

chrome.tabs.onRemoved.addListener(tabId => tallies.delete(tabId));