type UndoRedoItem = {
  property: string;
  action: string;
  value: string;
  clone: Node;
  undoElement?: ChildNode | null;
};

export const applyUndo = (element: HTMLElement, item: UndoRedoItem) => {
  if (item.property === 'html') {
    if (item.action !== 'replace') {
      item.undoElement?.remove();
      return;
    }
  }
  element.replaceWith(item.clone);
};

export const applyRedo = (element: HTMLElement, item: UndoRedoItem) => {
  if (item.property === 'html') {
    const parser = new DOMParser();
    const newElement = parser.parseFromString(item.value, 'text/html').body.firstChild;

    if (item.action === 'before') {
      item.undoElement = newElement;
      element.before(newElement as Node);
      return;
    }
    if (item.action === 'after') {
      item.undoElement = newElement;
      element.after(newElement as Node);
      return;
    }
    if (item.action === 'append') {
      element.append(newElement as Node);
      return;
    }
    if (item.action === 'insert') {
      item.undoElement = newElement;
      element.insertBefore(newElement as Node, element.firstChild);
      return;
    }
  }
  element.replaceWith(item.clone);
};
