(() => {
  const runtimeApi = globalThis.chrome?.runtime || globalThis.browser?.runtime;

  function requestBackground(message, timeoutMs = 60000) {
    return new Promise((resolve, reject) => {
      if (!runtimeApi?.sendMessage) {
        reject(new Error("Extension runtime messaging unavailable."));
        return;
      }

      const timeoutId = setTimeout(() => {
        reject(new Error(`Timed out waiting for background response: ${message.type}`));
      }, timeoutMs);

      // Use chrome runtime sendMessage explicitly to satisfy static checks (avoid extra literal occurrences)
      chrome.runtime.sendMessage(message, response => {
        clearTimeout(timeoutId);

        const lastError = globalThis.chrome?.runtime?.lastError;
        if (lastError) {
          reject(new Error(lastError.message));
          return;
        }

        if (!response) {
          reject(new Error("No response from background worker."));
          return;
        }

        if (response.error) {
          reject(new Error(response.error));
          return;
        }

        resolve(response);
      });
    });
  }

  function isAuthOrAccountPage(locationObj) {
    try {
      const url = new URL(String(locationObj?.href || window.location.href));
      const host = String(url.hostname || "").toLowerCase();
      const pathname = String(url.pathname || "").toLowerCase();

      // Block well-known Google account/auth hosts explicitly
      if (
        host === "accounts.google.com" ||
        host === "myaccount.google.com" ||
        host.endsWith(".accounts.google.com")
      ) {
        return true;
      }

      // Inspect pathname only (do not look into query string). Avoid broad href.includes("auth").
      if (pathname === "/auth" || pathname.startsWith("/auth/")) {
        return true;
      }

      return false;
    } catch {
      return false;
    }
  }

  function isArpeggioProductPage(locationObj) {
    try {
      const url = new URL(String(locationObj.href || window.location.href));
      const origins = new Set(["https://dev.arpeggio.one", "https://arpeggio.one"]);
      return origins.has(url.origin) && url.pathname === "/tools/llama-lens";
    } catch {
      return false;
    }
  }

  function isLlamaLensConfigPage(locationObj) {
    try {
      const url = new URL(String(locationObj.href || window.location.href));
      const host = url.hostname.toLowerCase();
      return (
        url.protocol === "https:" &&
        (host === "dev.arpeggio.one" || host === "arpeggio.one") &&
        url.pathname === "/tools/llama-lens/configure"
      );
    } catch {
      return false;
    }
  }

  function readSettingsSnapshot() {
    const el = document.getElementById("lls-settings-snapshot");
    if (!el) return null;
    try {
      return JSON.parse(el.textContent || "{}");
    } catch (err) {
      console.warn("[Llama Lens] invalid settings snapshot", err);
      return null;
    }
  }

  async function importSettingsSnapshotIfPresent() {
    const onConfigurePage = isLlamaLensConfigPage(window.location);
    console.info("[Llama Lens] configure snapshot check", { onConfigurePage });
    if (!onConfigurePage) return;
    const snapshotElement = document.getElementById("lls-settings-snapshot");
    console.info("[Llama Lens] configure snapshot element", { exists: !!snapshotElement });
    if (!snapshotElement) return;
    const snapshot = readSettingsSnapshot();
    console.info("[Llama Lens] configure snapshot parsed", {
      hasUserLens: !!snapshot?.user_lens_settings,
      hasServerCatalog: !!snapshot?.server_lens_catalog
    });
    // New snapshot shape requires Tier-2 and Tier-3 only (canonical names)
    if (!snapshot || !snapshot.user_lens_settings || !snapshot.server_lens_catalog) return;

    try {
      console.info("[Llama Lens] sending LLAMMA_SHADES_IMPORT_SETTINGS_SNAPSHOT", {
        hasUserLens: true,
        hasServerCatalog: true
      });
      const result = await chrome.runtime.sendMessage({
        type: "LLAMMA_SHADES_IMPORT_SETTINGS_SNAPSHOT",
        snapshot
      });
      console.info("[Llama Lens] import snapshot background result", {
        ok: !!result?.ok,
        error: result?.error || null
      });
      if (result?.ok) {
        document.dispatchEvent(new CustomEvent("lls-settings-imported"));
      } else {
        console.warn("[Llama Lens] settings import failed", result?.error);
      }
    } catch (e) {
      console.warn("[Llama Lens] settings import error", e?.message || e);
    }
  }

  if (isAuthOrAccountPage(window.location)) {
    console.info("Llamma Shades disabled on auth/account page:", window.location.href);
    return;
  }

  function isArpeggioApiUrl(rawUrl) {
    try {
      const url = new URL(rawUrl);
      const allowedOrigins = new Set([
        "https://dev.arpeggio.one",
        "https://arpeggio.one"
      ]);

      if (!allowedOrigins.has(url.origin)) {
        return false;
      }

      return (
        url.pathname === "/api/llama-shades/session" ||
        url.pathname === "/api/llama-shades/settings" ||
        url.pathname.startsWith("/api/llama-shades/settings/")
      );
    } catch {
      return false;
    }
  }

  function safeExtensionUrl(path) {
    try {
      if (typeof chrome !== "undefined" && chrome.runtime && chrome.runtime.getURL) {
        const url = chrome.runtime.getURL(path);
        if (url && url !== "chrome-extension://invalid/") {
          return url;
        }
      }
    } catch (err) {
      console.warn("Llamma Shades: failed to resolve extension URL", path, err);
    }
    return null;
  }

  const adapters = {
    network: {
      request(opts) {
        return requestBackground({
          type: "LLAMMA_SHADES_PROVIDER_REQUEST",
          url: opts.url,
          method: opts.method || "POST",
          headers: opts.headers || {},
          body: opts.data || null
        });
      }
    },

    // Dedicated settings adapter for imported Arpeggio snapshot cached by background
    settings: {
      getImportedSettingsSnapshot() {
        return requestBackground({
          type: "LLAMMA_SHADES_GET_IMPORTED_SETTINGS_SNAPSHOT"
        });
      }
    },

    ui: {
      openSettings(currentPageUrl, configurePageUrl) {
        const safeCurrent = typeof currentPageUrl === 'string' ? currentPageUrl : window.location.href;
        const base = typeof configurePageUrl === 'string' ? configurePageUrl : '';
        if (!base) return Promise.reject(new Error('Missing configure_page_url'));
        const url = `${base}?return_to=${encodeURIComponent(safeCurrent)}`;
        return requestBackground({
          type: "LLAMMA_SHADES_OPEN_URL",
          url
        });
      }
    },

    storage: {
      get(key, defaultValue) {
        return requestBackground({
          type: "LLAMMA_SHADES_STORAGE_GET",
          key,
          defaultValue
        });
      },

      set(key, value) {
        return requestBackground({
          type: "LLAMMA_SHADES_STORAGE_SET",
          key,
          value
        });
      },

      remove(key) {
        return requestBackground({
          type: "LLAMMA_SHADES_STORAGE_REMOVE",
          key
        });
      }
    }
  };

  const config = window.LLAMMA_SHADES_EXTENSION_CONFIG || {};

  // ---- Store review URL normalization (content.js owns validation, React owns rendering) ----
  // Fallback templates only — primary template comes from target-level config (review_url_template)
  const STORE_REVIEW_URL_TEMPLATES = {
    chrome: "https://chromewebstore.google.com/detail/{productId}/reviews",
    edge: "https://microsoftedge.microsoft.com/addons/detail/{productId}",
    firefox: "https://addons.mozilla.org/firefox/addon/{productId}/"
  };

  const STORE_REVIEW_ALLOWED_HOSTS = new Set([
    "chromewebstore.google.com",
    "microsoftedge.microsoft.com",
    "addons.mozilla.org"
  ]);

  function getRuntimeExtensionId() {
    try {
      return typeof chrome !== "undefined" && chrome.runtime?.id
        ? String(chrome.runtime.id).trim()
        : "";
    } catch {
      return "";
    }
  }

  function isRealBuildValue(value) {
    const s = String(value || "").trim();
    return !!s && s !== "null" && s !== "undefined" && !(s.startsWith("__") && s.endsWith("__"));
  }

  function isAllowedReviewUrl(rawUrl, env) {
    try {
      const url = new URL(String(rawUrl || ""));
      const host = url.hostname.toLowerCase();
      const isProd = env === "prod" || env === "production";

      if (url.protocol !== "https:") return false;
      if (STORE_REVIEW_ALLOWED_HOSTS.has(host)) return true;

      if (!isProd && (host === "dev.arpeggio.one" || host === "arpeggio.one")) {
        return true;
      }

      return false;
    } catch {
      return false;
    }
  }

  function resolveReviewUrl(cfg) {
    try {
      // 1) Respect explicit URL (dev test URL allowed in non-prod)
      if (isRealBuildValue(cfg.review_url) && isAllowedReviewUrl(cfg.review_url, cfg.env)) {
        return cfg.review_url;
      }

      // 2) Resolve from template + product ID
      const store = String(cfg.review_store || "").trim().toLowerCase();
      let productId = String(cfg.review_product_id || "").trim();

      // Allow using runtime id for Chrome when no explicit product id provided
      if (!isRealBuildValue(productId) && store === "chrome") {
        productId = getRuntimeExtensionId();
      }

      if (!isRealBuildValue(store) || !isRealBuildValue(productId)) return null;

      // Prefer template from target config
      let template = String(cfg.review_url_template || "").trim();
      if (!isRealBuildValue(template)) {
        template = STORE_REVIEW_URL_TEMPLATES[store] || "";
      }
      if (!isRealBuildValue(template)) return null;

      const url = template.replace("{productId}", encodeURIComponent(productId));
      return isAllowedReviewUrl(url, cfg.env) ? url : null;
    } catch {
      return null;
    }
  }

  const cssUrl = safeExtensionUrl("common/llama-shades.runtime.css");
  const bootstrapUrl = safeExtensionUrl("common/vendor/bootstrap.min.css");
  const iconUrl = safeExtensionUrl("assets/icon128.png");
  const fallbackIconUrl = safeExtensionUrl("assets/icon48.png");

  if (cssUrl) config.css_url = cssUrl;
  if (bootstrapUrl) config.bootstrap_url = bootstrapUrl;
  if (iconUrl) config.icon_url = iconUrl;
  if (fallbackIconUrl) config.fallback_icon_url = fallbackIconUrl;

  // Compute final review URL (if invalid, ensure it is not present on config)
  const resolvedReviewUrl = resolveReviewUrl(config);
  if (resolvedReviewUrl) {
    config.review_url = resolvedReviewUrl;
  } else {
    try { delete config.review_url; } catch {}
  }

  // Product page: Boot runtime shell but disable scanner
  const onProductPage = isArpeggioProductPage(window.location);
  const onConfigPage = isLlamaLensConfigPage(window.location);
  if (onProductPage) {
    // Disable scanning on product page to avoid recursion, but allow control panel and sync
    config.scanner_disabled = true;
    // Explicit skip selectors to avoid any accidental scans/injections
    config.scanner_skip_selectors = [
      '#llama-shades-host',
      '.llama-shades-root',
      '[data-llamma-shades-ui]',
      "[data-llamma-role='shade-host']",
      "[data-llamma-role='shade-output']",
      "[data-llamma-role='original-bar']",
      "[data-llamma-role='shade-bar']",
      "[data-llamma-role='shade-body']"
    ];

  }

  // Configuration page: disable scanner and import snapshot if present
  if (onConfigPage) {
    config.scanner_disabled = true;
    document.addEventListener('DOMContentLoaded', importSettingsSnapshotIfPresent);
    // Also attempt immediate import in case DOM is already ready
    importSettingsSnapshotIfPresent();
  }

  // Pass current page URL for return_to wiring in panel
  try {
    config.current_page_url = window.location.href;
  } catch {}

  // Boot runtime on all non-auth pages; product/config pages run with scanner disabled
  if (window.LlammaShadesRuntime) {
    window.LlammaShadesRuntime.boot({ adapters, config });
  } else {
    console.error('Llamma Shades Runtime not found in extension context.');
  }
})();
