var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/pisellRecordBoard/shellFrame/ResourceWall/PisellRecordBoardResourceWallView.tsx
var PisellRecordBoardResourceWallView_exports = {};
__export(PisellRecordBoardResourceWallView_exports, {
  DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY: () => DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY,
  PisellRecordBoardResourceWallView: () => PisellRecordBoardResourceWallView
});
module.exports = __toCommonJS(PisellRecordBoardResourceWallView_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_locales = require("../../../../locales");
var import_locale = require("../../../../utils/locale");
var import_useRecordBoardContext = require("../../hooks/useRecordBoardContext");
var import_types = require("../../types");
var import_venueWallUtils = require("./venueWallUtils");
var import_VenueWallCard = require("./VenueWallCard");
var import_ResourceWallControlPanel = require("./ResourceWallControlPanel");
var import_ResourceWallViewportToolbar = require("./ResourceWallViewportToolbar");
var import_ResourceWallViewport = require("./ResourceWallViewport.less");
var DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY = "resource_wall_resource_ids";
var RESOURCE_WALL_PSEUDO_FULLSCREEN_STORAGE_KEY = "pisell.recordBoard.resourceWall.pseudoFullscreen";
function readStoredPseudoFullscreen() {
  try {
    return typeof window !== "undefined" && window.localStorage.getItem(RESOURCE_WALL_PSEUDO_FULLSCREEN_STORAGE_KEY) === "1";
  } catch {
    return false;
  }
}
function persistPseudoFullscreen(on) {
  try {
    if (typeof window !== "undefined") {
      window.localStorage.setItem(
        RESOURCE_WALL_PSEUDO_FULLSCREEN_STORAGE_KEY,
        on ? "1" : "0"
      );
    }
  } catch {
  }
}
var FILTER_PARAMS_FIELD = "filter";
var LAYOUT_PRESETS = [
  { key: "1x1", label: "1 × 1", cols: 1, rows: 1 },
  { key: "1x2", label: "1 × 2", cols: 2, rows: 1 },
  { key: "2x3", label: "2 × 3", cols: 3, rows: 2 },
  { key: "3x2", label: "3 × 2", cols: 2, rows: 3 },
  { key: "3x3", label: "3 × 3", cols: 3, rows: 3 },
  { key: "custom", label: "", cols: 3, rows: 2 }
];
var DEFAULT_OCCUPIED = "#6f4ae6";
var DEFAULT_AVAILABLE = "#94a3b8";
var PisellRecordBoardResourceWallView = (props) => {
  var _a;
  const {
    className,
    style,
    loading,
    cards: cardsProp,
    statusToneOverrides: statusToneOverridesProp,
    onStatusToneOverridesChange,
    appearanceTheme: appearanceThemeProp,
    onAppearanceThemeChange,
    appearanceMode: appearanceModeProp,
    onAppearanceModeChange,
    resourceWallLayout: resourceWallLayoutProp,
    onResourceWallLayoutChange,
    statusSortFieldKeys: statusSortFieldKeysProp
  } = props;
  const ctx = (0, import_useRecordBoardContext.useRecordBoardContext)();
  const filterKey = props.filterFieldKey ?? DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY;
  const statusSortFieldKeys = (0, import_react.useMemo)(
    () => statusSortFieldKeysProp != null && statusSortFieldKeysProp.length > 0 ? statusSortFieldKeysProp : [...import_venueWallUtils.DEFAULT_RESOURCE_WALL_STATUS_SORT_FIELD_KEYS],
    [statusSortFieldKeysProp]
  );
  const [localToneOverrides, setLocalToneOverrides] = (0, import_react.useState)({});
  const emitToneOverrides = (0, import_react.useCallback)(
    (next) => {
      onStatusToneOverridesChange == null ? void 0 : onStatusToneOverridesChange(next);
      if (onStatusToneOverridesChange == null) {
        setLocalToneOverrides(next);
      }
    },
    [onStatusToneOverridesChange]
  );
  const [internalAppearanceTheme, setInternalAppearanceTheme] = (0, import_react.useState)({});
  const appearanceTheme = appearanceThemeProp ?? internalAppearanceTheme;
  const persistAppearanceTheme = (0, import_react.useCallback)(
    (next) => {
      onAppearanceThemeChange == null ? void 0 : onAppearanceThemeChange(next);
      if (onAppearanceThemeChange == null) {
        setInternalAppearanceTheme(next);
      }
    },
    [onAppearanceThemeChange]
  );
  const filterValues = (0, import_react.useMemo)(() => {
    var _a2;
    const f = (_a2 = ctx.searchParams) == null ? void 0 : _a2.filter;
    if (!f || typeof f !== "object" || f === null) return void 0;
    const v = f.values;
    if (v === null || v === void 0 || typeof v !== "object" || Array.isArray(v)) {
      return void 0;
    }
    return v;
  }, [ctx.searchParams]);
  const hasResourceWallFilterKey = filterValues != null && Object.prototype.hasOwnProperty.call(filterValues, filterKey);
  const selectedRaw = hasResourceWallFilterKey ? filterValues[filterKey] : void 0;
  const wallSelectedIds = (0, import_react.useMemo)(() => {
    if (!hasResourceWallFilterKey) return [];
    if (!Array.isArray(selectedRaw)) return [];
    const seen = /* @__PURE__ */ new Set();
    const out = [];
    for (const x of selectedRaw) {
      const t = String(x).trim();
      if (!t || seen.has(t)) continue;
      seen.add(t);
      out.push(t);
    }
    return out;
  }, [hasResourceWallFilterKey, selectedRaw]);
  const cards = cardsProp ?? [];
  const cardByResourceId = (0, import_react.useMemo)(() => {
    const m = /* @__PURE__ */ new Map();
    for (const c of cards) {
      m.set(String(c.resourceId), c);
    }
    return m;
  }, [cards]);
  const visibleCards = (0, import_react.useMemo)(() => {
    var _a2;
    if (!wallSelectedIds.length) {
      return [];
    }
    const result = [];
    for (const id of wallSelectedIds) {
      const hit = cardByResourceId.get(String(id));
      if (hit) result.push(hit);
    }
    const parsed = (0, import_venueWallUtils.parseRecordBoardToolbarSortParam)((_a2 = ctx.searchParams) == null ? void 0 : _a2.sort);
    if (parsed && (0, import_venueWallUtils.matchesResourceWallStatusSortField)(parsed.field, statusSortFieldKeys)) {
      const dir = parsed.dir;
      const indexed = result.map((card, idx) => ({ card, idx }));
      indexed.sort((a, b) => {
        const ra = (0, import_venueWallUtils.venueWallOccupiedSortRank)(a.card);
        const rb = (0, import_venueWallUtils.venueWallOccupiedSortRank)(b.card);
        if (ra !== rb) {
          return dir === "asc" ? ra - rb : rb - ra;
        }
        return a.idx - b.idx;
      });
      return indexed.map((x) => x.card);
    }
    return result;
  }, [
    cardByResourceId,
    wallSelectedIds,
    (_a = ctx.searchParams) == null ? void 0 : _a.sort,
    statusSortFieldKeys
  ]);
  const [now, setNow] = (0, import_react.useState)(() => /* @__PURE__ */ new Date());
  (0, import_react.useEffect)(() => {
    const id = window.setInterval(() => setNow(/* @__PURE__ */ new Date()), 1e3);
    return () => window.clearInterval(id);
  }, []);
  const [internalAppearanceMode, setInternalAppearanceMode] = (0, import_react.useState)("light");
  const appearanceModeControlled = appearanceModeProp !== void 0 && onAppearanceModeChange != null;
  const appearanceMode = appearanceModeControlled ? appearanceModeProp : internalAppearanceMode;
  const setAppearanceMode = (0, import_react.useCallback)(
    (m) => {
      onAppearanceModeChange == null ? void 0 : onAppearanceModeChange(m);
      if (!appearanceModeControlled) {
        setInternalAppearanceMode(m);
      }
    },
    [appearanceModeControlled, onAppearanceModeChange]
  );
  const [showControlPanel, setShowControlPanel] = (0, import_react.useState)(false);
  const closeControlPanel = (0, import_react.useCallback)(() => {
    setShowControlPanel(false);
  }, []);
  const [currentPage, setCurrentPage] = (0, import_react.useState)(0);
  const [pseudoFullscreen, setPseudoFullscreen] = (0, import_react.useState)(
    readStoredPseudoFullscreen
  );
  const togglePseudoFullscreen = (0, import_react.useCallback)(() => {
    setPseudoFullscreen((prev) => {
      const next = !prev;
      persistPseudoFullscreen(next);
      return next;
    });
  }, []);
  const shellRef = (0, import_react.useRef)(null);
  (0, import_react.useEffect)(() => {
    const cls = "pisell-resource-wall-fixed-viewport";
    if (typeof document === "undefined") return;
    if (pseudoFullscreen) {
      document.body.classList.add(cls);
    } else {
      document.body.classList.remove(cls);
    }
    return () => {
      document.body.classList.remove(cls);
    };
  }, [pseudoFullscreen]);
  const layoutPersisted = onResourceWallLayoutChange != null;
  const [internalLayout, setInternalLayout] = (0, import_react.useState)(() => ({
    ...import_types.DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST
  }));
  const layoutState = layoutPersisted ? {
    ...import_types.DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST,
    ...resourceWallLayoutProp ?? {}
  } : internalLayout;
  const setLayoutState = (0, import_react.useCallback)(
    (patch) => {
      if (layoutPersisted) {
        onResourceWallLayoutChange({
          ...import_types.DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST,
          ...resourceWallLayoutProp ?? {},
          ...patch
        });
      } else {
        setInternalLayout((prev) => ({
          ...import_types.DEFAULT_RESOURCE_WALL_LAYOUT_PERSIST,
          ...prev,
          ...patch
        }));
      }
    },
    [layoutPersisted, resourceWallLayoutProp, onResourceWallLayoutChange]
  );
  const {
    layoutKey,
    customCols,
    customRows,
    pageDurationSec,
    boardingSoonBeforeMin,
    heroMaxWidthRatio
  } = layoutState;
  const localeKey = (0, import_locale.getCurrentLocale)();
  const layoutPresetsWithI18n = (0, import_react.useMemo)(
    () => LAYOUT_PRESETS.map((p) => ({
      ...p,
      label: p.key === "custom" ? (0, import_locales.getText)("pisell-resource-wall-layout-custom") : p.label
    })),
    [localeKey]
  );
  const modeSlot = appearanceTheme[appearanceMode] ?? {};
  const occupiedCardColor = modeSlot.occupiedCardColor != null && modeSlot.occupiedCardColor !== "" ? modeSlot.occupiedCardColor : DEFAULT_OCCUPIED;
  const availableCardColor = modeSlot.availableCardColor != null && modeSlot.availableCardColor !== "" ? modeSlot.availableCardColor : DEFAULT_AVAILABLE;
  const modeToneOverrides = modeSlot.statusToneOverrides;
  const hasModeToneOverrides = modeToneOverrides != null && Object.keys(modeToneOverrides).length > 0;
  const statusToneOverrides = hasModeToneOverrides ? modeToneOverrides : statusToneOverridesProp !== void 0 ? statusToneOverridesProp : localToneOverrides;
  const selectedLayout = (0, import_react.useMemo)(() => {
    if (layoutKey === "custom") {
      return {
        key: "custom",
        label: (0, import_locales.getText)("pisell-resource-wall-layout-custom"),
        cols: Math.max(1, Math.min(6, customCols)),
        rows: Math.max(1, Math.min(6, customRows))
      };
    }
    return layoutPresetsWithI18n.find((p) => p.key === layoutKey) ?? layoutPresetsWithI18n[2];
  }, [layoutKey, customCols, customRows, layoutPresetsWithI18n]);
  const pageCapacity = selectedLayout.cols * selectedLayout.rows;
  const pagedGroups = (0, import_react.useMemo)(() => {
    const chunks = [];
    for (let i = 0; i < visibleCards.length; i += pageCapacity) {
      chunks.push(visibleCards.slice(i, i + pageCapacity));
    }
    return chunks;
  }, [visibleCards, pageCapacity]);
  const totalPages = Math.max(1, pagedGroups.length);
  const renderCards = pagedGroups[currentPage] ?? visibleCards.slice(0, pageCapacity);
  const controlCarouselPager = (0, import_react.useMemo)(
    () => ({ currentPage, totalPages }),
    [currentPage, totalPages]
  );
  (0, import_react.useEffect)(() => {
    setCurrentPage(
      (p) => totalPages > 0 ? Math.min(p, totalPages - 1) : 0
    );
  }, [totalPages]);
  (0, import_react.useEffect)(() => {
    if (totalPages <= 1) {
      setCurrentPage(0);
      return;
    }
    const ms = Math.max(3, pageDurationSec) * 1e3;
    const timer = window.setInterval(() => {
      setCurrentPage((p) => (p + 1) % totalPages);
    }, ms);
    return () => window.clearInterval(timer);
  }, [totalPages, pageDurationSec]);
  (0, import_react.useEffect)(() => {
    setCurrentPage(0);
  }, [pageCapacity, visibleCards.length]);
  const mergeFilterResourceIds = (0, import_react.useCallback)(
    (ids) => {
      var _a2;
      const sp = ctx.searchParams ?? {};
      const filterValue = sp[FILTER_PARAMS_FIELD];
      const currentValues = (filterValue == null ? void 0 : filterValue.values) ?? {};
      const nextFilter = {
        ...filterValue,
        values: {
          ...currentValues,
          [filterKey]: ids
        }
      };
      (_a2 = ctx.onSearch) == null ? void 0 : _a2.call(ctx, { ...sp, [FILTER_PARAMS_FIELD]: nextFilter });
    },
    [ctx, filterKey]
  );
  const handleControlApply = (0, import_react.useCallback)(
    (payload) => {
      mergeFilterResourceIds(payload.resourceIds);
      setLayoutState({
        layoutKey: payload.layoutKey,
        customCols: payload.customCols,
        customRows: payload.customRows,
        pageDurationSec: payload.pageDurationSec,
        boardingSoonBeforeMin: payload.boardingSoonBeforeMin,
        heroMaxWidthRatio: payload.heroMaxWidthRatio
      });
      const nextSlot = {
        ...appearanceTheme[appearanceMode],
        occupiedCardColor: payload.occupiedCardColor,
        availableCardColor: payload.availableCardColor,
        statusToneOverrides: payload.statusToneOverrides
      };
      persistAppearanceTheme({
        ...appearanceTheme,
        [appearanceMode]: nextSlot
      });
      emitToneOverrides(payload.statusToneOverrides);
    },
    [
      mergeFilterResourceIds,
      emitToneOverrides,
      appearanceTheme,
      appearanceMode,
      persistAppearanceTheme,
      setLayoutState
    ]
  );
  const statusToneMap = (0, import_react.useMemo)(
    () => (0, import_venueWallUtils.getVenueWallStatusToneMap)(statusToneOverrides),
    [statusToneOverrides]
  );
  const isDark = appearanceMode === "dark";
  const pageBg = isDark ? "#0f172a" : "#f5f7fb";
  const headerBg = isDark ? "#1e293b" : "#ffffff";
  const headerBorder = isDark ? "1px solid #334155" : "1px solid #e2e8f0";
  const clockColor = isDark ? "#f1f5f9" : "#0f172a";
  const mutedText = isDark ? "#94a3b8" : "#64748b";
  const toolbarBtnBorder = isDark ? "1px solid #475569" : "1px solid #e2e8f0";
  const toolbarBtnBg = isDark ? "#334155" : "#ffffff";
  const toolbarBtnBgActive = isDark ? "#475569" : "#f1f5f9";
  const countdownSec = Math.max(3, pageDurationSec);
  const shell = /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      ref: shellRef,
      className: `pisell-resource-wall-shell${className ? ` ${className}` : ""}`,
      style: {
        flex: 1,
        minHeight: 0,
        display: "flex",
        flexDirection: "column",
        overflow: "hidden",
        background: pageBg,
        color: clockColor,
        ...style
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_ResourceWallViewportToolbar.ResourceWallViewportToolbar,
      {
        now,
        appearanceMode,
        onAppearanceModeChange: setAppearanceMode,
        pseudoFullscreen,
        onTogglePseudoFullscreen: togglePseudoFullscreen,
        onOpenControlPanel: () => setShowControlPanel(true),
        headerBorder,
        headerBg,
        clockColor,
        mutedText,
        toolbarBtnBorder,
        toolbarBtnBg,
        toolbarBtnBgActive
      }
    ),
    /* @__PURE__ */ import_react.default.createElement("div", { style: { flex: 1, minHeight: 0, padding: 12, display: "flex", flexDirection: "column", gap: 10 } }, totalPages > 1 ? /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          flexShrink: 0,
          display: "flex",
          alignItems: "center",
          gap: 12
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            fontSize: 13,
            fontWeight: 600,
            color: mutedText,
            whiteSpace: "nowrap"
          }
        },
        (0, import_locales.getText)("pisell-resource-wall-page-indicator").replace("{cur}", String(currentPage + 1)).replace("{total}", String(totalPages))
      ),
      /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          style: {
            flex: 1,
            height: 4,
            borderRadius: 2,
            overflow: "hidden",
            background: isDark ? "rgba(255,255,255,0.1)" : "rgba(15,23,42,0.08)"
          }
        },
        /* @__PURE__ */ import_react.default.createElement(
          "div",
          {
            key: `${currentPage}-${countdownSec}`,
            className: "pisell-resource-wall-page-countdown-bar",
            style: {
              height: "100%",
              width: "100%",
              background: occupiedCardColor,
              animationDuration: `${countdownSec}s`
            }
          }
        )
      )
    ) : null, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        style: {
          flex: 1,
          minHeight: 0,
          height: "100%",
          display: "grid",
          gap: 16,
          gridTemplateColumns: `repeat(${selectedLayout.cols}, minmax(0, 1fr))`,
          gridTemplateRows: `repeat(${selectedLayout.rows}, minmax(0, 1fr))`
        }
      },
      renderCards.map((card) => /* @__PURE__ */ import_react.default.createElement(
        import_VenueWallCard.VenueWallCard,
        {
          key: String(card.resourceId),
          card,
          wallNowMs: now.getTime(),
          boardingSoonBeforeMin,
          occupiedCardColor,
          availableCardColor,
          heroMaxWidthRatio,
          statusToneMap,
          appearance: appearanceMode
        }
      ))
    )),
    /* @__PURE__ */ import_react.default.createElement(
      import_ResourceWallControlPanel.ResourceWallControlPanel,
      {
        open: showControlPanel,
        onClose: closeControlPanel,
        isDark,
        layoutPresets: layoutPresetsWithI18n,
        layoutKey,
        customCols,
        customRows,
        pageDurationSec,
        occupiedCardColor,
        availableCardColor,
        boardingSoonBeforeMin,
        statusToneOverrides,
        selectedResourceIds: wallSelectedIds,
        carouselPager: controlCarouselPager,
        heroMaxWidthRatio,
        onApply: handleControlApply
      }
    )
  );
  if (loading && !showControlPanel) {
    return /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className,
        style: {
          flex: 1,
          minHeight: 0,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          background: pageBg,
          ...style
        }
      },
      /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, null)
    );
  }
  return shell;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  DEFAULT_RESOURCE_WALL_FILTER_FIELD_KEY,
  PisellRecordBoardResourceWallView
});
