// src/utils/remarkVideoPlugin.ts
import { visit } from 'unist-util-visit';
import type { Plugin } from 'unified';
import type { Root } from 'hast';

function escapeHtml(unsafe: string): string {
  if (typeof unsafe !== 'string') return '';
  
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

export const remarkVideoPlugin: Plugin<[], Root> = () => {
  return (tree: Root) => {
    visit(tree, 'html', (node: any, index: number | undefined, parent: any) => {
      if (node.value && node.value.includes('<video') && typeof index === 'number') {
        const srcMatch = node.value.match(/src=["']([^"']+)["']/);
        const titleMatch = node.value.match(/title=["']([^"']+)["']/);
        
        if (srcMatch) {
          const originalSrc = srcMatch[1];
          const title = titleMatch?.[1] || 'Video';
          
          const hasControls = node.value.includes('controls');
          const hasAutoplay = node.value.includes('autoplay');
          const hasMuted = node.value.includes('muted');
          const hasLoop = node.value.includes('loop');
          const preloadMatch = node.value.match(/preload=["']([^"']+)["']/);
          
          const enhancedHTML = `
            <div class="video-container">
              <video 
                src="${escapeHtml(originalSrc)}"
                ${hasControls ? 'controls' : ''}
                ${hasAutoplay ? 'autoplay' : ''}
                ${hasMuted ? 'muted' : ''}
                ${hasLoop ? 'loop' : ''}
                ${preloadMatch ? `preload="${preloadMatch[1]}"` : 'preload="metadata"'}
                data-video-title="${escapeHtml(title)}"
              >
                <p>Your browser does not support the video element.</p>
              </video>
              ${title !== 'Video' ? `
                <div class="video-metadata">
                  <div class="video-title">${escapeHtml(title)}</div>
                </div>
              ` : ''}
            </div>
          `.trim();
          
          parent.children[index] = { type: 'html', value: enhancedHTML };
          console.log(`[VIDEO] Enhanced: ${title} (${originalSrc})`);
        }
      }
      
      if (node.value && node.value.includes('<iframe') && typeof index === 'number' && parent) {
        
        if (node.value.includes('video-container')) {
          return;
        }
        
        const titleMatch = node.value.match(/title=["']([^"']+)["']/);
        const title = titleMatch?.[1] || 'Embedded Video';
        
        const enhancedHTML = `
          <div class="video-container">
            ${node.value}
          </div>
          <div class="video-metadata">
            <div class="video-title">${escapeHtml(title)}</div>
          </div>
        `.trim();
        
        parent.children[index] = { type: 'html', value: enhancedHTML };
        console.log(`[VIDEO] Enhanced iframe: ${title}`);
      }
    });
  };
};