/**
 * HTML Sanitization Utility
 * Sanitizes HTML content to prevent XSS attacks
 * 
 * Note: For production, consider using DOMPurify library for more robust sanitization
 * For now, this provides basic script tag removal and safe HTML rendering
 */

/**
 * Sanitize HTML string by removing dangerous elements and attributes
 * @param html - The HTML string to sanitize
 * @returns Sanitized HTML string
 */
export function sanitizeHTML(html: string): string {
  if (!html) return '';
  
  // Create a temporary div to parse HTML
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = html;
  
  // Remove script tags and their contents
  const scripts = tempDiv.querySelectorAll('script');
  scripts.forEach(script => script.remove());
  
  // Remove event handlers from all elements
  const allElements = tempDiv.querySelectorAll('*');
  allElements.forEach(el => {
    // Remove all event handlers
    const attributes = el.attributes;
    for (let i = attributes.length - 1; i >= 0; i--) {
      const attr = attributes[i];
      if (attr.name.startsWith('on')) {
        el.removeAttribute(attr.name);
      }
      // Remove javascript: protocol from href/src
      if ((attr.name === 'href' || attr.name === 'src') && attr.value.startsWith('javascript:')) {
        el.removeAttribute(attr.name);
      }
    }
  });
  
  return tempDiv.innerHTML;
}

/**
 * Check if content appears to be HTML
 * @param content - Content to check
 * @returns True if content appears to be HTML
 */
export function isHTML(content: string): boolean {
  if (!content) return false;
  // Check for HTML tags
  return /<[a-z][\s\S]*>/i.test(content);
}

/**
 * Check if content appears to be JSON
 * @param content - Content to check
 * @returns True if content appears to be JSON
 */
export function isJSON(content: string): boolean {
  if (!content) return false;
  try {
    JSON.parse(content);
    return true;
  } catch {
    return false;
  }
}

