

declare global {
  var __ASUKA_PDF_SUPPORT__: {
    scriptUrl?: string;
    autoLoad?: boolean;
    enabled?: boolean;
  } | undefined;
  var __ASUKA_PDF_SUPPORT_PROMISE__: Promise<any | null> | undefined;
}

export type AsukaPdfSupportConfig = {
  scriptUrl?: string;
  autoLoad?: boolean;
  enabled?: boolean;
};

export const DEFAULT_JSPDF_SCRIPT_URL = 'https://cdn.jsdelivr.net/npm/jspdf@4.2.1/dist/jspdf.umd.min.js';

function getGlobalScope(): any {
  return globalThis as any;
}

function getConfig(override?: AsukaPdfSupportConfig | null): AsukaPdfSupportConfig {
  const g = getGlobalScope();
  const enabled = override?.enabled ?? g.__ASUKA_PDF_SUPPORT__?.enabled ?? true;
  return {
    enabled,
    autoLoad: override?.autoLoad ?? g.__ASUKA_PDF_SUPPORT__?.autoLoad ?? true,
    scriptUrl: enabled === false
      ? undefined
      : (override?.scriptUrl ?? g.__ASUKA_PDF_SUPPORT__?.scriptUrl ?? DEFAULT_JSPDF_SCRIPT_URL),
  };
}

export function configurePdfSupport(config?: AsukaPdfSupportConfig | null): void {
  const g = getGlobalScope();
  g.__ASUKA_PDF_SUPPORT__ = {
    ...(g.__ASUKA_PDF_SUPPORT__ ?? {}),
    ...(config ?? {}),
  };
}

export function getGlobalJsPdfCtor(): any | null {
  const g = getGlobalScope();
  const fromJspdfNs = g.jspdf?.jsPDF ?? g.jspdf?.default?.jsPDF ?? g.jspdf?.default ?? null;
  const fromWindowCtor = g.jsPDF ?? null;
  return fromJspdfNs ?? fromWindowCtor ?? null;
}

export function isPdfSupportEnabled(config?: AsukaPdfSupportConfig | null): boolean {
  return getConfig(config).enabled !== false;
}

export function isPdfAvailable(config?: AsukaPdfSupportConfig | null): boolean {
  if (!isPdfSupportEnabled(config)) return false;
  return !!getGlobalJsPdfCtor();
}

export function canLoadPdfSupport(config?: AsukaPdfSupportConfig | null): boolean {
  const resolved = getConfig(config);
  if (resolved.enabled === false) return false;
  return !!String(resolved.scriptUrl ?? '').trim();
}

export async function ensurePdfSupport(config?: AsukaPdfSupportConfig | null): Promise<any | null> {
  const resolved = getConfig(config);
  if (resolved.enabled === false) return null;
  const existing = getGlobalJsPdfCtor();
  if (existing) return existing;
  const url = String(resolved.scriptUrl ?? '').trim();
  if (!url || resolved.autoLoad === false) return null;
  const g = getGlobalScope();
  if (g.__ASUKA_PDF_SUPPORT_PROMISE__) return g.__ASUKA_PDF_SUPPORT_PROMISE__;
  g.__ASUKA_PDF_SUPPORT_PROMISE__ = new Promise((resolve) => {
    if (typeof document === 'undefined') {
      resolve(null);
      return;
    }
    const selector = `script[data-asuka-pdf-support="${url}"]`;
    const existingScript = document.querySelector(selector) as HTMLScriptElement | null;
    if (existingScript) {
      existingScript.addEventListener('load', () => resolve(getGlobalJsPdfCtor()), { once: true });
      existingScript.addEventListener('error', () => resolve(null), { once: true });
      return;
    }
    const script = document.createElement('script');
    script.src = url;
    script.async = true;
    script.defer = true;
    script.dataset.asukaPdfSupport = url;
    script.onload = () => resolve(getGlobalJsPdfCtor());
    script.onerror = () => resolve(null);
    document.head.appendChild(script);
  }).finally(() => {
    g.__ASUKA_PDF_SUPPORT_PROMISE__ = undefined;
  });
  return g.__ASUKA_PDF_SUPPORT_PROMISE__;
}
