// Wires the embed blocker to this visitor's consent: an embed is allowed when
// its category was opted in, or when the visitor accepted that one service.

import { sendServiceConsentBeacon } from "./beacons";
import {
  CONSENT_STATE_VERSION,
  getState,
  type ConsentState,
} from "./consent-store";
import { applyConsent, releaseGoogleHeld } from "./blocker";
import { ageRule } from "./age-band";
import {
  reconcileRuleScripts,
  releaseService,
  setServiceAcceptedCheck,
} from "./service-scripts";
import { isCurrentInstance } from "./instance";
import { setAgeScreen, setSiteAges, setTeenNotice } from "./age-band";
import { configureConsentMode, signalConsentMode } from "./gtm-bridge";
import type { ConsentStoreConfig } from "./consent-store";
import {
  categoryAllowed,
  effectiveState,
  gpcDetected,
  setConsentModel,
  setGpcAnalytics,
  setUsVisitor,
} from "./consent-policy";
import { usesLocalFiles } from "./chunk-loader";
import { refreshLoaderIfStale } from "./cdn-code";
import { startTrackerGuards, stopTrackerGuards } from "./tracker-guard";
import { removeDisallowedTrackerCookies } from "./tracker-cookies";
import type { ViewPayload } from "./banner-view";
import { loadChunk, setChunkBase } from "./chunk-loader";
import { buildEmbedPlaceholder, setEmbedStyle } from "./embed-placeholder";
import {
  embedsOnPage,
  heldServices,
  refreshEmbeds,
  releaseHooks,
  setupEmbedBlocker,
} from "./embed-blocker";
import type { PreferenceService } from "./banner-services";
import type { RenderDecision } from "./banner-preferences";
import {
  allEmbedServices,
  keepServiceOverrides,
  setServiceOverrides,
  type EmbedCategory,
  type EmbedService,
} from "./embed-services";
import {
  clearServiceGrants,
  getServiceGrants,
  grantService,
} from "./service-consent";

// A service the visitor accepted on its own. Never for a visitor under 13: the age block
// overrides what was accepted before and any new acceptance.
function granted(config: ConsentStoreConfig, slug: string): boolean {
  return ageRule() !== "block" && getServiceGrants(config).includes(slug);
}

// A sensitive service (a frame rule marked sensitive) needs the dedicated switch: a
// placeholder's own Accept does not release it.
function isAllowed(config: ConsentStoreConfig, service: EmbedService): boolean {
  return (
    categoryAllowed(config, service.category) ||
    (service.category !== "sensitive" && granted(config, service.slug))
  );
}

// The loader's own URL, kept for refreshing its cached copy (cdn-code.ts).
let loaderSrc: string | null = null;

/** Starts holding back embeds of known services. Call as early as the install
 * snippet allows: an embed removed before it loads never contacts its service.
 * `scriptSrc` is the loader's own URL, where the service details live. */
export function startEmbeds(params: {
  config: ConsentStoreConfig;
  scriptToken: string;
  scriptSrc: string | null;
  // False when the site manages consent for scripts itself
  // (data-auto-block="false"): embeds are still held back, trackers are left alone.
  guardTrackers: boolean;
}): void {
  const { config, scriptToken, scriptSrc, guardTrackers } = params;
  loaderSrc = scriptSrc;
  startedConfig = config;
  setChunkBase(scriptSrc);
  // A widget script the page was served already parked (by the plugin or the edge) is
  // let go when its service was accepted on an earlier visit, as one the loader parks.
  setServiceAcceptedCheck((slug) => granted(config, slug));
  if (ageRule() !== "block") getServiceGrants(config).forEach(releaseService);
  releaseHooks();
  managingTrackers = guardTrackers;
  if (guardTrackers) {
    startTrackerGuards(
      (category, service) =>
        categoryAllowed(config, category) ||
        (category !== "sensitive" && !!service && granted(config, service)),
    );
  } else {
    stopTrackerGuards();
  }
  setupEmbedBlocker({
    isAllowed: (service) => isAllowed(config, service),
    allowsAll: () =>
      categoryAllowed(config, "functional") &&
      categoryAllowed(config, "analytics") &&
      categoryAllowed(config, "marketing"),
    renderPlaceholder: (service, original) =>
      buildEmbedPlaceholder({
        service,
        original,
        onInfo: () =>
          void loadChunk("info")
            .then((chunk) => chunk.openServiceInfo({ service, scriptSrc }))
            .catch(() => undefined),
        onAccept: () => {
          if (ageRule() === "block") return;
          // Sensitive data has its own switch: the placeholder opens it.
          if (service.category === "sensitive") {
            (
              window as { ConsentHub?: { openPreferences?: () => void } }
            ).ConsentHub?.openPreferences?.();
            return;
          }
          grantService(config, service.slug);
          // The markup comes back first, then the service's script that dresses it.
          refreshEmbeds();
          releaseService(service.slug);
          sendServiceConsentBeacon({
            scriptToken,
            serviceSlug: service.slug,
            granted: true,
          });
        },
      }),
  });
  // With the signal on, this waits for the config: until it confirms the model the signal is
  // applied as for an opt-in site (the cautious guess that holds scripts back), and that must
  // not delete the analytics cookies of an opt-out visitor the signal does not cover. The
  // config's arrival runs the cleanup (see onPublishedConfig).
  if (getState(config) && !gpcDetected()) clearUnallowedTrackerCookies(config);
}

let startedConfig: ConsentStoreConfig | null = null;

/** The site's hold-back rules were replaced (the settings arrived): embeds and scripts
 * held under the old ones are checked against the new. */
export function applyRuleChange(): void {
  refreshEmbeds();
  const config = startedConfig;
  if (config) {
    reconcileRuleScripts((category) =>
      categoryAllowed(config, category as EmbedCategory),
    );
  }
}
// Off when the site manages consent for scripts itself (data-auto-block="false").
let managingTrackers = false;

/** Removes known tracker cookies the visitor has not allowed. Only done once
 * the policy is known for this visitor (a decision, or the page's confirmed
 * model): before that, "nothing allowed yet" is only a cautious guess and
 * must not delete an opt-out visitor's cookies. */
function clearUnallowedTrackerCookies(config: ConsentStoreConfig): void {
  if (!managingTrackers) return;
  removeDisallowedTrackerCookies((category) =>
    categoryAllowed(config, category),
  );
}

/** What a visitor who has not decided is allowed right now (an opt-out site
 * allows everything), as the boxes the preference center should start with;
 * undefined when nothing optional is allowed. */
export function defaultDecision(): RenderDecision | undefined {
  const state = startedConfig ? effectiveState(startedConfig) : null;
  if (!state) return undefined;
  return {
    functionalOptIn: state.functionalOptIn,
    analyticsOptIn: state.analyticsOptIn,
    marketingOptIn: state.marketingOptIn,
  };
}

/** What the preference center lists under each category: every embedded service on this
 * page (held back or already loaded) and every one the visitor accepted on its own, each
 * marked accepted, allowed (by its category) or blocked. */
export function preferenceServices(): PreferenceService[] {
  const config = startedConfig;
  if (!config) return [];
  const accepted = getServiceGrants(config);
  const present = [...heldServices(), ...embedsOnPage()].map(
    (service) => service.slug,
  );
  return allEmbedServices()
    .filter(
      (service) =>
        accepted.includes(service.slug) || present.includes(service.slug),
    )
    .map((service) => ({
      slug: service.slug,
      name: service.name,
      category: service.category,
      status: categoryAllowed(config, service.category)
        ? "allowed"
        : accepted.includes(service.slug)
          ? "accepted"
          : "blocked",
    }));
}

/** A new banner decision starts clean: services accepted one by one before it
 * no longer count, so withdrawing consent also holds those embeds back again.
 * Each accepted service the decision leaves blocked gets a withdrawal record,
 * so the audit trail shows the end of the acceptance as well as its start.
 * Services in `keepServices` stay accepted. */
export function resetEmbedsForDecision(params: {
  config: ConsentStoreConfig;
  scriptToken: string;
  // Services accepted on their own that this decision leaves as they were.
  keepServices?: string[];
}): void {
  const { config, scriptToken, keepServices = [] } = params;
  const accepted = getServiceGrants(config);
  clearUnallowedTrackerCookies(config);
  clearServiceGrants(config);
  keepServices.forEach((slug) => grantService(config, slug));
  refreshEmbeds();
  for (const slug of accepted.filter((s) => !keepServices.includes(s))) {
    const service = allEmbedServices().find((s) => s.slug === slug);
    if (service && !categoryAllowed(config, service.category)) {
      sendServiceConsentBeacon({
        scriptToken,
        serviceSlug: slug,
        granted: false,
      });
    }
  }
}

// Nothing optional allowed: applied when a stricter model arrives for a
// visitor who has not decided, so scripts created from now on stay gated.
export const ALL_DENIED: ConsentState = {
  version: CONSENT_STATE_VERSION,
  decision: "reject_all",
  functionalOptIn: false,
  analyticsOptIn: false,
  marketingOptIn: false,
  decidedAt: 0,
};

/** Called once the published banner config is in: applies the consent model
 * (opt-in or opt-out) this page has just confirmed, and refreshes this
 * loader's cached copy if a newer build exists.
 *
 * When the model changes what this visitor is allowed right now, held scripts
 * and embeds are released (opt-out) or re-gated (opt-in). */
export function onPublishedConfig(
  config: ConsentStoreConfig,
  payload: ViewPayload | null,
): void {
  // A copy of the loader that a later one replaced must not act on its late config.
  if (!payload || !isCurrentInstance()) return;
  // A site that serves its own copy of the loader (the WordPress plugin) is updated with the
  // plugin, never from the CDN.
  if (!usesLocalFiles()) {
    refreshLoaderIfStale({
      config,
      latestBuild: payload.latestLoaderBuild,
      scriptSrc: loaderSrc,
    });
  }
  configureConsentMode(payload.config.consentMode);
  setEmbedStyle(payload.config.style);
  // The categories the site chose for some services: what is held follows them.
  const servicesChanged = setServiceOverrides(payload.config.serviceOverrides);
  if (servicesChanged) applyRuleChange();
  keepServiceOverrides(config.scriptToken);
  // What age rule applies comes first: the Google exemptions and the consent signal
  // below must already know about it.
  const minors = payload.config.targeting?.minors;
  // Off unless the owner turned it on (a config that carries no setting reads as off).
  const teenOn = minors?.teenNotice === true;
  // Ages the site passes count unless the site chose our age screen instead.
  const siteChanged = setSiteAges(minors?.ageSource !== "screen");
  // The teen protections apply in the regions the site picked (one list for the age screen
  // and for ages from the site). A visitor whose region is not known counts as in: the
  // stricter answer, and a US visitor with no state also counts as Californian. A config
  // without the list applies everywhere, as before it existed.
  const regions = minors?.ageScreen?.regions;
  const inRegions =
    !regions ||
    !payload.visitorRegion ||
    regions.includes(payload.visitorRegion) ||
    (!!payload.visitorRegionAlt && regions.includes(payload.visitorRegionAlt));
  const teenChanged = setTeenNotice(teenOn && inRegions);
  // Our age screen: on when chosen and the teen protections apply to this visitor.
  const screenChanged = setAgeScreen(
    teenOn && inRegions && minors?.ageSource === "screen",
  );
  // A US visitor: the Global Privacy Control signal covers marketing only for them (under an
  // opt-out model; see gpcMarketingOnly).
  // (The region keys that start "ca" or "restOfU" are California and the rest of the US.)
  setUsVisitor(/^(ca|restOfU)/.test(payload.visitorRegion ?? ""));
  releaseGoogleHeld();
  signalConsentMode(effectiveState(config));
  const changed = setConsentModel(payload.config.consentModel ?? "opt-in");
  const gpcChanged = setGpcAnalytics(
    payload.config.targeting?.gpcAppliesToAnalytics === true,
  );
  clearUnallowedTrackerCookies(config);
  // A service moved to another category (or back) is held or released under it, after the
  // age and consent-model settings above are in.
  if (
    !changed &&
    !gpcChanged &&
    !teenChanged &&
    !screenChanged &&
    !siteChanged &&
    !servicesChanged
  )
    return;
  applyConsent(effectiveState(config) ?? ALL_DENIED);
  refreshEmbeds();
  // The site's ages stopped (or started) counting: what was held back for the earlier
  // age is drawn again.
  if (siteChanged) ageChangeHandler?.();
}

let ageChangeHandler: (() => void) | null = null;

/** The loader's way of drawing the banner and icon again when the age rule changes. */
export function setAgeChangeHandler(handler: () => void): void {
  ageChangeHandler = handler;
}
