/**
 * Decode HTML entities (e.g. &laquo; → «) to plain text — safe to use as textContent.
 * Uses a detached textarea so no HTML is ever rendered to the DOM.
 */
export function decodeHtmlEntities(html: string): string {
  const el = document.createElement("textarea");
  el.innerHTML = html;
  return el.value;
}

/**
 * Minimal XSS sanitizer for trusted-but-unvalidated HTML strings.
 * Strips script/iframe/object elements and on* / javascript: attributes.
 * Use DOMPurify for stricter sanitization requirements.
 */
export function sanitizeHtml(html: string): string {
  const doc = new DOMParser().parseFromString(html, "text/html");

  doc
    .querySelectorAll("script, iframe, object, embed, form, base, link, meta")
    .forEach((el) => el.remove());

  doc.querySelectorAll("*").forEach((el) => {
    Array.from(el.attributes).forEach((attr) => {
      if (
        attr.name.startsWith("on") ||
        (attr.name === "href" &&
          attr.value.trimStart().startsWith("javascript:")) ||
        (attr.name === "src" &&
          attr.value.trimStart().startsWith("javascript:"))
      ) {
        el.removeAttribute(attr.name);
      }
    });
  });

  return doc.body.innerHTML;
}
