// One wrapper around Element.prototype.setAttribute for every guard that needs to
// see an address being set ("src" or "href"). Each guard used to wrap it on its own,
// so every setAttribute call on the page (class, style, aria-*, ...) went through
// one extra function per guard. Now the page has one wrapper that does nothing but
// pass other attributes straight through, and the guards register a handler here.
//
// The registry lives on the page, so a second copy of the loader replaces the first
// copy's handler instead of stacking another wrapper on top of it.

import { wrapMember } from "./wrap";

/** Returns true when it took the address itself, so the call must not go on. */
export type AddressHandler = (
  el: Element,
  name: "src" | "href",
  value: string,
) => boolean;

interface Hub {
  handlers: Record<string, AddressHandler | undefined>;
  // Puts the page's own setAttribute back; false when another wrapper sits on top.
  undo?: () => boolean;
}

const HUB_KEY = "__consent_hub_setattr__";

function hub(): Hub {
  const page = window as unknown as Record<string, Hub | undefined>;
  return (page[HUB_KEY] ??= { handlers: {} });
}

function install(shared: Hub): void {
  shared.undo = wrapMember(
    Element.prototype,
    "setAttribute",
    (originalSetAttribute) =>
      function (this: Element, name: string, value: string): void {
        // The native method takes anything that becomes a string (a boxed "src" is
        // "src"), so the guard reads the name the same way, and passes `name` on as given.
        let lower = "";
        try {
          lower = String(name).toLowerCase();
        } catch {
          // A name that cannot become a string: the native method throws for it.
        }
        if (lower === "src" || lower === "href") {
          const text = String(value);
          for (const handler of Object.values(shared.handlers)) {
            if (handler?.(this, lower, text)) return;
          }
        }
        originalSetAttribute.call(this, name, value);
      },
  );
}

/** Registers (or, with null, removes) the handler named `id`. The wrapper goes on
 * with the first handler and comes off with the last. */
export function setAddressHandler(
  id: string,
  handler: AddressHandler | null,
): void {
  const shared = hub();
  shared.handlers[id] = handler ?? undefined;
  const any = Object.values(shared.handlers).some(Boolean);
  if (any && !shared.undo) install(shared);
  if (!any && shared.undo) {
    // If the page wrapped setAttribute after us, ours stays in the chain (passing every
    // call straight through): keep its handle, so a later handler reuses it instead of
    // stacking a second wrapper.
    if (shared.undo()) shared.undo = undefined;
  }
}
