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 ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
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); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
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 _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useEffect, useRef, useState } from 'react';
import { dedupeResourceWallIdsPreserveOrder, isVenueWallAppearanceThemeNonEmpty, parseResourceWallLocalStorage, readResourceWallPersistedSliceFromDisk } from "../data/resourceWallLocalStorage";
import { PISELL_RESERVATION_RESOURCE_WALL_FILTER_STORAGE_PREFIX, RESERVATION_RESOURCE_WALL_PERSISTED_FILTER_VALUE_KEYS } from "../reservationConstants";
/**
 * 资源墙：首屏读盘 state、localStorage 水合 / id 剪枝 / 筛参落盘（三 effect 顺序与 PisellReservation 旧版一致）。
 */
export function useReservationResourceWallPersist(_ref) {
  var bodyViewStorageKey = _ref.bodyViewStorageKey,
    isInternalListData = _ref.isInternalListData,
    searchParams = _ref.searchParams,
    onSearch = _ref.onSearch,
    venueWallCards = _ref.venueWallCards,
    floorDayBookingLoading = _ref.floorDayBookingLoading;
  var resourceWallFilterHydratedRef = useRef(false);
  var _useState = useState(function () {
      return readResourceWallPersistedSliceFromDisk(bodyViewStorageKey);
    }),
    _useState2 = _slicedToArray(_useState, 1),
    venueWallBoot = _useState2[0];
  var _useState3 = useState(venueWallBoot.venueWallAppearanceTheme),
    _useState4 = _slicedToArray(_useState3, 2),
    venueWallAppearanceTheme = _useState4[0],
    setVenueWallAppearanceTheme = _useState4[1];
  var _useState5 = useState(venueWallBoot.venueWallAppearanceMode),
    _useState6 = _slicedToArray(_useState5, 2),
    venueWallAppearanceMode = _useState6[0],
    setVenueWallAppearanceMode = _useState6[1];
  var _useState7 = useState(venueWallBoot.venueWallResourceLayout),
    _useState8 = _slicedToArray(_useState7, 2),
    venueWallResourceLayout = _useState8[0],
    setVenueWallResourceLayout = _useState8[1];
  var resourceWallFilterStorageKey = "".concat(PISELL_RESERVATION_RESOURCE_WALL_FILTER_STORAGE_PREFIX, ":").concat(bodyViewStorageKey !== null && bodyViewStorageKey !== void 0 ? bodyViewStorageKey : 'default');

  /** 大屏资源多选：localStorage v1 恢复（id 与勾选一致，不与画布/日历列表求交），并持久化变更（不上传独立接口） */
  useEffect(function () {
    var _lsParsed, _lsParsed$resourceIds;
    if (!isInternalListData) return;
    if (resourceWallFilterHydratedRef.current) return;
    var fv = searchParams === null || searchParams === void 0 ? void 0 : searchParams.filter;
    var values = fv && _typeof(fv) === 'object' && fv !== null && _typeof(fv.values) === 'object' && fv.values !== null ? fv.values : {};
    var whitelist = RESERVATION_RESOURCE_WALL_PERSISTED_FILTER_VALUE_KEYS;
    var lsParsed = {
      filterValuePatches: {}
    };
    try {
      var raw = localStorage.getItem(resourceWallFilterStorageKey);
      lsParsed = parseResourceWallLocalStorage(raw, whitelist);
    } catch (_unused) {
      /* keep default */
    }
    if (((_lsParsed = lsParsed) === null || _lsParsed === void 0 ? void 0 : _lsParsed.venueWallAppearanceTheme) != null && isVenueWallAppearanceThemeNonEmpty(lsParsed.venueWallAppearanceTheme)) {
      setVenueWallAppearanceTheme(lsParsed.venueWallAppearanceTheme);
    }
    if (lsParsed.venueWallAppearanceMode === 'light' || lsParsed.venueWallAppearanceMode === 'dark') {
      setVenueWallAppearanceMode(lsParsed.venueWallAppearanceMode);
    }
    if (lsParsed.venueWallResourceLayout != null) {
      setVenueWallResourceLayout(lsParsed.venueWallResourceLayout);
    }
    var existing = values.resource_wall_resource_ids;
    if (Array.isArray(existing) && existing.length > 0) {
      var hasPatches = Object.keys(lsParsed.filterValuePatches).length > 0;
      if (onSearch && hasPatches) {
        onSearch(_objectSpread(_objectSpread({}, searchParams), {}, {
          filter: _objectSpread(_objectSpread({}, _typeof(searchParams.filter) === 'object' && searchParams.filter !== null ? searchParams.filter : {}), {}, {
            values: _objectSpread(_objectSpread(_objectSpread({}, _typeof(values) === 'object' ? values : {}), lsParsed.filterValuePatches), {}, {
              resource_wall_resource_ids: existing.map(String)
            })
          })
        }));
      }
      resourceWallFilterHydratedRef.current = true;
      return;
    }
    var explicitRid = lsParsed.resourceWallResourceIdsInFile === true;
    var idsFromLs = (_lsParsed$resourceIds = lsParsed.resourceIds) !== null && _lsParsed$resourceIds !== void 0 ? _lsParsed$resourceIds : [];
    var finalList = explicitRid ? dedupeResourceWallIdsPreserveOrder(idsFromLs) : [];
    resourceWallFilterHydratedRef.current = true;
    if (!onSearch) return;
    onSearch(_objectSpread(_objectSpread({}, searchParams), {}, {
      filter: _objectSpread(_objectSpread({}, _typeof(searchParams.filter) === 'object' && searchParams.filter !== null ? searchParams.filter : {}), {}, {
        values: _objectSpread(_objectSpread(_objectSpread({}, _typeof(values) === 'object' ? values : {}), lsParsed.filterValuePatches), {}, {
          resource_wall_resource_ids: finalList
        })
      })
    }));
  }, [isInternalListData, resourceWallFilterStorageKey, onSearch, searchParams]);
  useEffect(function () {
    if (!isInternalListData) return;
    if (!resourceWallFilterHydratedRef.current) return;
    if (floorDayBookingLoading) return;
    if (venueWallCards.length === 0) return;
    var fv = searchParams === null || searchParams === void 0 ? void 0 : searchParams.filter;
    if (!fv || _typeof(fv) !== 'object' || fv === null) return;
    var vals = fv.values;
    if (!vals || _typeof(vals) !== 'object' || Array.isArray(vals)) return;
    var existingRaw = vals.resource_wall_resource_ids;
    if (!Array.isArray(existingRaw)) return;
    var existingIds = existingRaw.map(function (x) {
      return String(x);
    });
    var validIdSet = new Set(venueWallCards.map(function (c) {
      return String(c.resourceId);
    }));
    var prunedIds = existingIds.filter(function (id) {
      return validIdSet.has(id);
    });
    if (prunedIds.length === existingIds.length) return;
    onSearch === null || onSearch === void 0 || onSearch(_objectSpread(_objectSpread({}, searchParams), {}, {
      filter: _objectSpread(_objectSpread({}, fv), {}, {
        values: _objectSpread(_objectSpread({}, vals), {}, {
          resource_wall_resource_ids: prunedIds
        })
      })
    }));
  }, [isInternalListData, venueWallCards, floorDayBookingLoading, searchParams, onSearch]);
  useEffect(function () {
    if (!isInternalListData) return;
    var fv = searchParams === null || searchParams === void 0 ? void 0 : searchParams.filter;
    if (!fv || _typeof(fv) !== 'object' || fv === null || _typeof(fv.values) !== 'object' || fv.values === null) {
      return;
    }
    var vals = fv.values;
    var rid = vals.resource_wall_resource_ids;
    if (!Array.isArray(rid)) return;
    var ridStable = dedupeResourceWallIdsPreserveOrder(rid.map(String));
    var filter_values = {};
    var _iterator = _createForOfIteratorHelper(RESERVATION_RESOURCE_WALL_PERSISTED_FILTER_VALUE_KEYS),
      _step;
    try {
      for (_iterator.s(); !(_step = _iterator.n()).done;) {
        var k = _step.value;
        if (k === 'resource_wall_resource_ids') continue;
        if (Object.prototype.hasOwnProperty.call(vals, k)) {
          filter_values[k] = vals[k];
        }
      }
    } catch (err) {
      _iterator.e(err);
    } finally {
      _iterator.f();
    }
    var pack = {
      v: 1,
      resource_wall_resource_ids: ridStable
    };
    if (Object.keys(filter_values).length > 0) {
      pack.filter_values = filter_values;
    }
    if (isVenueWallAppearanceThemeNonEmpty(venueWallAppearanceTheme)) {
      pack.venueWallAppearanceTheme = venueWallAppearanceTheme;
    }
    pack.venueWallAppearanceMode = venueWallAppearanceMode;
    pack.venueWallResourceLayout = venueWallResourceLayout;
    try {
      localStorage.setItem(resourceWallFilterStorageKey, JSON.stringify(pack));
    } catch (_unused2) {
      /* ignore */
    }
  }, [isInternalListData, searchParams, resourceWallFilterStorageKey, venueWallAppearanceTheme, venueWallAppearanceMode, venueWallResourceLayout]);
  return {
    venueWallAppearanceTheme: venueWallAppearanceTheme,
    setVenueWallAppearanceTheme: setVenueWallAppearanceTheme,
    venueWallAppearanceMode: venueWallAppearanceMode,
    setVenueWallAppearanceMode: setVenueWallAppearanceMode,
    venueWallResourceLayout: venueWallResourceLayout,
    setVenueWallResourceLayout: setVenueWallResourceLayout
  };
}