const cache = new Map();

function setIndicator({ icon, badgeText, badgeColor }) {
  chrome.action.setIcon({ path: `../img/${icon}` });
  chrome.action.setBadgeText({ text: badgeText });
  chrome.action.setBadgeBackgroundColor({ color: badgeColor });
}


function resetIndicator() {
  setIndicator({
    icon: "icon-idle.png",
    badgeText: "",
    badgeColor: "#00000000"
  });
}


async function fetchSiteManifest(origin, tabId) {
  const url = `${origin}/.well-known/webrings.json`;

  try {
    const res = await fetch(url, { method: "GET" });
    const manifest = await res.json();

      
      setIndicator({
        icon: "icon-found.png",
        badgeText: "?",
        badgeColor: "#68bdfcff"
      });
      cache.set(tabId, { ok: true, manifest });    

  } catch {
    cache.set(tabId, { ok: false, manifest: null });
    resetIndicator();
  }
  chrome.tabs.sendMessage(tabId, { type: "RS_MANIFEST_FETCH", ...cache.get(tabId) })
    .catch(() => {});
}

chrome.webNavigation.onCompleted.addListener(details => {
  if (details.frameId !== 0) return;

  const url = new URL(details.url);
  fetchSiteManifest(url.origin, details.tabId);
});

