import DOMPurify from 'dompurify';

/**
 * Sanitizes HTML content to prevent XSS attacks
 * Only allows safe formatting tags (bold, italic, emphasis, strong, line breaks)
 *
 * @param dirty - Untrusted HTML string
 * @returns Sanitized HTML string safe for rendering
 */
export function sanitizeHtml(dirty: string): string {
  return DOMPurify.sanitize(dirty, {
    ALLOWED_TAGS: ['b', 'i', 'em', 'strong', 'br'],
    ALLOWED_ATTR: [],
  });
}

/**
 * Sanitizes GrapesJS-authored landing page HTML. Permissive enough to preserve
 * layout (divs, sections, inline styles, classes, data-attrs) while stripping
 * <script>, event-handler attributes, and javascript:/data: URLs.
 *
 * Added 2026-04-12 as defense-in-depth: though only authenticated admins can
 * author these pages, a compromised admin account or stored XSS via a widget
 * embed would otherwise reach every public visitor.
 */
export function sanitizeLandingHtml(dirty: string): string {
  return DOMPurify.sanitize(dirty, {
    // Preserve custom widget placeholders that LandingPage.tsx hydrates via refs.
    ADD_TAGS: ['video-player', 'advanced-video-player', 'donation-widget',
               'pricing-widget', 'product-widget', 'campaign-form-widget',
               'scheduling-poll-widget', 'gallery-ad-card'],
    ADD_ATTR: ['target'],
    FORBID_TAGS: ['script', 'style', 'iframe', 'object', 'embed'],
    FORBID_ATTR: ['onerror', 'onload', 'onclick', 'onmouseover', 'onfocus', 'onblur'],
  });
}

/** CSS sanitizer: strips `@import`, `expression(...)`, and url(javascript:...) vectors. */
export function sanitizeLandingCss(dirty: string): string {
  return dirty
    .replace(/@import[^;]*;?/gi, '')
    .replace(/expression\s*\([^)]*\)/gi, '')
    .replace(/url\s*\(\s*['"]?\s*javascript:[^)]*\)/gi, '');
}
