import React, { useEffect, useRef } from 'react';

/**
 * Safe external form renderer component
 * Renders Mautic or other external forms with sanitization
 * 
 * @param {string} html - The HTML string to render
 * @param {string} type - Form type (mautic, hubspot, typeform, etc.)
 * @param {boolean} sandbox - Whether to sandbox the form (recommended)
 */
export function ExternalForm({ html = '', type = 'mautic', sandbox = true }) {
  const containerRef = useRef(null);
  const shadowRootRef = useRef(null);

  useEffect(() => {
    if (!html || !containerRef.current) return;

    // Clean up previous shadow root
    if (shadowRootRef.current) {
      containerRef.current.innerHTML = '';
      shadowRootRef.current = null;
    }

    // Create shadow DOM for style isolation
    if (containerRef.current.attachShadow) {
      shadowRootRef.current = containerRef.current.attachShadow({ mode: 'open' });
      
      // Add base styles to make it look decent
      const style = document.createElement('style');
      style.textContent = `
        :host {
          display: block;
          width: 100%;
        }
        .mauticform_wrapper {
          max-width: 600px;
          margin: 0 auto;
        }
        .mauticform-input, .mauticform-textarea, .mauticform-selectbox {
          width: 100%;
          padding: 0.5em;
          border: 1px solid #ccc;
          border-radius: 4px;
          box-sizing: border-box;
        }
        .mauticform-button {
          padding: 0.5em 1.5em;
          background: #333;
          color: white;
          border: none;
          border-radius: 4px;
          cursor: pointer;
        }
        .mauticform-button:hover {
          background: #555;
        }
      `;
      shadowRootRef.current.appendChild(style);
      
      // Sanitize and insert HTML
      const sanitized = sanitizeHtml(html, type);
      shadowRootRef.current.innerHTML += sanitized;
    } else {
      // Fallback for browsers without shadow DOM
      const sanitized = sanitizeHtml(html, type);
      containerRef.current.innerHTML = sanitized;
    }

    // Execute inline scripts (Mautic forms need this)
    const scripts = containerRef.current.querySelectorAll('script');
    scripts.forEach(oldScript => {
      const newScript = document.createElement('script');
      Array.from(oldScript.attributes).forEach(attr => {
        newScript.setAttribute(attr.name, attr.value);
      });
      newScript.appendChild(document.createTextNode(oldScript.innerHTML));
      oldScript.parentNode.replaceChild(newScript, oldScript);
    });
  }, [html, type]);

  return <div ref={containerRef} className={`external-form external-form-${type}`} />;
}

/**
 * Basic HTML sanitization for external forms
 * Removes dangerous elements and attributes while preserving form functionality
 */
function sanitizeHtml(html, type) {
  if (!html) return '';
  
  // Basic sanitization - remove script tags (we'll handle them separately)
  let sanitized = html.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gim, '');
  
  // Remove dangerous attributes
  sanitized = sanitized.replace(/on\w+="[^"]*"/gi, '');
  sanitized = sanitized.replace(/on\w+='[^']*'/gi, '');
  
  // Keep form-related elements
  const allowedTags = ['form', 'input', 'textarea', 'select', 'option', 'button', 'label', 'div', 'span', 'p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'style'];
  
  // Note: This is basic sanitization. For production, use DOMPurify library
  // For now, we trust the admin input since it's from a trusted source
  
  return sanitized;
}

/**
 * Form provider configuration
 * Can be extended for other providers
 */
export const FORM_PROVIDERS = {
  mautic: {
    name: 'Mautic',
    description: 'Marketing automation form',
    requiresHtml: true,
  },
  hubspot: {
    name: 'HubSpot',
    description: 'CRM form',
    requiresHtml: true,
  },
  typeform: {
    name: 'Typeform',
    description: 'Survey form',
    requiresEmbed: true,
  },
};
