'use client';

import { useEffect, useRef } from 'react';

interface ArticleContentProps {
  content: string;
  aioBox?: {
    title?: string;
    content?: string;
  } | null;
  keyTakeaways?: string | null;
  faqItems?: Array<{
    question: string;
    answer: string;
  }> | null;
  videos?: Array<{
    videoId: string;
    title?: string;
    platform?: string;
  }> | null;
}

export function ArticleContent({ 
  content, 
  aioBox
}: ArticleContentProps) {
  const contentRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!contentRef.current) return;

    // Add IDs to headings for anchor linking (if not already present)
    const headings = contentRef.current.querySelectorAll('h2, h3, h4');
    headings.forEach((heading) => {
      if (!heading.id) {
        const text = heading.textContent || '';
        const id = text
          .toLowerCase()
          .replace(/[^\w\s-]/g, '')
          .replace(/\s+/g, '-')
          .replace(/--+/g, '-')
          .trim();
        heading.id = id;
      }
    });

    // Find all youtube-video divs and convert them to embedded iframes
    const youtubeVideos = contentRef.current.querySelectorAll('.youtube-video');
    
    youtubeVideos.forEach((videoDiv) => {
      const videoId = videoDiv.getAttribute('data-video-id');
      const videoTitle = videoDiv.getAttribute('data-title') || 'YouTube video';
      
      if (videoId) {
        // Create iframe element
        const iframe = document.createElement('iframe');
        iframe.src = `https://www.youtube.com/embed/${videoId}`;
        iframe.title = videoTitle;
        iframe.allow = 'accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture';
        iframe.allowFullscreen = true;
        iframe.loading = 'lazy';
        
        // Clear the div and append iframe
        videoDiv.innerHTML = '';
        videoDiv.appendChild(iframe);
      }
    });
  }, []);

  return (
    <div className="article-content-wrapper">
      {/* AIO Box (AI Overview) - Render if exists */}
      {aioBox && (aioBox.title || aioBox.content) && (
        <div className="aio-box">
          {aioBox.title && <h3>{aioBox.title}</h3>}
          {aioBox.content && (
            <div dangerouslySetInnerHTML={{ __html: aioBox.content }} />
          )}
        </div>
      )}

      {/* Main Article Content with prose-article styles */}
      <div 
        ref={contentRef}
        className="prose-article"
        dangerouslySetInnerHTML={{ __html: content }}
      />
    </div>
  );
}
