// Entry point bundled to dist/cmp.js and embedded via a <script
// data-domain-token="..."> tag on the tenant's site (see the install
// snippet on the Installation screen).

import {
  ageRule,
  ageScreenPending,
  clearAge,
  holdSavedDecision,
  initAgeBand,
  recordAge,
  setAge,
} from "./age-band";
import {
  consentStorageName,
  DEFAULT_CONSENT_EXPIRY_MONTHS,
  getState,
  setState,
  hasConsented,
  clearState,
  type ConsentStoreConfig,
} from "./consent-store";
import type { RenderDecision } from "./banner-preferences";
import { DEFAULT_PAYLOAD } from "./default-banner";
import { decisionLabel } from "./decision-label";
import {
  currentScriptDataset,
  readConsentStoreConfig,
  readOwnScriptToken,
  scriptLoadsAsync,
  scriptsBeforeThisOne,
} from "./script-dataset";
import {
  ALL_DENIED,
  applyRuleChange,
  setAgeChangeHandler,
  defaultDecision,
  onPublishedConfig,
  preferenceServices,
  resetEmbedsForDecision,
  startEmbeds,
} from "./embed-runtime";
import { getServiceGrants } from "./service-consent";
import {
  effectiveState,
  getConsentModel,
  gpcDetected,
  gpcMarketingOnly,
  gpcOverrides,
  activeGpcOverride,
  gpcScoped,
  isUsVisitor,
  withPrivacySignal,
} from "./consent-policy";
import {
  consentModeEnabled,
  googleTagsFree,
  setConsentMode,
  signalConsentMode,
} from "./gtm-bridge";
import { setConsentSignalScope } from "./consent-signal";
import { claimInstance, isCurrentInstance } from "./instance";
import {
  cdnOriginOf,
  loadChunk,
  preloadPreferenceCenter,
  setFilesBase,
} from "./chunk-loader";
import { applyConsent, setupAutoBlocker } from "./blocker";
import { releasedScripts } from "./script-activate";
import { formIsDirty, noteTyping } from "./form-dirty";
import { PLUGIN_BUILD } from "./cdn-code";
import { trackSession } from "./session-tracker";
import { fetchPublishedBanner } from "./banner-config-fetch";
import {
  keepHoldRules,
  loadStartingHoldRules,
  setHoldRules,
  hasSensitiveRules,
} from "./custom-rules";
import { loadKeptServiceOverrides } from "./embed-services";
import {
  apiBaseUrl,
  sendConsentDecisionBeacon,
  sendInstallBeacon,
  sendSessionBeacon,
  setApiBase,
} from "./beacons";
import { newConsentId } from "./consent-id";
import { renderPublishedBanner } from "./banner-render";
import type { ViewPayload } from "./banner-view";
import { contentForPayload, mountRevisitIcon } from "./revisit-mount";
import { indiaFor, withIndiaNotice } from "./banner-india";
import { keepLanguage, languageChoices, rememberLanguage } from "./lang-switch";

// document.currentScript (so readOwnScriptToken/readConsentStoreConfig) is only
// valid while the script first runs — captured once in init() so a preferences
// call made later, from a page element the visitor clicks, still works.
let capturedScriptToken: string | null = null;
let capturedStoreConfig: ConsentStoreConfig | null = null;
let capturedPublished: ViewPayload | null = null;
// How long a banner waits for the published config before showing the default
// banner. The config is normally an instant HTTP-cache hit, so the visitor
// almost always sees the real banner on first paint; on a very slow network the
// default is shown after this and swapped for the real one if it arrives later.
// Long enough that an ordinary cold connection to the API still gets the real
// banner at once, with no built-in banner flashing first (the config can also say
// the plan is suspended, which shows no banner at all).
const BANNER_CONFIG_WAIT_MS = 1500;
// A tenant this browser last saw suspended (a Free plan over its sessions quota) is
// waited for longer, so a slow answer does not draw a banner that is then taken
// down. The memory lapses, and is cleared as soon as a config says otherwise.
const SUSPENDED_WAIT_MS = 5000;
const SUSPENDED_MEMORY_MS = 6 * 60 * 60 * 1000;

function suspendedKey(): string {
  // Not a template literal: the build's CSS minifier pairs up backticks across the file.
  return "saasaudit-suspended-" + capturedScriptToken;
}

function rememberSuspension(suspendedNow: boolean): void {
  try {
    if (suspendedNow) {
      localStorage.setItem(
        suspendedKey(),
        String(Date.now() + SUSPENDED_MEMORY_MS),
      );
    } else {
      localStorage.removeItem(suspendedKey());
    }
  } catch {
    // No storage: the shorter wait applies.
  }
}

function rememberedSuspended(): boolean {
  try {
    return Number(localStorage.getItem(suspendedKey())) > Date.now();
  } catch {
    return false;
  }
}

function configWaitMs(): number {
  return rememberedSuspended() ? SUSPENDED_WAIT_MS : BANNER_CONFIG_WAIT_MS;
}

// One "show" per time a banner is displayed (first visit, or a reopen).
// `decided` flips once the visitor acts, so a late-arriving published config
// can't replace a banner they already dismissed; scoped per show so an earlier
// decision can't block the swap on a later reopen.
interface BannerShow {
  decided: boolean;
}
let currentShow: BannerShow = { decided: false };

// The published config is fetched at most once per page load. Every visitor
// needs it: the revisit icon follows the tenant's settings (see showRevisit),
// and a first-time visitor also gets the banner from it.
let publishedPromise: Promise<ViewPayload | null> | null = null;

// A Free plan over its monthly sessions quota: the config says so, and the page
// shows no banner or icon (including a built-in one drawn before the config came).
let suspended = false;
function suspend(): void {
  suspended = true;
  document
    .querySelectorAll(".chub-root, .chub-revisit, .chub-overlay, .chub-banner")
    .forEach((el) => el.remove());
}

// A saved decision is dropped when the visitor turns out to be a minor, but only once the
// published config confirms the teen rules apply to them. Before it arrives the rules are
// assumed (the stricter answer) and a config that leaves them off would find the decision
// already gone, so what the visitor rejected would run. Until then, or if the config never
// comes, the saved decision stands.
let ageClearPending = false;
let ageConfigIn = false;

/** The published config is in: drops the decision that waited, if the teen rules apply. */
function confirmAgeClear(): void {
  ageConfigIn = true;
  const pending = ageClearPending;
  ageClearPending = false;
  holdSavedDecision(false);
  if (!pending) return;
  // The teen rules apply: the earlier decision goes and the visitor chooses. They do not:
  // the decision the visitor saved stands, as it was.
  if (ageRule() === "optin") applyAgeChange();
  else applyAgeState();
}

function loadPublished(): Promise<ViewPayload | null> {
  if (!publishedPromise) {
    publishedPromise = fetchPublishedBanner(
      apiBaseUrl(),
      capturedScriptToken ?? "",
      // The API says "suspended" in a config, so an empty answer means it is not.
      () => rememberSuspension(false),
    ).then((payload) => {
      capturedPublished = payload;
      if (payload?.config.reloadOnWithdraw) {
        document.addEventListener("input", noteTyping, true);
      }
      if (payload) rememberSuspension(payload.suspended === true);
      if (payload && capturedScriptToken) {
        // A config without rules means the site has none now: a failed request (no
        // payload) changes nothing, so an outage never lifts them.
        if (setHoldRules(payload.holdRules)) applyRuleChange();
        keepHoldRules(capturedScriptToken);
      }
      if (payload?.suspended) suspend();
      if (capturedStoreConfig) {
        onPublishedConfig(capturedStoreConfig, payload);
        if (payload) confirmAgeClear();
      }
      return payload;
    });
  }
  return publishedPromise;
}

function wait(ms: number): Promise<undefined> {
  return new Promise((resolve) => setTimeout(() => resolve(undefined), ms));
}

function recordDecision(
  chosen: RenderDecision,
  keep?: string[],
  options?: {
    gpcOverride?: boolean;
    optOutSale?: boolean;
    // The opt-out was applied from the browser's signal with no banner shown.
    gpcAuto?: boolean;
  },
): void {
  if (!capturedScriptToken || !capturedStoreConfig) return;
  // A confirmed override stands for as long as the decision still allows
  // analytics or marketing: later saves keep it, and opting out of both ends it.
  const allowsAny = chosen.analyticsOptIn || chosen.marketingOptIn;
  // A confirmation made under an opt-out model covered marketing only, and says so.
  const gpcOverride =
    allowsAny &&
    (options?.gpcOverride
      ? (gpcMarketingOnly() && "marketing") || true
      : activeGpcOverride(getState(capturedStoreConfig)?.gpcOverride));
  // Global Privacy Control overrides marketing (and analytics, except for a US visitor under
  // an opt-out model) on a site that is not confirmed opt-in, so what is recorded is what
  // actually applies.
  const privacy = gpcOverrides() && !gpcOverride ? gpcScoped(chosen) : chosen;
  const before = effectiveState(capturedStoreConfig);
  // Accept All does not touch sensitive data: it stays as the visitor had it.
  const decision = {
    ...privacy,
    sensitiveOptIn:
      privacy.sensitiveOptIn ??
      getState(capturedStoreConfig)?.sensitiveOptIn === true,
  };
  const consentId = newConsentId();
  const state = setState({
    config: capturedStoreConfig,
    consentId,
    decision: decisionLabel(decision),
    optIns: decision,
    // A teen's choice is kept for at least 12 months before the banner asks again.
    expiryMonths:
      ageRule() === "optin"
        ? Math.max(12, capturedPublished?.config.consentExpiryMonths ?? 12)
        : capturedPublished?.config.consentExpiryMonths,
    gpcOverride,
    optOutSale: options?.optOutSale,
  });
  applyConsent(state);
  // A category that was allowed and no longer is: what is already running cannot be
  // stopped from here, so the withdrawal is handled in the preference center's code
  // (cookies removed, Meta revoked, a reload only when needed).
  if (before) {
    void loadChunk("prefs")
      .then((chunk) =>
        chunk.withdraw({
          before,
          after: decision,
          cookies: capturedPublished?.cookies,
          storageCleanup: capturedPublished?.storageCleanup,
          released: releasedScripts(),
          googleAdvanced: googleTagsFree(),
          consentModeOn: consentModeEnabled(),
          // The Do Not Sell link keeps the banner open to show its confirmation.
          reload: !options?.optOutSale,
          reloadOnWithdraw: capturedPublished?.config.reloadOnWithdraw,
          formDirty: formIsDirty(),
        }),
      )
      .catch(() => {
        // The code that handles a withdrawal could not load: what was allowed and no
        // longer is cannot be stopped from here, so the page is reloaded (the saved
        // decision then holds those tags back from the start).
        const withdrawn =
          (before.functionalOptIn && !decision.functionalOptIn) ||
          (before.analyticsOptIn && !decision.analyticsOptIn) ||
          (before.marketingOptIn && !decision.marketingOptIn) ||
          (before.sensitiveOptIn === true && !decision.sensitiveOptIn);
        if (withdrawn && !options?.optOutSale) location.reload();
      });
  }
  resetEmbedsForDecision({
    config: capturedStoreConfig,
    scriptToken: capturedScriptToken,
    keepServices: keep,
  });
  // The consent log has no field for sensitive data yet: the API refuses a body with
  // one it does not know, so only the three it records are sent.
  sendConsentDecisionBeacon(
    capturedScriptToken,
    {
      functionalOptIn: decision.functionalOptIn,
      analyticsOptIn: decision.analyticsOptIn,
      marketingOptIn: decision.marketingOptIn,
    },
    gpcDetected(),
    consentId,
    { optOutSale: options?.optOutSale, gpcAuto: options?.gpcAuto },
  );
  // The "Do Not Sell or Share" link: say, inside the banner that stays open, that it
  // is applied. Does nothing if a later decision has already removed the banner.
  if (options?.optOutSale && !options.gpcAuto) {
    void loadChunk("prefs")
      .then((chunk) => chunk.showDnsDone(gpcDetected()))
      .catch(() => undefined);
  }
}

// Every banner render (fallback or published) must use this, not
// recordDecision directly, so `decided` reflects a real visitor action rather
// than merely "some banner got mounted" — see BannerShow above.
function handleDecision(
  decision: RenderDecision,
  keep?: string[],
  options?: { gpcOverride?: boolean; optOutSale?: boolean },
): void {
  currentShow.decided = true;
  // With the signal on the link stays active: the visitor's own opt-out is recorded by the
  // first click, and a later one only shows the message again.
  // ...but only while nothing has changed since: a service accepted from its placeholder in
  // between (Accept & Load) is a grant the next click must still take back.
  const grants = capturedStoreConfig
    ? getServiceGrants(capturedStoreConfig).join()
    : "";
  if (
    options?.optOutSale &&
    gpcDetected() &&
    dnsClicked &&
    grants === dnsGrants
  ) {
    void loadChunk("prefs")
      .then((chunk) => chunk.showDnsDone(true))
      .catch(() => undefined);
    return;
  }
  dnsClicked = options?.optOutSale === true;
  recordDecision(decision, keep, options);
  dnsGrants = capturedStoreConfig
    ? getServiceGrants(capturedStoreConfig).join()
    : "";
}
// The services the visitor had accepted when that decision was recorded.
let dnsGrants = "";
// Whether the "Do Not Sell or Share" link was the visitor's last decision.
let dnsClicked = false;

// Our age screen is shown at most once per page view.
let agePrompt: Promise<void> | null = null;

/** Asks the visitor how old they are when the site chose our age screen for their
 * region and nobody has said yet; resolves once they answered (the tags stay held until
 * then). `refresh`: a returning visitor, whose page has to be brought up to date
 * afterwards (a first-time visitor's banner is drawn by the caller). */
function askAge(payload: ViewPayload, refresh: boolean): Promise<void> {
  if (!ageScreenPending()) return Promise.resolve();
  agePrompt ??= new Promise<void>((resolve) => {
    const resolved = contentForPayload(payload);
    void loadChunk("prefs")
      .then((chunk) =>
        chunk.showAgeScreen({
          config: payload.config,
          words: resolved?.content.ageScreen,
          language: resolved?.language,
          firstQuestion:
            payload.config.targeting?.minors?.ageScreen?.firstQuestion ?? 16,
          closeLabel: resolved?.content.ui.close ?? "Close",
          onAnswer: (band) => {
            recordAge(band);
            if (refresh) applyAgeChange();
            else applyAgeState();
            resolve();
          },
        }),
      )
      .catch(() => {
        // The dialog could not load: the gate stays closed (tags stay held, no banner),
        // and the next page view tries again.
        agePrompt = null;
        resolve();
      });
  });
  return agePrompt;
}

/** Shows a banner (first visit, or a reopen with `initial`): the published
 * one if its config arrives within BANNER_CONFIG_WAIT_MS (longer for a tenant
 * last seen suspended), else the built-in
 * one — swapped for the published one if that arrives later and the visitor
 * hasn't acted yet. renderPublishedFrom replaces the fallback's DOM itself, so
 * swapping while the fallback is visible is safe. */
// Bumped when the age changes, so a draw that was waiting on the config does not outlive it.
let ageEpoch = 0;

/** A visitor under an opt-out model whose browser sends Global Privacy Control, on a site that
 * hides the banner for it: their opt-out of targeted advertising (in the US, of sale and
 * sharing) is applied and recorded as their decision, no banner is drawn, and a brief
 * confirmation is shown. True when that was done. */
function applyGpcSilently(payload: ViewPayload): boolean {
  // What an opt-out visitor with the signal on is allowed before they decide: functional and
  // analytics, not marketing (sensitive data stays off, as it is until they turn it on).
  const decision = defaultDecision();
  if (
    !decision ||
    getConsentModel() !== "opt-out" ||
    !gpcDetected() ||
    payload.config.targeting?.suppressBannerOnGpc === false
  )
    return false;
  recordDecision(decision, undefined, { optOutSale: true, gpcAuto: true });
  // The wording is picked in the chunk, from the banner's own text for the region.
  const optOut = contentForPayload(payload)?.content.optOut;
  void loadChunk("prefs")
    .then((chunk) =>
      chunk.showGpcToast({
        optOut,
        us: isUsVisitor(),
        style: payload.config.style,
      }),
    )
    .catch(() => undefined);
  return true;
}

async function showBanner(
  initial?: RenderDecision,
  startAt?: "preferences",
): Promise<void> {
  // Nothing to choose for a visitor under 13: no banner. The site's settings (its hold-back
  // rules) are still fetched, so what they hold back is held.
  if (ageRule() === "block" && !startAt) {
    void loadPublished();
    return;
  }
  const show: BannerShow = { decided: false };
  currentShow = show;

  const early = await Promise.race([loadPublished(), wait(configWaitMs())]);
  if (currentShow !== show || !isCurrentInstance()) return; // superseded
  if (suspended) return;
  // Our age screen comes first; its answer decides whether any banner follows.
  // (No await when nobody needs asking, so the banner is drawn in the same step as before.)
  if (early && ageScreenPending()) {
    await askAge(early, false);
    if (currentShow !== show || !isCurrentInstance()) return;
  }
  // Still waiting for an answer (the dialog could not load): no banner to accept from.
  if (ageScreenPending()) return;
  if (ageRule() === "block" && !startAt) return;
  if (early) {
    if (!startAt && applyGpcSilently(early)) return;
    renderPublishedFrom(early, initial, startAt);
    return;
  }
  // A tenant last seen suspended gets no built-in banner while its config is
  // unknown (slow, failed or timed out request): the memory lapses on its own.
  if (rememberedSuspended()) return;
  renderPublishedFrom(DEFAULT_PAYLOAD, initial, startAt);
  // `early` is null when nothing is published (or the fetch failed): the
  // built-in banner is final. It is undefined on timeout: the config may
  // still arrive.
  if (early === undefined) {
    void loadPublished().then(async (payload) => {
      if (
        payload &&
        !suspended &&
        currentShow === show &&
        !show.decided &&
        isCurrentInstance()
      ) {
        // The age screen comes first for a config that arrives late too; the built-in
        // banner that was up meanwhile gives way to it.
        if (ageScreenPending()) {
          document
            .querySelectorAll(".chub-root:not(.chub-age), .chub-overlay")
            .forEach((node) => node.remove());
          await askAge(payload, false);
          if (currentShow !== show || !isCurrentInstance()) return;
          if (ageScreenPending() || (ageRule() === "block" && !startAt)) return;
        }
        if (!startAt && applyGpcSilently(payload)) {
          document
            .querySelectorAll(".chub-root:not(.chub-age), .chub-overlay")
            .forEach((node) => node.remove());
          return;
        }
        renderPublishedFrom(payload, initial, startAt);
      }
    });
  }
}

/** Puts the revisit icon on the page for every visitor, first-time or
 * returning, with the tenant's icon and position once the published config is
 * in. Waits no longer than the banner does: past that it shows the built-in
 * icon, then swaps to the tenant's if the config arrives later. */
async function showRevisit(): Promise<void> {
  const epoch = ageEpoch;
  if (ageRule() === "block") {
    void loadPublished();
    return;
  }
  const early = await Promise.race([loadPublished(), wait(configWaitMs())]);
  if (!isCurrentInstance() || suspended || epoch !== ageEpoch) return;
  if (!early && rememberedSuspended()) return;
  // A returning visitor who has not said how old they are is asked too.
  if (early && ageScreenPending() && hasConsented(capturedStoreConfig!)) {
    await askAge(early, true);
  }
  if (ageRule() === "block" || ageScreenPending()) return;
  mountRevisitIcon({ payload: early ?? null, onClick: openPreferences });
  if (early !== undefined) return;
  void loadPublished().then(async (payload) => {
    if (payload && !suspended && isCurrentInstance() && epoch === ageEpoch) {
      if (ageScreenPending() && hasConsented(capturedStoreConfig!)) {
        await askAge(payload, true);
        if (!isCurrentInstance() || epoch !== ageEpoch) return;
      }
      if (ageRule() === "block" || ageScreenPending()) return;
      mountRevisitIcon({ payload, onClick: openPreferences });
    }
  });
}

/** Public withdrawal/preferences entry point (window.ConsentHub.
 * openPreferences()) — a CMP must let a visitor change or withdraw
 * consent without clearing browser storage manually. Reopens the
 * banner pre-filled with the visitor's current decision (or with
 * everything unchecked if none exists yet); saving records the new
 * decision exactly like the first-visit flow. */
function openPreferences(): void {
  if (suspended || !capturedScriptToken || !capturedStoreConfig) return;
  // The age dialog comes first: preferences wait for its answer.
  if (ageScreenPending()) return;
  // What applies now (the signal included), so a decision made before GPC was
  // switched on is not shown as allowing what the signal blocks.
  const stored = getState(capturedStoreConfig);
  const current = stored ? withPrivacySignal(stored) : null;
  const initial = current
    ? {
        functionalOptIn: current.functionalOptIn,
        analyticsOptIn: current.analyticsOptIn,
        marketingOptIn: current.marketingOptIn,
        sensitiveOptIn: current.sensitiveOptIn === true,
        // Still the visitor's latest choice: the preference center says so.
        ...(current.optOutSale && !current.marketingOptIn
          ? { optOutSale: true }
          : {}),
      }
    : undefined;

  if (capturedPublished) {
    currentShow = { decided: false };
    renderPublishedFrom(capturedPublished, initial, "preferences");
    return;
  }
  void showBanner(initial, "preferences");
}

// True when the install tag says data-powered-by="off".
let poweredByOff = false;

/** Picks the visitor's language among the tenant's enabled ones and shows the
 * banner for `payload` (the first-visit notice, or the same notice reopened
 * when `initial` is a prior decision). If the published config has no usable
 * text, or drawing it fails, the default banner is shown instead: a visitor
 * must always be able to choose. */
function renderPublishedFrom(
  payload: ViewPayload,
  initial?: RenderDecision,
  startAt?: "preferences",
  // What was ticked in the preference center, not yet saved, when the language was changed.
  pending?: RenderDecision,
): void {
  const resolved = contentForPayload(payload);
  const showDefault = (): void => {
    if (payload !== DEFAULT_PAYLOAD)
      renderPublishedFrom(DEFAULT_PAYLOAD, initial, startAt);
  };
  if (!resolved) return showDefault();
  // A visitor under an opt-out model with the signal on reads the wording for their region (a US
  // visitor's names the sale and sharing of personal information), not the general message.
  // Only when the signal covers marketing alone: the region wording does not mention analytics.
  const optOut = resolved.content.optOut;
  const gpcText =
    payload.config.consentModel === "opt-out" &&
    gpcMarketingOnly() &&
    (isUsVisitor() ? optOut?.gpcNotice : optOut?.gpcNoticeOther);
  // A visitor in India reads the site's own India wording when it has named an officer.
  const india = indiaFor(
    payload.config,
    resolved.content,
    payload.visitorCountry,
  );
  const { enabled, switcher } = payload.config.languages;
  try {
    renderPublishedBanner({
      // The install tag may switch the line off only in the plugin's own copy, or where the plan
      // allows it (the API says so): a tag edited by hand must not hide it on any other plan.
      config:
        poweredByOff && (PLUGIN_BUILD || payload.config.brandingHideable)
          ? { ...payload.config, showBranding: false }
          : payload.config,
      content: withIndiaNotice(
        gpcText
          ? {
              ...resolved.content,
              notice: { ...resolved.content.notice, gpcMessage: gpcText },
            }
          : resolved.content,
        india,
      ),
      india,
      languageSwitch:
        switcher && enabled.length > 1
          ? {
              codes: languageChoices(enabled, payload.visitorCountry),
              label: resolved.content.ui.language ?? "Language",
              onPick: (code, prefs, pending) => {
                rememberLanguage(code);
                renderPublishedFrom(
                  payload,
                  initial,
                  prefs ? "preferences" : undefined,
                  pending,
                );
              },
            }
          : undefined,
      cookies: payload.cookies,
      language: resolved.language,
      cookiePolicyUrl: payload.cookiePolicyUrl,
      // A pick made in the preference center keeps what was ticked there: over the earlier
      // decision, or (a first visit) as the starting ticks.
      initial: pending && initial ? { ...initial, ...pending } : initial,
      startAt,
      services: preferenceServices,
      defaults: pending && !initial ? () => pending : defaultDecision,
      buildPreferences: (p) =>
        loadChunk("prefs").then((c) =>
          c.buildPreferenceCenter({
            ...p,
            // Country only: every US visitor reads the sale/sharing wording.
            optOutRegion: payload.visitorRegion
              ? /^(california|restOfUs)$/.test(payload.visitorRegion)
                ? "us"
                : "other"
              : undefined,
            consentRecord: capturedStoreConfig
              ? {
                  name: consentStorageName(capturedStoreConfig),
                  host: capturedStoreConfig.rootHostname ?? location.hostname,
                  // The lifetime a decision is stored with: setState's own precedence.
                  expiryMonths:
                    payload.config.consentExpiryMonths ??
                    (capturedStoreConfig.cookieExpiryDays
                      ? undefined
                      : DEFAULT_CONSENT_EXPIRY_MONTHS),
                  expiryDays: capturedStoreConfig.cookieExpiryDays,
                  storage: capturedStoreConfig.rootHostname
                    ? undefined
                    : "local_storage",
                }
              : undefined,
          }),
        ),
      // `overrides` is whether a choice allowing analytics or marketing must be
      // confirmed first: whenever the browser sends the signal, on any consent
      // model (an opt-in banner's Accept All is no less at odds with it). Once the
      // visitor has confirmed the override the signal no longer applies to their
      // decision, so the notice and the question stop appearing.
      gpc: () => {
        const stored =
          capturedStoreConfig &&
          activeGpcOverride(getState(capturedStoreConfig)?.gpcOverride);
        return {
          detected: gpcDetected() && !stored,
          overrides: gpcDetected() && !stored,
          marketingOnly: gpcMarketingOnly(),
        };
      },
      buildGpcConfirm: (p) =>
        loadChunk("prefs").then((c) => c.buildGpcConfirm(p)),
      consentId: () =>
        capturedStoreConfig
          ? getState(capturedStoreConfig)?.consentId
          : undefined,
      onDecision: (decision, kept, options) => {
        keepLanguage();
        handleDecision(decision, kept, options);
      },
      onOpenPreferences: openPreferences,
      onPreferencesIntent: () => void loadChunk("prefs").catch(() => undefined),
      hasSensitive: hasSensitiveRules,
    });
    // Downloaded now, run when asked for; a returning visitor who never sees
    // the banner never fetches it.
    preloadPreferenceCenter();
  } catch {
    showDefault();
  }
}

/** Applies what the visitor may have now (the Google signal and the tags), as the
 * region rules or the age band say. */
function applyAllowed(config: ConsentStoreConfig): void {
  const allowed = effectiveState(config);
  signalConsentMode(allowed);
  // No decision and nothing allowed by default: gate everything now, so the script
  // backstop, the consent-signal cookie and the WordPress Consent API follow.
  applyConsent(allowed ?? ALL_DENIED);
}

/** What the visitor may have now that their age is known (or no longer pending). */
function applyAgeState(): void {
  if (capturedStoreConfig) applyAllowed(capturedStoreConfig);
}

/** The age band changed after the page loaded: apply it. Tags that already ran cannot
 * be stopped from here; what has not run yet is held, and the banner follows the band. */
function applyAgeChange(): void {
  const config = capturedStoreConfig;
  if (!config) return;
  // Whatever was about to be drawn for the earlier age is dropped.
  ageEpoch += 1;
  currentShow = { decided: false };
  // A visitor now known to be a minor chooses for themselves: an earlier decision (made
  // before we knew) does not stand.
  if (ageRule() === "optin" && hasConsented(config)) {
    if (ageConfigIn) clearState(config);
    else {
      ageClearPending = true;
      holdSavedDecision(true);
    }
  }
  applyAllowed(config);
  // Embeds already on the page follow the new age as well.
  applyRuleChange();
  // The age dialog itself (an under-13 visitor's message) stays until it is closed.
  const keepAgeDialog = document.querySelector(".chub-age") !== null;
  document
    .querySelectorAll(
      keepAgeDialog
        ? ".chub-root:not(.chub-age), .chub-revisit"
        : ".chub-root, .chub-revisit, .chub-overlay",
    )
    .forEach((node) => node.remove());
  if (ageRule() === "block") return;
  if (!hasConsented(config)) void showBanner();
  void showRevisit();
}

function init(): void {
  claimInstance();
  // The install tag may ask to switch the "Powered by" line off (the WordPress plugin's own
  // script always may; any other only where the plan allows it); read now, while currentScript is set.
  poweredByOff = currentScriptDataset()?.poweredBy === "off";
  // Post-render runtime marker the scanner-worker's Playwright crawl
  // looks for — set regardless of how this script reached the page
  // (manual tag, GTM container, CMS plugin), since Playwright inspects
  // the rendered page rather than the page's original source.
  (window as unknown as Record<string, unknown>).__CONSENT_HUB__ = true;

  // Must happen while document.currentScript is still this script — see
  // apiBaseUrl()'s comment. Every later beacon (including ones fired from
  // an async banner-click callback) reads this captured value instead.
  setApiBase(currentScriptDataset()?.apiBase ?? null);
  setFilesBase(
    currentScriptDataset()?.filesBase,
    (document.currentScript as HTMLScriptElement | null)?.src,
  );

  const scriptToken = readOwnScriptToken();
  if (!scriptToken) return;

  const storeConfig = readConsentStoreConfig(scriptToken);
  setConsentSignalScope(
    storeConfig.rootToken ?? scriptToken,
    storeConfig.rootHostname,
  );
  capturedScriptToken = scriptToken;
  capturedStoreConfig = storeConfig;
  // The site's age flag, before anything is decided from the default state.
  let ageTightened = initAgeBand(scriptToken, currentScriptDataset()?.ageBand);
  // Age calls a page queued before this script started count from the very first decision,
  // before any tag is released (the other queued calls wait for the end of init).
  const handledCalls = new Set<unknown>();
  const queuedEarly = (window as unknown as Record<string, unknown>)
    .ConsentHubQueue;
  if (Array.isArray(queuedEarly)) {
    for (const call of queuedEarly) {
      if (!Array.isArray(call)) continue;
      if (call[0] === "setAge") {
        if (setAge(call[1])) ageTightened = true;
        handledCalls.add(call);
      } else if (call[0] === "clearAge") {
        clearAge();
        handledCalls.add(call);
      }
    }
  }
  // What this browser last kept of the site's service categories comes first: Consent Mode
  // reads them (Google Analytics filed under Marketing), so the default below is right at once.
  loadKeptServiceOverrides(scriptToken);
  // Google Consent Mode's default goes out before anything else, so the tags
  // that read it find what this visitor allows (their decision, the model's
  // default, or nothing yet) from the start.
  setConsentMode(
    currentScriptDataset()?.consentMode,
    currentScriptDataset()?.consentModeInitial,
  );
  signalConsentMode(effectiveState(storeConfig));
  // The site's own hold-back rules: those the install tag carries, so even a first
  // visit has them from the first request, and what this browser last kept.
  loadStartingHoldRules({
    token: scriptToken,
    inline: currentScriptDataset()?.holdRules,
  });
  // Next, before any network or rendering work: an embed taken out of the
  // page before it loads never contacts the service it belongs to.
  const cdnOrigin = cdnOriginOf(currentScriptDataset()?.cdnBase);
  startEmbeds({
    config: storeConfig,
    scriptToken,
    // The CDN's origin when the tag names one (the loader is then served from the site
    // itself, which does not hold the service details), else the script's own address.
    scriptSrc:
      cdnOrigin ??
      (document.currentScript as HTMLScriptElement | null)?.src ??
      null,
    guardTrackers: currentScriptDataset()?.autoBlock !== "false",
  });

  // What the install tag looks like is only readable while this script runs, so
  // it is captured now; the reporting that uses it waits (see the end of init).
  const installFacts = {
    loadedAsync: scriptLoadsAsync(),
    scriptsBefore: scriptsBeforeThisOne(),
    autoBlock: currentScriptDataset()?.autoBlock !== "false",
  };

  // Public API for a "Manage cookie preferences" link/button the
  // customer places anywhere on their site — the only way a visitor can
  // withdraw or change consent short of manually clearing storage.
  const hub: Record<string, (input?: unknown) => void> = {
    openPreferences,
    // The site says how old the visitor is: { band: "under13" | "under16" | "adult" }.
    // A stricter band applies at once; clearAge lifts it (see age-band.ts).
    setAge: (input: unknown) => {
      if (setAge(input)) applyAgeChange();
    },
    clearAge: () => {
      clearAge();
      applyAgeChange();
    },
  };
  (window as unknown as Record<string, unknown>).ConsentHub = hub;
  // Calls a page made before this script was ready (a theme, Tag Manager):
  // window.ConsentHubQueue = window.ConsentHubQueue || []; ConsentHubQueue.push(["setAge",
  // { band: "under16" }]). They run now; later pushes run at once.
  const run = (call: unknown): void => {
    // Only a plain string names a method: anything else is ignored, not coerced.
    const name =
      Array.isArray(call) && typeof call[0] === "string" ? call[0] : "";
    if (handledCalls.has(call)) return;
    if (!Object.prototype.hasOwnProperty.call(hub, name)) return;
    try {
      hub[name]!((call as unknown[])[1]);
    } catch {
      // A call the page got wrong must not stop the others.
    }
  };
  const waiting = (window as unknown as Record<string, unknown>)
    .ConsentHubQueue;
  if (Array.isArray(waiting)) waiting.forEach(run);
  (window as unknown as Record<string, unknown>).ConsentHubQueue = {
    push: run,
  };
  // A link or button marked data-consent-open does the same, so a site's cookie
  // policy can offer "Cookie settings" without inline script (which a strict
  // content security policy forbids). It only opens the choices.
  document.addEventListener("click", (event) => {
    const target = event.target as Element | null;
    // Only the copy of the script that owns the page answers, so a script
    // installed twice does not open the choices twice.
    if (isCurrentInstance() && target?.closest?.("[data-consent-open]")) {
      event.preventDefault();
      openPreferences();
    }
  });

  // The auto-blocker watches the whole document for late-inserted tags, which
  // costs the browser a little on every DOM insertion the page makes. Sites
  // that gate tags another way (e.g. Consent Mode through GTM) can opt out
  // with data-auto-block="false" on the snippet; inert tags already on the
  // page are still activated when a decision is made either way.
  if (currentScriptDataset()?.autoBlock !== "false") {
    setupAutoBlocker(() => effectiveState(storeConfig));
  }

  setAgeChangeHandler(applyAgeChange);

  // A tag that makes the visitor a teen after an earlier (adult) decision: that decision
  // does not stand.
  if (ageTightened && ageRule() === "optin") {
    ageClearPending = true;
    holdSavedDecision(true);
  }
  const alreadyConsented = hasConsented(storeConfig);
  // Gate tags per what this visitor is allowed — their stored decision, or the
  // consent model's default for someone who has not decided — on every page
  // load, not just at decision time.
  const allowed = effectiveState(storeConfig);
  if (allowed) applyConsent(allowed);

  // Returning visitors are gated per their stored decision above and need no
  // banner. A first-time visitor gets the published banner on first paint when
  // the config is quickly available, or the built-in one otherwise (see
  // showBanner). Everyone gets the revisit icon.
  if (!alreadyConsented) {
    void showBanner();
  }
  void showRevisit();

  // Reporting (the install and session beacons: storage access, a random id, a
  // request) is not needed to protect the visitor or to show the banner, so it
  // runs after the guards above are on and the page has had a turn. The session
  // marker is written inside the same task as its beacon, so a page left before
  // it runs is simply counted on the next load.
  setTimeout(() => {
    // Both go out when a visit starts (the first page in a 30-minute window, in any tab), so
    // the install report needs no storage key of its own to avoid repeating on every page.
    trackSession(storeConfig, (sessionId) => {
      sendInstallBeacon(scriptToken, installFacts.loadedAsync, installFacts);
      sendSessionBeacon(scriptToken, sessionId);
    });
  }, 0);
}

init();
