"use strict";

exports.__esModule = true;
exports.useKanban = void 0;
var _react = require("@wix/bex-core/react");
var _react2 = require("react");
var _KanbanState = require("../state/KanbanState");
const useKanban = params => {
  const container = (0, _react.useWixPatternsContainer)();
  if (!container) {
    throw new Error('useKanban must be used within a WixPatternsContainer');
  }
  const [currentKanbanState, setCurrentKanbanState] = (0, _react2.useState)(() => new _KanbanState.KanbanState({
    ...params,
    container
  }));
  const previousKanbanIdRef = (0, _react2.useRef)(params.kanbanId);
  const stateCleanupFunctionRef = (0, _react2.useRef)(null);
  (0, _react2.useEffect)(() => {
    const hasKanbanIdChanged = previousKanbanIdRef.current !== params.kanbanId;
    if (hasKanbanIdChanged) {
      const recreateKanbanStateForNewId = async () => {
        const cleanupPreviousState = stateCleanupFunctionRef.current;
        if (cleanupPreviousState) {
          cleanupPreviousState();
          stateCleanupFunctionRef.current = null;
        }
        const newKanbanState = new _KanbanState.KanbanState({
          ...params,
          container
        });
        const cleanupFunction = await newKanbanState.init();
        stateCleanupFunctionRef.current = cleanupFunction;
        setCurrentKanbanState(newKanbanState);
        previousKanbanIdRef.current = params.kanbanId;
      };
      recreateKanbanStateForNewId();
    }
  }, [params.kanbanId, container]);
  (0, _react2.useEffect)(() => {
    const needsInitialization = !stateCleanupFunctionRef.current && previousKanbanIdRef.current === params.kanbanId;
    if (needsInitialization) {
      currentKanbanState.init().then(cleanupFunction => {
        const isStillCurrentState = previousKanbanIdRef.current === params.kanbanId;
        if (isStillCurrentState) {
          stateCleanupFunctionRef.current = cleanupFunction;
        } else {
          cleanupFunction == null || cleanupFunction();
        }
      });
    }
  }, [currentKanbanState, params.kanbanId]);
  (0, _react2.useEffect)(() => {
    return () => {
      const cleanupCurrentState = stateCleanupFunctionRef.current;
      if (cleanupCurrentState) {
        cleanupCurrentState();
      }
    };
  }, []);
  return currentKanbanState;
};
exports.useKanban = useKanban;
//# sourceMappingURL=useKanban.js.map