/**
 * Client-bootstrap auto-loader.
 *
 * When the SDK script first executes on a host page, it looks for a
 * `window.IL_CLIENT_BOOTSTRAP_LIB` global declared by the host (in AEM this
 * is injected by the `Infralytiqs.html` Sightly fragment). If present, the
 * SDK fetches that client-specific bootstrap JavaScript from the CDN and
 * appends it to <head>. The bootstrap is then responsible for calling
 * `Infralytiqs.init({...})` with tenant/site configuration and wiring any
 * site-specific event hooks.
 *
 * Path resolution
 * ---------------
 * `IL_CLIENT_BOOTSTRAP_LIB` may be either:
 *   • A fully qualified URL ("https://…/bootstrap.min.js") — used as-is.
 *   • A path starting with "/" (e.g. "/cl/publicis/ps/bootstrap.min.js") —
 *     resolved against the SDK's own origin (the CDN host that served this
 *     script). This lets every client bootstrap live in the same S3 bucket
 *     as the SDK without the host page needing to know the CDN hostname.
 *   • A relative path — resolved against the SDK's own URL.
 *
 * The SDK script URL is captured at module-evaluation time via
 * `document.currentScript`, which is only reliable during the SDK's
 * synchronous IIFE execution. A defensive fallback scans existing <script>
 * tags for one whose src matches the SDK bundle naming convention.
 */

const SDK_SCRIPT_URL: string = (() => {
  try {
    if (typeof document === 'undefined') return '';
    const current = document.currentScript as HTMLScriptElement | null;
    if (current && current.src) return current.src;

    const scripts = document.getElementsByTagName('script');
    for (let i = scripts.length - 1; i >= 0; i--) {
      const src = scripts[i].src;
      if (src && /infralytiqs(\.min)?\.js(\?.*)?$/.test(src)) return src;
    }
  } catch {
    /* noop — fall through to empty */
  }
  return '';
})();

const BOOTSTRAP_FLAG = '__il_bootstrap_loaded__';

interface WindowWithBootstrap {
  IL_CLIENT_BOOTSTRAP_LIB?: string;
  [BOOTSTRAP_FLAG]?: boolean;
}

function resolveBootstrapUrl(rawPath: string): string {
  if (/^https?:\/\//i.test(rawPath)) return rawPath;
  if (!SDK_SCRIPT_URL) return rawPath;
  try {
    return new URL(rawPath, SDK_SCRIPT_URL).href;
  } catch {
    return rawPath;
  }
}

/**
 * Injects a <script src="…"> tag for the client bootstrap declared on the
 * host page. Idempotent — a window sentinel guards against double injection
 * if the SDK is somehow evaluated twice.
 */
export function loadClientBootstrap(): void {
  if (typeof window === 'undefined' || typeof document === 'undefined') return;

  const w = window as unknown as WindowWithBootstrap;
  if (w[BOOTSTRAP_FLAG]) return;

  const lib = w.IL_CLIENT_BOOTSTRAP_LIB;
  if (!lib || typeof lib !== 'string') return;

  const absoluteUrl = resolveBootstrapUrl(lib);

  w[BOOTSTRAP_FLAG] = true;

  const s = document.createElement('script');
  s.src = absoluteUrl;
  s.async = true;
  s.setAttribute('data-il-bootstrap', 'client');
  s.onerror = (): void => {
    if (typeof console !== 'undefined') {
      console.error('[Infralytiqs] failed to load client bootstrap from', absoluteUrl);
    }
  };

  const parent = document.head || document.documentElement;
  if (parent) {
    parent.appendChild(s);
  }
}
