export const htmlToPlainText = (value?: string | null) => {
  if (!value) return "";

  const decodeEntities = (input: string) => {
    if (typeof document === "undefined") return input;
    const textarea = document.createElement("textarea");
    textarea.innerHTML = input;
    return textarea.value;
  };

  let html = value;
  for (let i = 0; i < 2 && /&(?:lt|gt|amp|quot|#39);/i.test(html); i += 1) {
    html = decodeEntities(html);
  }

  const withBreaks = html
    .replace(/<br\s*\/?>/gi, "\n")
    .replace(/<\/(p|div|li|h[1-6])>/gi, "\n");

  const parsed = typeof DOMParser === "undefined"
    ? withBreaks.replace(/<[^>]*>/g, "")
    : new DOMParser().parseFromString(withBreaks, "text/html").body.textContent || "";

  const lines = parsed
    .replace(/\u00a0/g, " ")
    .split(/\n+/)
    .map((line) => line.replace(/\s+/g, " ").trim())
    .filter(Boolean);

  return lines.filter((line, index) => lines.indexOf(line) === index).join(" ");
};