function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
/**
 * 资源墙 localStorage：解析、校验、首屏读盘（与 PisellReservation 水合/落盘同源）。
 */

import { DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST } from '@pisell/materials';
import { PISELL_RESERVATION_RESOURCE_WALL_FILTER_STORAGE_PREFIX, RESERVATION_RESOURCE_WALL_PERSISTED_FILTER_VALUE_KEYS } from "../reservationConstants";
/**
 * 解析资源墙 localStorage：兼容旧版纯 `string[]`，或 v1 对象（资源 id、白名单 filter 片段、六态配色覆盖）。
 */
function sanitizeVenueWallResourceLayout(raw) {
  if (raw == null || _typeof(raw) !== 'object') return undefined;
  var o = raw;
  var clampInt = function clampInt(v, min, max, d) {
    var n = typeof v === 'number' ? v : Number(v);
    if (!Number.isFinite(n)) return d;
    return Math.max(min, Math.min(max, Math.round(n)));
  };
  var heroRaw = typeof o.heroMaxWidthRatio === 'number' ? o.heroMaxWidthRatio : Number(o.heroMaxWidthRatio);
  var heroMaxWidthRatio = Number.isFinite(heroRaw) ? Math.max(0.4, Math.min(0.8, heroRaw)) : DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST.heroMaxWidthRatio;
  var layoutKey = typeof o.layoutKey === 'string' && o.layoutKey.length > 0 ? o.layoutKey : DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST.layoutKey;
  return {
    layoutKey: layoutKey,
    customCols: clampInt(o.customCols, 1, 6, DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST.customCols),
    customRows: clampInt(o.customRows, 1, 6, DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST.customRows),
    pageDurationSec: clampInt(o.pageDurationSec, 3, 60, DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST.pageDurationSec),
    boardingSoonBeforeMin: clampInt(o.boardingSoonBeforeMin, 1, 60, DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST.boardingSoonBeforeMin),
    heroMaxWidthRatio: heroMaxWidthRatio
  };
}

/** 资源墙外观主题是否含有效数据（用于决定是否落盘 / 是否用磁盘值覆盖 state） */
export function isVenueWallAppearanceThemeNonEmpty(t) {
  var slotHasData = function slotHasData(s) {
    if (!s) return false;
    if (s.occupiedCardColor || s.availableCardColor) return true;
    var o = s.statusToneOverrides;
    return o != null && Object.keys(o).length > 0;
  };
  return slotHasData(t.light) || slotHasData(t.dark);
}

/** 资源墙多选 id：去重且保持首次出现顺序（与勾选 / 落盘顺序一致）。 */
export function dedupeResourceWallIdsPreserveOrder(ids) {
  var seen = new Set();
  var out = [];
  var _iterator = _createForOfIteratorHelper(ids),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var raw = _step.value;
      var t = String(raw).trim();
      if (!t || seen.has(t)) continue;
      seen.add(t);
      out.push(t);
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return out;
}
export function parseResourceWallLocalStorage(raw, whitelist) {
  var empty = {
    filterValuePatches: {}
  };
  if (!raw) return empty;
  try {
    var parsed = JSON.parse(raw);
    if (Array.isArray(parsed)) {
      return {
        resourceIds: parsed.map(String),
        resourceWallResourceIdsInFile: true,
        filterValuePatches: {}
      };
    }
    if (!parsed || _typeof(parsed) !== 'object') return empty;
    var o = parsed;
    var hasRidKey = Object.prototype.hasOwnProperty.call(o, 'resource_wall_resource_ids');
    var ridRaw = o.resource_wall_resource_ids;
    var resourceIds = !hasRidKey ? undefined : Array.isArray(ridRaw) ? ridRaw.map(String) : [];
    var patches = {};
    var fv = o.filter_values;
    if (fv && _typeof(fv) === 'object') {
      var _iterator2 = _createForOfIteratorHelper(whitelist),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var k = _step2.value;
          if (k === 'resource_wall_resource_ids') continue;
          if (Object.prototype.hasOwnProperty.call(fv, k)) {
            patches[k] = fv[k];
          }
        }
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
    }
    var legacyTones = o.venueWallStatusToneOverrides;
    var diskTheme = o.venueWallAppearanceTheme;
    var venueWallAppearanceTheme = diskTheme && _typeof(diskTheme) === 'object' ? diskTheme : undefined;
    if (!venueWallAppearanceTheme && legacyTones && _typeof(legacyTones) === 'object' && Object.keys(legacyTones).length > 0) {
      venueWallAppearanceTheme = {
        light: {
          statusToneOverrides: legacyTones
        },
        dark: {
          statusToneOverrides: legacyTones
        }
      };
    }
    var rawMode = o.venueWallAppearanceMode;
    var venueWallAppearanceMode = rawMode === 'light' || rawMode === 'dark' ? rawMode : undefined;
    var venueWallResourceLayout = sanitizeVenueWallResourceLayout(o.venueWallResourceLayout);
    return {
      resourceIds: resourceIds,
      resourceWallResourceIdsInFile: hasRidKey,
      filterValuePatches: patches,
      venueWallAppearanceTheme: venueWallAppearanceTheme,
      venueWallAppearanceMode: venueWallAppearanceMode,
      venueWallResourceLayout: venueWallResourceLayout
    };
  } catch (_unused) {
    return empty;
  }
}

/**
 * 首屏同步读盘，供 `useState` 初值使用。
 * 避免同一提交内「persist effect 先于 hydrate 的 setState 落盘」时用默认 layout 覆盖 localStorage 里已保存的版式。
 */
export function readResourceWallPersistedSliceFromDisk(bodyViewStorageKey) {
  var _ls$venueWallResource;
  var key = "".concat(PISELL_RESERVATION_RESOURCE_WALL_FILTER_STORAGE_PREFIX, ":").concat(bodyViewStorageKey !== null && bodyViewStorageKey !== void 0 ? bodyViewStorageKey : 'default');
  var raw = null;
  try {
    if (typeof localStorage !== 'undefined') {
      raw = localStorage.getItem(key);
    }
  } catch (_unused2) {
    raw = null;
  }
  var ls = parseResourceWallLocalStorage(raw, RESERVATION_RESOURCE_WALL_PERSISTED_FILTER_VALUE_KEYS);
  return {
    venueWallAppearanceTheme: ls.venueWallAppearanceTheme != null && isVenueWallAppearanceThemeNonEmpty(ls.venueWallAppearanceTheme) ? ls.venueWallAppearanceTheme : {},
    venueWallAppearanceMode: ls.venueWallAppearanceMode === 'light' || ls.venueWallAppearanceMode === 'dark' ? ls.venueWallAppearanceMode : 'light',
    venueWallResourceLayout: (_ls$venueWallResource = ls.venueWallResourceLayout) !== null && _ls$venueWallResource !== void 0 ? _ls$venueWallResource : DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST
  };
}