/**
 * HTML sanitization utilities
 * @countermeasure/web-components/utils/sanitize
 */

import DOMPurify from 'dompurify'

export interface SanitizeHtmlOptions {
  allowSvg?: boolean
}

/** Escape HTML special characters to prevent injection in text content */
export function escapeHtml(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#039;')
}

/** Sanitize HTML to remove dangerous content while preserving safe markup */
export function sanitizeHtml(html: string, options?: SanitizeHtmlOptions): string {
  const config =
    options?.allowSvg === true ? { USE_PROFILES: { svg: true, html: true } } : undefined
  return DOMPurify.sanitize(html, config)
}

/** Safely assign sanitized HTML into an element. */
export function setSafeHtml(
  element: HTMLElement,
  html: string,
  options?: SanitizeHtmlOptions
): void {
  element.innerHTML = sanitizeHtml(html, options)
}

/** Safely assign icon markup while preserving inline SVG support. */
export function setSafeIconHtml(element: HTMLElement, html: string): void {
  setSafeHtml(element, html, { allowSvg: true })
}
