import { FeatureFlag } from '../../helpers/feature-control/feature-flag-controller';
import { GlobalSlimmersRegistry } from 'vega-slimmer/core';
import { VegaWatchMethodCancelSlimmer } from '../../helpers/slimmers/global/vega-watch-method-cancel-slimmer';
import { TypographyUrls } from '../../constants/tokens/typography';
import { VegaTranslateObserverSlimmer } from '../../helpers/slimmers/global/vega-translate-observer-slimmer';
import vegaEnvManager from '../../helpers/vega-telemetry-helper/vega-env-manager';
import { vegaNonceManager } from '../../helpers/csp/vega-nonce-manager';
import { VegaNonceInjectorSlimmer } from '../../helpers/slimmers/global/vega-nonce-injector-slimmer';
import { VegaModuleLoader } from '../module-loader/vega-module-loader';
import { VegaThemeManager } from '../../helpers/theme/theme-manager';
// eslint-disable-next-line spellcheck/spell-checker
/**
 * Default export function that will be used by stencil global script,
 * which will be invoked before library loaded.
 *
 * This lean version only contains essential setup that ALL consumers need:
 * - Feature flag configuration from client globals
 * - Global slimmers (component lifecycle hooks)
 * - Typography injection
 * - Telemetry initialization (VegaEnvInfo + runtime metrics)
 * - CSP nonce head patch
 * - VegaModuleLoader on globalThis (for on-demand lazy loading of public API modules)
 * - Apply branding from client global (via VegaModuleLoader, zero static-import cost)
 *
 * The heavier vanilla-JS-only globalThis injections are handled separately
 * by vanillaJsGlobalSetup (only in `vega.esm.js`, the full browser entry).
 * Consumers who want a leaner bundle can use `vega-lean.esm.js` instead.
 */
export default function () {
  disableFeatureFlagFromClientGlobal();
  enableFeatureFlagFromClientGlobal();
  registerGlobalVegaSlimmers();
  injectVegaTypography();
  initRuntimeMetricsTelemetryCollection();
  patchHeadInsertBeforeWithNonce();
  exposeVegaModuleLoader();
  applyBrandingFromClientGlobal();
}
/**
 * Disable feature flags from the client global defined lists.
 */
function disableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaDisabledFeatureKeys']) {
    FeatureFlag.disable(...globalThis['VegaDisabledFeatureKeys']);
  }
}
/**
 * This function enables feature flags based on a global variable in TypeScript.
 */
function enableFeatureFlagFromClientGlobal() {
  if (globalThis['VegaEnabledFeatureKeys']) {
    FeatureFlag.enable(...globalThis['VegaEnabledFeatureKeys']);
  }
}
/**
 * register global vega slimmers
 */
function registerGlobalVegaSlimmers() {
  GlobalSlimmersRegistry.register([
    VegaWatchMethodCancelSlimmer,
    VegaTranslateObserverSlimmer,
    VegaNonceInjectorSlimmer,
  ]);
}
/**
 * Inject Vega typography stylesheet
 */
function injectVegaTypography() {
  Object.keys(TypographyUrls).forEach((key) => {
    const { url } = TypographyUrls[key];
    const typographyLinkId = `vega-typography-${key}`;
    // eslint-disable-next-line no-restricted-globals
    if (!document.querySelector(`#${typographyLinkId}`)) {
      // eslint-disable-next-line no-restricted-globals
      const typographyLink = document.createElement('link');
      typographyLink.id = typographyLinkId;
      typographyLink.href = url;
      typographyLink.rel = 'stylesheet';
      // eslint-disable-next-line no-restricted-globals
      document.head.append(typographyLink);
    }
  });
}
/**
 * init telemetry runtime metrics.
 * 1. Inject VegaEnvInfo to global (used by vega-telemetry-runtime-metrics for environment tracking)
 * 2. Register runtime metrics add page hide listener method
 */
function initRuntimeMetricsTelemetryCollection() {
  globalThis.VegaEnvInfo = vegaEnvManager.getVegaEnv();
  // eslint-disable-next-line spellcheck/spell-checker
  void import('@heartlandone/vega-sandbox-pr-2680-c27afe5ede016b7af4bf1b6953f05353219c36ba-telemetry-runtime-metrics/index').then((
  // eslint-disable-next-line spellcheck/spell-checker
  module) => {
    module['default']['init'](FeatureFlag);
  });
}
/**
 * Patch document.head.insertBefore to ensure nonce is set on injected elements.
 */
function patchHeadInsertBeforeWithNonce() {
  vegaNonceManager.patchHeadInsertBeforeWithNonceToStencil();
}
/**
 * Expose VegaModuleLoader on globalThis so vanilla JS consumers using the lean entry
 * can load public API modules on demand:
 *
 * ```js
 * const VegaThemeManager = await VegaModuleLoader.load('VegaThemeManager');
 * ```
 *
 * VegaModuleLoader has no static imports — all module references use dynamic import(),
 * so adding it here does not increase the lean bundle's initial load size.
 */
function exposeVegaModuleLoader() {
  globalThis['VegaModuleLoader'] = VegaModuleLoader;
}
/**
 * Switch the Vega theme to a new brand theme from the client global defined options.
 *
 * This runs synchronously so that branding is guaranteed to be applied before
 * any component renders, in both the lean and full entries.
 */
function applyBrandingFromClientGlobal() {
  if (globalThis['VegaThemeManagerApplyBranding']) {
    VegaThemeManager.applyBranding(globalThis['VegaThemeManagerApplyBranding']);
  }
}
