import sanitizeHtml from "sanitize-html";

const allowedTags = [
  ...sanitizeHtml.defaults.allowedTags,
  "h1",
  "h2",
  "h3",
  "h4",
  "h5",
  "h6",
  "img",
  "figure",
  "figcaption",
  "span",
  "br",
  "sup",
  "sub",
  "table",
  "thead",
  "tbody",
  "tr",
  "th",
  "td",
];

export function sanitizeWpHtml(html: string | null | undefined): string {
  if (!html) return "";

  return sanitizeHtml(html, {
    allowedTags,
    allowedSchemes: ["http", "https", "mailto", "tel"],
    allowedAttributes: {
      a: ["href", "name", "target", "rel", "title", "aria-label", "class", "id"],
      img: ["src", "srcset", "sizes", "alt", "title", "width", "height", "loading", "class", "id"],
      "*": ["class", "id", "aria-label", "aria-hidden"],
    },
    transformTags: {
      a: sanitizeHtml.simpleTransform("a", {
        rel: "noopener noreferrer",
      }),
    },
  });
}

export function safeJsonLd(data: unknown): string {
  return JSON.stringify(data).replace(/</g, "\\u003c");
}
