(function initActiveContextManager(global) {
  "use strict";

  const root = global.VisaFlowX || {};
  if (root.ActiveContextManager) return;

  const UI_STATE_KEY = "vfx.uiState";
  const CONTEXTS = Object.freeze({
    AUTOMATION: "AUTOMATION",
    FIVA: "FIVA"
  });

  function normalizeContext(context = "") {
    const value = String(context || "").trim().toUpperCase();
    return value === CONTEXTS.FIVA ? CONTEXTS.FIVA : CONTEXTS.AUTOMATION;
  }

  function readUiState() {
    try {
      return JSON.parse(global.localStorage?.getItem(UI_STATE_KEY) || "{}");
    } catch (_) {
      return {};
    }
  }

  function writeUiState(patch = {}) {
    const current = readUiState();
    global.localStorage?.setItem(UI_STATE_KEY, JSON.stringify({
      ...current,
      ...patch,
      updatedAt: new Date().toISOString()
    }));
  }

  function contextFromState(state = readUiState()) {
    if (state.activeContext) return normalizeContext(state.activeContext);
    return String(state.activeSection || "").toLowerCase() === "fiva"
      ? CONTEXTS.FIVA
      : CONTEXTS.AUTOMATION;
  }

  function getContext() {
    return contextFromState();
  }

  function sectionFor(context) {
    return normalizeContext(context) === CONTEXTS.FIVA ? "fiva" : "automation";
  }

  function setContext(context, { emit = true } = {}) {
    const nextContext = normalizeContext(context);
    writeUiState({
      activeContext: nextContext,
      activeSection: sectionFor(nextContext)
    });

    if (emit && typeof global.dispatchEvent === "function" && typeof global.CustomEvent === "function") {
      global.dispatchEvent(new CustomEvent("VFX_ACTIVE_CONTEXT_CHANGED", {
        detail: { activeContext: nextContext, activeSection: sectionFor(nextContext) }
      }));
    }

    return nextContext;
  }

  function isFiva(context = getContext()) {
    return normalizeContext(context) === CONTEXTS.FIVA;
  }

  function isAutomation(context = getContext()) {
    return normalizeContext(context) === CONTEXTS.AUTOMATION;
  }

  root.ActiveContextManager = Object.freeze({
    CONTEXTS,
    getContext,
    isAutomation,
    isFiva,
    normalizeContext,
    sectionFor,
    setContext
  });

  global.VisaFlowX = root;

  if (typeof module !== "undefined" && module.exports) {
    module.exports = root.ActiveContextManager;
  }
})(typeof globalThis !== "undefined" ? globalThis : this);
