import type { LocalChange } from 'injector/types';

export const applyHtmlChange = (element: HTMLElement, item: LocalChange) => {
  try {
    const parser = new DOMParser();
    if (!item.value) return;
    const newElement = parser.parseFromString(item.value, 'text/html').body.firstChild as HTMLElement | null;
    if (!newElement) return;

    if (item.action === 'replace') {
      element.replaceWith(newElement);
    } else {
      item.undoElement = newElement;
      if (item.action === 'after') {
        element.after(newElement);
      } else if (item.action === 'before') {
        element.before(newElement);
      } else if (item.action === 'append') {
        element.append(newElement);
      } else if (item.action === 'insert') {
        element.insertBefore(newElement, element.firstChild);
      }
    }
  } catch (error) {}
};
