// What the install snippet's <script> tag says (its data-* attributes). Only
// valid while the loader runs synchronously — document.currentScript is null
// afterwards — so loader.ts reads it once, at init.

import type { ConsentStoreConfig } from "./consent-store";

export function currentScriptDataset(): DOMStringMap | undefined {
  return (document.currentScript as HTMLScriptElement | null)?.dataset;
}

/** True when the install tag carries async or defer: then the page keeps being
 * read while the loader downloads, and anything above it is outside its control. */
export function scriptLoadsAsync(): boolean {
  const script = document.currentScript as HTMLScriptElement | null;
  return (
    script?.hasAttribute("async") || script?.hasAttribute("defer") || false
  );
}

// The most the beacon reports (and the API accepts): a page with more scripts
// than this before the banner is already as bad as it gets, and a larger number
// would make the API refuse the whole beacon.
const MAX_SCRIPTS_REPORTED = 255;

// Framer adds this ~220-character inline snippet to every page above its own head box; the
// owner cannot move ours above it, and it starts no tracker (same rule as
// isBuilderInjectedScript in @consent-management/shared, repeated here to keep the
// loader free of imports).
function isFramerEditorBarCheck(s: HTMLScriptElement): boolean {
  return (
    !s.src &&
    s.text.length <= 400 &&
    s.text.includes("__framer_force_showing_editorbar_since")
  );
}

/** How many other scripts that run come before this one in the page (a src, or
 * inline JavaScript; JSON data blocks and blocked `text/plain` tags do not run),
 * capped at 255, or undefined when this script cannot be found in the document.
 * Any of them can start a tracker before this script is running. */
export function scriptsBeforeThisOne(): number | undefined {
  const own = document.currentScript;
  if (!own) return undefined;
  const scripts = Array.from(document.scripts);
  const index = scripts.indexOf(own as HTMLScriptElement);
  if (index < 0) return undefined;
  return Math.min(
    MAX_SCRIPTS_REPORTED,
    scripts
      .slice(0, index)
      .filter(
        (s) =>
          /^$|^(text|application)\/(x-)?(java|ecma)script$|^module$/i.test(
            s.type,
          ) && !isFramerEditorBarCheck(s),
      ).length,
  );
}

export function readOwnScriptToken(): string | null {
  return currentScriptDataset()?.domainToken ?? null;
}

export function readConsentStoreConfig(
  scriptToken: string,
): ConsentStoreConfig {
  const dataset = currentScriptDataset();
  const isShared = dataset?.consentScope === "shared";
  const rootHostname = isShared ? (dataset?.rootHostname ?? null) : null;
  const rootToken = isShared ? (dataset?.rootToken ?? null) : null;
  const cookieExpiryDays = dataset?.cookieExpiryDays
    ? Number(dataset.cookieExpiryDays)
    : null;
  return { scriptToken, rootHostname, rootToken, cookieExpiryDays };
}
