(function (root, factory) {
  const api = factory();
  if (typeof module === "object" && module.exports) module.exports = api;
  if (root) root.JIANGLAI_TENANT_STATE = api;
})(typeof globalThis !== "undefined" ? globalThis : this, function () {
  "use strict";

  const LEGACY_STORAGE_KEY = "factory_ai_desktop_v1";
  const ACTIVE_COMPANY_KEY = "jianglai_active_company_id";
  const SIGNED_OUT_STORAGE_KEY = `${LEGACY_STORAGE_KEY}_signed_out`;

  function normalizeCompanyId(value) {
    return String(value || "").trim().replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 96);
  }

  function companyStorageKey(companyId) {
    const normalized = normalizeCompanyId(companyId);
    return normalized ? `${LEGACY_STORAGE_KEY}_company_${normalized}` : SIGNED_OUT_STORAGE_KEY;
  }

  function safeGet(storage, key) {
    try { return String(storage?.getItem?.(key) || ""); }
    catch (_) { return ""; }
  }

  function safeSet(storage, key, value) {
    try {
      storage?.setItem?.(key, value);
      return true;
    } catch (_) {
      return false;
    }
  }

  function activate(storage, companyId) {
    const normalized = normalizeCompanyId(companyId);
    if (!normalized) {
      return { companyId:"", storageKey:SIGNED_OUT_STORAGE_KEY, migrated:false };
    }
    const storageKey = companyStorageKey(normalized);
    let migrated = false;
    if (!safeGet(storage, storageKey)) {
      const previousCompanyId = normalizeCompanyId(safeGet(storage, ACTIVE_COMPANY_KEY));
      const legacyPayload = safeGet(storage, LEGACY_STORAGE_KEY);
      // Only the company that last owned the legacy workspace may adopt it.
      // A newly registered or newly switched company always starts clean.
      if (previousCompanyId === normalized && legacyPayload) {
        migrated = safeSet(storage, storageKey, legacyPayload);
      }
    }
    return { companyId:normalized, storageKey, migrated };
  }

  function initialContext(storage) {
    return activate(storage, safeGet(storage, ACTIVE_COMPANY_KEY));
  }

  return {
    LEGACY_STORAGE_KEY,
    ACTIVE_COMPANY_KEY,
    SIGNED_OUT_STORAGE_KEY,
    normalizeCompanyId,
    companyStorageKey,
    activate,
    initialContext,
  };
});
