/* eslint-disable @typescript-eslint/ban-ts-comment */
// @ts-nocheck

function cloneValue(value) {
  if (typeof structuredClone === "function") {
    return structuredClone(value);
  }
  return value == null ? value : JSON.parse(JSON.stringify(value));
}

export function createMapDocumentStore(initialState) {
  const state = {
    width: Math.max(1, Number(initialState?.width) || 1),
    height: Math.max(1, Number(initialState?.height) || 1),
    mapName: String(initialState?.mapName || initialState?.mapId || "Untitled"),
    backgroundColor: String(initialState?.backgroundColor || ""),
    backgroundTileId: String(initialState?.backgroundTileId || ""),
    heightBlurStep: Number.isFinite(Number(initialState?.heightBlurStep))
      ? Number(initialState.heightBlurStep)
      : (Number.isFinite(Number(initialState?.heightDetailStep)) ? Number(initialState.heightDetailStep) : 0.1),
    backgroundCellMode: String(initialState?.backgroundCellMode || "inherit"),
    mapInfoDraft: cloneValue(initialState?.mapInfoDraft) || {},
    roomLayers: cloneValue(initialState?.roomLayers) || [],
    heightLayers: cloneValue(initialState?.heightLayers) || [],
    npcOverlays: cloneValue(initialState?.npcOverlays) || [],
    contentBundle: cloneValue(initialState?.contentBundle) || {},
  };

  function setMapName(value, fallbackMapId) {
    state.mapName = String(value || fallbackMapId || "Untitled");
    return state.mapName;
  }

  function setBackgroundTileId(value, normalizeBackgroundTileId) {
    state.backgroundTileId = typeof normalizeBackgroundTileId === "function"
      ? normalizeBackgroundTileId(value)
      : String(value || "").trim();
    return state.backgroundTileId;
  }

  function setBackgroundCellMode(value, allowedModes) {
    const allowed = Array.isArray(allowedModes) && allowedModes.length > 0
      ? allowedModes.map((entry) => String(entry || ""))
      : ["tile", "hole", "inherit"];
    const normalized = String(value || "");
    state.backgroundCellMode = allowed.includes(normalized) ? normalized : "inherit";
    return state.backgroundCellMode;
  }

  return {
    state,
    setMapName,
    setBackgroundTileId,
    setBackgroundCellMode,
  };
}
