/* Compatibility shim: this renderer ignores CSS mask-image, which the design
   system's icons (SocialIcon, Icon, ButtonTertiary arrow, Frame5264 mark) use to
   recolour a single asset. Swap each masked element for a pre-tinted SVG chosen
   by the tint the component asked for (its background colour). */
const MASK_TINTS = { "rgb(255, 255, 255)": "white", "rgb(0, 81, 255)": "blue", "rgb(15, 23, 43)": "ink", "rgb(0, 0, 0)": "black" };

function applyMaskShim(root) {
  (root || document).querySelectorAll("*:not([data-unmasked])").forEach((el) => {
    const cs = getComputedStyle(el);
    const raw = cs.maskImage && cs.maskImage !== "none" ? cs.maskImage : cs.webkitMaskImage;
    if (!raw || raw === "none") return;
    const found = /url\("?([^")]+)"?\)/.exec(raw);
    if (!found) return;
    const name = found[1].split("/").pop().replace(/\.svg$/, "").replace(/-white$/, "");
    const tint = MASK_TINTS[cs.backgroundColor] || "white";
    el.setAttribute("data-unmasked", "");
    el.style.webkitMaskImage = "none";
    el.style.maskImage = "none";
    el.style.background = `url(assets/tinted/${name}-${tint}.svg) center / contain no-repeat`;
  });
}

function watchMasks() {
  const root = document.getElementById("root");
  applyMaskShim(root);
  let queued = false;
  new MutationObserver(() => {
    if (queued) return;
    queued = true;
    requestAnimationFrame(() => { queued = false; applyMaskShim(root); });
  }).observe(root, { childList: true, subtree: true });
}

Object.assign(window, { applyMaskShim, watchMasks });
