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

  const TYPES = Object.freeze({
    IVAC: "ivac",
    FIVA: "fiva",
    CLOUDFLARE: "cloudflareVerification",
    UNSUPPORTED: "unsupported"
  });

  const URLS = Object.freeze({
    IVAC_SIGNIN: "https://appointment.ivacbd.com/signin",
    FIVA_REGISTRATION: "https://indianvisa-bangladesh.nic.in/visa/Registration"
  });

  function parseUrl(url = "") {
    try {
      return new URL(String(url || ""));
    } catch (_) {
      return null;
    }
  }

  function classifyUrl(url = "") {
    const parsed = parseUrl(url);
    const hostname = parsed?.hostname || "";
    const href = parsed?.href || String(url || "");

    if (hostname === "appointment.ivacbd.com") {
      return {
        type: TYPES.IVAC,
        supported: true,
        primary: true,
        url: href,
        hostname,
        label: "IVAC"
      };
    }

    if (hostname === "indianvisa-bangladesh.nic.in") {
      return {
        type: TYPES.FIVA,
        supported: true,
        primary: true,
        url: href,
        hostname,
        label: "Indian Visa"
      };
    }

    if (hostname === "challenges.cloudflare.com" || hostname.endsWith(".cloudflare.com")) {
      return {
        type: TYPES.CLOUDFLARE,
        supported: true,
        primary: false,
        url: href,
        hostname,
        label: "Verification"
      };
    }

    return {
      type: TYPES.UNSUPPORTED,
      supported: false,
      primary: false,
      url: href,
      hostname,
      label: hostname || "Unsupported tab"
    };
  }

  function fromTab(tab = {}) {
    const context = classifyUrl(tab?.url || tab?.pendingUrl || "");
    return {
      ...context,
      tabId: tab?.id || null,
      windowId: tab?.windowId || null,
      active: tab?.active === true,
      status: tab?.status || ""
    };
  }

  function isIvacUrl(url = "") {
    return classifyUrl(url).type === TYPES.IVAC;
  }

  function isFivaUrl(url = "") {
    return classifyUrl(url).type === TYPES.FIVA;
  }

  function isCloudflareUrl(url = "") {
    return classifyUrl(url).type === TYPES.CLOUDFLARE;
  }

  function needsUnsupportedConfirmation(context = {}, targetType = TYPES.IVAC) {
    if (!context || context.type === TYPES.UNSUPPORTED) return true;
    if (targetType === TYPES.IVAC) return context.type !== TYPES.IVAC;
    if (targetType === TYPES.FIVA) return context.type !== TYPES.FIVA;
    return false;
  }

  const SiteContext = Object.freeze({
    TYPES,
    URLS,
    classifyUrl,
    fromTab,
    isCloudflareUrl,
    isFivaUrl,
    isIvacUrl,
    needsUnsupportedConfirmation
  });

  global.VisaFlowX = Object.assign(global.VisaFlowX || {}, { SiteContext });

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