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

import { normalizePanelFolderLayout } from "./panelFolders";

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

export function normalizeEditorUiState(rawState) {
  const source = rawState && typeof rawState === "object" && !Array.isArray(rawState)
    ? rawState
    : {};
  const rawLayouts = source.panelLayouts && typeof source.panelLayouts === "object" && !Array.isArray(source.panelLayouts)
    ? source.panelLayouts
    : {};
  return {
    panelLayouts: { ...rawLayouts },
  };
}

export function createEditorUiStore(initialState) {
  let state = normalizeEditorUiState(initialState);

  function getState() {
    return state;
  }

  function setState(nextState) {
    state = normalizeEditorUiState(nextState);
    return state;
  }

  function cloneState(sourceState) {
    if (sourceState !== undefined) {
      return normalizeEditorUiState(cloneValue(sourceState) || { panelLayouts: {} });
    }
    return normalizeEditorUiState(cloneValue(state) || { panelLayouts: {} });
  }

  function getPanelLayout(panelKey, itemIds) {
    const normalizedKey = String(panelKey || "").trim();
    if (!normalizedKey) {
      return normalizePanelFolderLayout({}, itemIds);
    }
    const nextLayout = normalizePanelFolderLayout(state.panelLayouts[normalizedKey], itemIds);
    state = {
      ...state,
      panelLayouts: {
        ...state.panelLayouts,
        [normalizedKey]: nextLayout,
      },
    };
    return nextLayout;
  }

  function setPanelLayout(panelKey, nextLayout, itemIds) {
    const normalizedKey = String(panelKey || "").trim();
    if (!normalizedKey) {
      return normalizePanelFolderLayout({}, itemIds);
    }
    const normalizedLayout = normalizePanelFolderLayout(nextLayout, itemIds);
    state = {
      ...state,
      panelLayouts: {
        ...state.panelLayouts,
        [normalizedKey]: normalizedLayout,
      },
    };
    return normalizedLayout;
  }

  function updatePanelLayout(panelKey, itemIds, updater) {
    const currentLayout = getPanelLayout(panelKey, itemIds);
    const nextLayout = typeof updater === "function" ? updater(cloneValue(currentLayout)) : currentLayout;
    return setPanelLayout(panelKey, nextLayout, itemIds);
  }

  return {
    getState,
    setState,
    cloneState,
    getPanelLayout,
    setPanelLayout,
    updatePanelLayout,
  };
}
