import _slicedToArray from "@babel/runtime/helpers/slicedToArray";
import _typeof from "@babel/runtime/helpers/typeof";
import _classCallCheck from "@babel/runtime/helpers/classCallCheck";
import _createClass from "@babel/runtime/helpers/createClass";
import _defineProperty from "@babel/runtime/helpers/defineProperty";
import _asyncToGenerator from "@babel/runtime/helpers/asyncToGenerator";
import _regeneratorRuntime from "@babel/runtime/regenerator";
import { StorageClient } from '@atlaskit/frontend-utilities/storage-client';
import { getCurrentSiteCloudId, getCurrentSiteCloudIdSync } from '../current-site-cloud-id';
var BASE_URL = '/gateway/api/tap-delivery/api/v3/personalization';
export var PERSONALIZATION_STORAGE_SCOPE = 'smart-card-social-proof';
export var PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX = 'pct-map:v1:';
export var PERSONALIZATION_PROVIDER_PCT_TTL_MS = 24 * 60 * 60 * 1000;
export var SOCIAL_PROOF_TRAIT_NAME = 'sl_3p_connected_providers_site_pct';
var smartCardStorage = new StorageClient(PERSONALIZATION_STORAGE_SCOPE);

/** Keys written by this service in localStorage when using {@link smartCardStorage}. */
var LOCAL_STORAGE_ROW_KEY_PREFIX = "".concat(PERSONALIZATION_STORAGE_SCOPE, "_").concat(PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX);
function scopedCacheKey(cloudId, traitName) {
  return "".concat(cloudId, ":").concat(traitName);
}
function pctMapStorageItemKey(cloudId, traitName) {
  return "".concat(PERSONALIZATION_STORAGE_ITEM_KEY_PREFIX).concat(encodeURIComponent(cloudId), ":").concat(encodeURIComponent(traitName));
}
function fetchSiteTraits(_x) {
  return _fetchSiteTraits.apply(this, arguments);
}
/**
 * Service for fetching site-level traits from the TAP Delivery personalization API.
 */
function _fetchSiteTraits() {
  _fetchSiteTraits = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee3(cloudId) {
    var _data$attributes;
    var response, data;
    return _regeneratorRuntime.wrap(function (_context3) {
      while (1) switch (_context3.prev = _context3.next) {
        case 0:
          _context3.next = 1;
          return fetch("".concat(BASE_URL, "/site/").concat(cloudId), {
            method: 'GET',
            credentials: 'include',
            headers: {
              'Content-Type': 'application/json'
            }
          });
        case 1:
          response = _context3.sent;
          if (response.ok) {
            _context3.next = 2;
            break;
          }
          return _context3.abrupt("return", []);
        case 2:
          _context3.next = 3;
          return response.json();
        case 3:
          data = _context3.sent;
          return _context3.abrupt("return", (_data$attributes = data === null || data === void 0 ? void 0 : data.attributes) !== null && _data$attributes !== void 0 ? _data$attributes : []);
        case 4:
        case "end":
          return _context3.stop();
      }
    }, _callee3);
  }));
  return _fetchSiteTraits.apply(this, arguments);
}
export var PersonalizationService = /*#__PURE__*/function () {
  function PersonalizationService() {
    _classCallCheck(this, PersonalizationService);
    _defineProperty(this, "cache", new Map());
  }
  return _createClass(PersonalizationService, [{
    key: "getProviderPctMapSync",
    value: /** Pure synchronous read for an explicit cloud id / trait pair. */
    function getProviderPctMapSync(cloudId, traitName) {
      if (!cloudId) {
        return null;
      }
      return this.readStoredProviderPctMap(cloudId, traitName);
    }
  }, {
    key: "getProviderPctMap",
    value: function () {
      var _getProviderPctMap = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee2(cloudId, traitName) {
        var _this = this;
        var cacheKey, cachedPromise, promise, retryablePromise;
        return _regeneratorRuntime.wrap(function (_context2) {
          while (1) switch (_context2.prev = _context2.next) {
            case 0:
              if (cloudId) {
                _context2.next = 1;
                break;
              }
              return _context2.abrupt("return", undefined);
            case 1:
              cacheKey = scopedCacheKey(cloudId, traitName);
              cachedPromise = this.cache.get(cacheKey);
              if (!cachedPromise) {
                _context2.next = 2;
                break;
              }
              return _context2.abrupt("return", cachedPromise);
            case 2:
              promise = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee() {
                var traits, trait, mapped, _t;
                return _regeneratorRuntime.wrap(function (_context) {
                  while (1) switch (_context.prev = _context.next) {
                    case 0:
                      _context.prev = 0;
                      _context.next = 1;
                      return fetchSiteTraits(cloudId);
                    case 1:
                      traits = _context.sent;
                      trait = traits.find(function (t) {
                        return t.name === traitName;
                      });
                      mapped = _this.parseTraitValue(trait === null || trait === void 0 ? void 0 : trait.value);
                      if (mapped !== undefined) {
                        _this.writeStoredProviderPctMap(cloudId, traitName, mapped);
                      }
                      return _context.abrupt("return", mapped);
                    case 2:
                      _context.prev = 2;
                      _t = _context["catch"](0);
                      return _context.abrupt("return", undefined);
                    case 3:
                    case "end":
                      return _context.stop();
                  }
                }, _callee, null, [[0, 2]]);
              }))();
              retryablePromise = promise.finally(function () {
                _this.cache.delete(cacheKey);
              });
              this.cache.set(cacheKey, retryablePromise);
              return _context2.abrupt("return", retryablePromise);
            case 3:
            case "end":
              return _context2.stop();
          }
        }, _callee2, this);
      }));
      function getProviderPctMap(_x2, _x3) {
        return _getProviderPctMap.apply(this, arguments);
      }
      return getProviderPctMap;
    }()
  }, {
    key: "readStoredProviderPctMap",
    value: function readStoredProviderPctMap(cloudId, traitName) {
      try {
        var stored = smartCardStorage.getItem(pctMapStorageItemKey(cloudId, traitName));
        if (stored === undefined || stored === null) {
          return null;
        }
        return this.normalizeProviderPctMap(stored);
      } catch (_unused2) {
        return null;
      }
    }
  }, {
    key: "writeStoredProviderPctMap",
    value: function writeStoredProviderPctMap(cloudId, traitName, map) {
      try {
        smartCardStorage.setItemWithExpiry(pctMapStorageItemKey(cloudId, traitName), map, PERSONALIZATION_PROVIDER_PCT_TTL_MS);
      } catch (_unused3) {
        // Quota, private-mode, etc.
      }
    }
  }, {
    key: "normalizeProviderPctMap",
    value: function normalizeProviderPctMap(value) {
      if (_typeof(value) !== 'object' || value === null || Array.isArray(value)) {
        return null;
      }
      var map = {};
      var entries = Object.entries(value);
      for (var _i = 0, _entries = entries; _i < _entries.length; _i++) {
        var _entries$_i = _slicedToArray(_entries[_i], 2),
          providerKey = _entries$_i[0],
          percentageRaw = _entries$_i[1];
        if (typeof percentageRaw !== 'number' || !Number.isFinite(percentageRaw)) {
          return null;
        }
        map[providerKey] = percentageRaw;
      }
      return map;
    }
  }, {
    key: "parseTraitValue",
    value: function parseTraitValue(raw) {
      if (typeof raw !== 'string') {
        return undefined;
      }
      try {
        var parsed = JSON.parse(raw);
        var normalized = this.normalizeProviderPctMap(parsed);
        return normalized === null ? undefined : normalized;
      } catch (_unused4) {
        return undefined;
      }
    }
  }, {
    key: "clearCache",
    value: function clearCache() {
      this.cache.clear();
      this.clearStoredProviderPctMaps();
    }
  }, {
    key: "clearStoredProviderPctMaps",
    value: function clearStoredProviderPctMaps() {
      // eslint-disable-next-line @atlaskit/platform/no-direct-web-storage-usage -- existing usage
      if (typeof globalThis.localStorage === 'undefined' || globalThis.localStorage === null) {
        return;
      }
      var keysToRemove = [];
      // eslint-disable-next-line @atlaskit/platform/no-direct-web-storage-usage -- existing usage
      for (var index = 0; index < globalThis.localStorage.length; index += 1) {
        // eslint-disable-next-line @atlaskit/platform/no-direct-web-storage-usage -- existing usage
        var key = globalThis.localStorage.key(index);
        if (key !== null && key.startsWith(LOCAL_STORAGE_ROW_KEY_PREFIX)) {
          keysToRemove.push(key);
        }
      }
      for (var _i2 = 0, _keysToRemove = keysToRemove; _i2 < _keysToRemove.length; _i2++) {
        var _key = _keysToRemove[_i2];
        try {
          // eslint-disable-next-line @atlaskit/platform/no-direct-web-storage-usage -- existing usage
          globalThis.localStorage.removeItem(_key);
        } catch (_unused5) {
          /* ignore */
        }
      }
    }
  }]);
}();
export var personalizationService = new PersonalizationService();
export var getProviderPctMap = function getProviderPctMap(cloudId, traitName) {
  return personalizationService.getProviderPctMap(cloudId, traitName);
};
export function getProviderPctMapSync(cloudId, traitName) {
  return personalizationService.getProviderPctMapSync(cloudId, traitName);
}

/**
 * Backwards-compatible cache-first helper for inline-card social proof callers.
 *
 * Reads the persisted provider percentage map synchronously using the current site cloud id, then
 * starts a background refresh for subsequent mounts. The async result intentionally does not affect
 * the current call site, matching the warm-cache-only rendering contract.
 */
export function getCachedProviderPctMapAndRefresh(traitName) {
  var cloudId = getCurrentSiteCloudIdSync();
  var providerPctMap = getProviderPctMapSync(cloudId, traitName);
  void getCurrentSiteCloudId().then(function (resolvedCloudId) {
    void getProviderPctMap(resolvedCloudId, traitName);
  });
  return providerPctMap;
}