import DOMPurify from 'dompurify';

/**
 * Removes all HTML tags from a string and returns plain text content.
 * Useful for displaying previews or summaries where HTML is not desired.
 * 
 * @param {string} html - The string containing HTML tags
 * @returns {string} - Plain text content
 */
export const stripHtmlTags = (html) => {
  if (!html) return '';
  if (typeof html !== 'string') return String(html);
  
  // Use a temporary DOM element to parse and extract text content safely
  // This is more robust than regex for nested tags and entities
  const temp = document.createElement('div');
  temp.innerHTML = html;
  return temp.textContent || temp.innerText || "";
};

/**
 * Sanitizes HTML content using DOMPurify to prevent XSS attacks while preserving
 * safe HTML structure and styling.
 * 
 * @param {string} html - The HTML string to sanitize
 * @returns {string} - The sanitized HTML string
 */
export const sanitizeHtml = (html) => {
  if (!html) return '';
  
  // Configure DOMPurify to allow specific tags and attributes often used in forms/rich text
  return DOMPurify.sanitize(html, {
    ADD_TAGS: ['iframe', 'style', 'img', 'span', 'div', 'p', 'br', 'strong', 'em', 'u', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'blockquote', 'table', 'tbody', 'tr', 'td', 'th', 'thead'],
    ADD_ATTR: [
      'style', 'class', 'id', 'target', 'href', 'src', 'alt', 'title', 'width', 'height', 
      'align', 'valign', 'bgcolor', 'border', 'cellpadding', 'cellspacing'
    ],
    // Force all links to open in new tab for security/UX
    ADD_URI_SAFE_ATTR: ['src', 'href'],
    FORCE_BODY: false, // Don't wrap in body tag
  });
};

/**
 * Validates HTML content structure.
 * Returns an object with isValid boolean and optional warnings.
 * 
 * @param {string} html - The HTML string to validate
 * @returns {object} - { isValid: boolean, warnings: string[] }
 */
export const validateHtmlContent = (html) => {
  if (!html) return { isValid: true, warnings: [] };

  const warnings = [];
  
  // Check if sanitization fundamentally changes the content (implies unsafe tags were removed)
  const sanitized = sanitizeHtml(html);
  
  // A very rough check for scripts which are definitely not allowed
  if (html.toLowerCase().includes('<script')) {
    warnings.push('Script tags are not allowed and will be removed.');
  }

  if (html.toLowerCase().includes('javascript:')) {
    warnings.push('Javascript protocols in links are not allowed.');
  }

  return {
    isValid: warnings.length === 0,
    warnings,
    sanitized // Return the clean version so caller can use it
  };
};