export function decodeHtml(html = '') {
  if (typeof window === 'undefined') return html;

  const textArea = document.createElement('textarea');
  textArea.innerHTML = html;
  return textArea.value;
}

export function sanitizeCmsHtml(html = '') {
  const decodedHtml = decodeHtml(html);

  if (typeof window === 'undefined') return decodedHtml;

  const template = document.createElement('template');
  template.innerHTML = decodedHtml;

  template.content
    .querySelectorAll('script, iframe, object, embed, link, meta')
    .forEach((node) => node.remove());

  template.content.querySelectorAll('*').forEach((node) => {
    [...node.attributes].forEach((attribute) => {
      const name = attribute.name.toLowerCase();
      const value = attribute.value.trim().toLowerCase();

      if (name.startsWith('on') || value.startsWith('javascript:')) {
        node.removeAttribute(attribute.name);
      }
    });
  });

  return template.innerHTML;
}
