// Turns a held (inert) script into a real one once its category is allowed.

import { siteCategoryFor } from "./embed-services";

/** A tag released on this page view, kept inside the loader (never on `window`, where
 * page scripts could read or change it) so a later withdrawal can tell whether
 * anything that cannot be stopped in place is running (see withdraw.ts, which reads
 * these). */
export interface ReleasedScript {
  category: string;
  src?: string;
  text?: string;
}

const released: ReleasedScript[] = [];

// Whether a held tag may still run: set by blocker.ts, which knows the visitor's current
// consent. A script that waited for the service's scripts to load checks it again before it
// runs, so a visitor who withdrew meanwhile does not get it.
let stillAllowed: (el: HTMLScriptElement) => boolean = () => true;
export function setStillAllowed(
  check: (el: HTMLScriptElement) => boolean,
): void {
  stillAllowed = check;
}

export function releasedScripts(): readonly ReleasedScript[] {
  return released;
}

/** Notes a tag that may now run (the loader released it, or a tracker script another
 * tag gave an address while its category was allowed). Each address once. */
export function recordReleased(script: ReleasedScript): void {
  if (script.src === undefined || !released.some((r) => r.src === script.src)) {
    released.push(script);
  }
}

// Scripts of a service that were released and are still loading, and the inline scripts held
// with that service that wait for them: such an inline script (data-consent-ordered, no
// address) runs once the service's scripts released before it have loaded (or failed), as it
// did in the page. Per service, so an unrelated script that never settles holds nothing back.
const loading: Record<string, number> = {};
const waiting: Record<string, (() => void)[]> = {};
function loaded(service: string): void {
  if (--loading[service]! === 0)
    waiting[service]?.splice(0).forEach((run) => run());
}

export function activate(el: HTMLScriptElement): void {
  const service = el.dataset.consentService ?? "";
  recordReleased({
    // The category it runs under (the site may have moved its service), not the one parked.
    category:
      (service ? siteCategoryFor(service) : undefined) ??
      el.dataset.consentCategory ??
      "",
    src: el.dataset.consentSrc,
    text: el.dataset.consentSrc ? undefined : (el.textContent ?? ""),
  });
  const activated = document.createElement("script");
  for (const { name, value } of Array.from(el.attributes)) {
    if (
      name === "type" ||
      name === "data-consent-category" ||
      name === "data-consent-src" ||
      name === "data-consent-script-type" ||
      name === "data-consent-ordered" ||
      name === "data-consent-rule" ||
      name === "data-consent-service"
    ) {
      continue;
    }
    activated.setAttribute(name, value);
  }
  // A page-written script parked by parsed-script-guard.ts: run it as the page
  // wrote it. The nonce is not an attribute value once the element is in the
  // page, so it is carried over as the property.
  if (el.dataset.consentScriptType)
    activated.type = el.dataset.consentScriptType;
  if (el.dataset.consentOrdered !== undefined) activated.async = false;
  if (el.nonce) activated.nonce = el.nonce;
  const src = el.dataset.consentSrc;
  if (src) {
    activated.src = src;
    if (service) {
      loading[service] = (loading[service] ?? 0) + 1;
      activated.addEventListener("load", () => loaded(service));
      activated.addEventListener("error", () => loaded(service));
    }
    el.replaceWith(activated);
    return;
  }
  activated.textContent = el.textContent;
  const run = (): void => {
    if (el.isConnected && stillAllowed(el)) el.replaceWith(activated);
  };
  if (service && el.dataset.consentOrdered !== undefined && loading[service]) {
    (waiting[service] ??= []).push(run);
  } else {
    run();
  }
}
