import { ref } from 'vue';

export function useHistory(initialState = []) {
  const history = ref([[]]);
  const future = ref([[]]);
  const currentState = ref(initialState);

  // 提交一个新的状态到历史记录
  function commit(newState) {
    history.value.push(newState);
    future.value = []; // 清空未来状态
    currentState.value = newState;
  }

  // 撤销操作
  function undo() {
    if (history.value.length > 1) {
      const previous = history.value[history.value.length - 2];
      history.value.pop();
      future.value.push(currentState.value);
      currentState.value = previous;
    }
  }

  // 重做操作
  function redo() {
    if (future.value.length > 0) {
      const next = future.value.pop();
      history.value.push(currentState.value);
      currentState.value = next;
    }
  }

  // 暴露给外部的方法
  return {
    currentState,
    history,
    future,
    commit,
    undo,
    redo
  };
};
