/**
 * Real-Time Sitemap Preview Component
 * 
 * Shows a live preview of the XML sitemap as settings change
 * Uses Web Worker for performance with large sitemaps
 * 
 * @package ProRank\SEO
 * @since 1.0.0
 */

import { useState, useEffect, useRef } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Spinner } from '@wordpress/components';
import ProrankButton from '../ProrankButton';

interface SitemapPreviewProps {
  settings: any;
  postTypes: any[];
  taxonomies: any[];
}

const SitemapPreview = ({ settings, postTypes, taxonomies }: SitemapPreviewProps) => {
  const [preview, setPreview] = useState<string>('');
  const [loading, setLoading] = useState(true);
  const [activeView, setActiveView] = useState<'formatted' | 'raw'>('formatted');
  const workerRef = useRef<Worker | null>(null);

  useEffect(() => {
    // Initialize Web Worker for generating preview
    if (typeof Worker !== 'undefined' && !workerRef.current) {
      workerRef.current = new Worker('/wp-content/plugins/prorank-seo/assets/workers/sitemap-preview.js');
      
      workerRef.current.onmessage = (e) => {
        if (e.data.type === 'preview') {
          setPreview(e.data.content);
          setLoading(false);
        }
      };
    }

    return () => {
      if (workerRef.current) {
        workerRef.current.terminate();
      }
    };
  }, []);

  useEffect(() => {
    // Generate preview when settings change
    if (workerRef.current && settings.enable_xml_sitemap) {
      setLoading(true);
      workerRef.current.postMessage({
        type: 'generate',
        settings,
        postTypes,
        taxonomies
      });
    }
  }, [settings, postTypes, taxonomies]);

  const generateFormattedPreview = () => {
    if (!preview) return '';
    
    // Parse XML and format for display
    const parser = new DOMParser();
    const xmlDoc = parser.parseFromString(preview, 'text/xml');
    
    const formatNode = (node: Element, depth: number = 0): string => {
      const indent = '  '.repeat(depth);
      let result = `${indent}<span class="prorank-xml-tag">&lt;${node.tagName}&gt;</span>\n`;
      
      if (node.children.length > 0) {
        for (const child of Array.from(node.children)) {
          result += formatNode(child, depth + 1);
        }
      } else if (node.textContent) {
        result = `${indent}<span class="prorank-xml-tag">&lt;${node.tagName}&gt;</span>`;
        result += `<span class="prorank-xml-value">${node.textContent}</span>`;
        result += `<span class="prorank-xml-tag">&lt;/${node.tagName}&gt;</span>\n`;
        return result;
      }
      
      result += `${indent}<span class="prorank-xml-tag">&lt;/${node.tagName}&gt;</span>\n`;
      return result;
    };

    const root = xmlDoc.documentElement;
    return formatNode(root);
  };

  const downloadSitemap = () => {
    const blob = new Blob([preview], { type: 'application/xml' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'sitemap-preview.xml';
    a.click();
    URL.revokeObjectURL(url);
  };

  const copyToClipboard = async () => {
    try {
      await navigator.clipboard.writeText(preview);
      // Show success feedback
      const button = document.querySelector('.prorank-copy-button');
      if (button) {
        button.textContent = __('Copied!', 'prorank-seo');
        setTimeout(() => {
          button.textContent = __('Copy XML', 'prorank-seo');
        }, 2000);
      }
    } catch (err) {
      // Silently fail
    }
  };

  if (!settings.enable_xml_sitemap) {
    return (
      <div className="prorank-sitemap-preview-disabled">
        <p>{__('Enable XML Sitemaps to see a preview', 'prorank-seo')}</p>
      </div>
    );
  }

  return (
    <div className="prorank-sitemap-preview">
      <div className="prorank-preview-header">
        <h3>{__('Sitemap Preview', 'prorank-seo')}</h3>
        <div className="prorank-preview-actions">
          <ProrankButton
            variant={activeView === 'formatted' ? 'primary' : 'secondary'}
            size="small"
            onClick={() => setActiveView('formatted')}
          >
            {__('Formatted', 'prorank-seo')}
          </ProrankButton>
          <ProrankButton
            variant={activeView === 'raw' ? 'primary' : 'secondary'}
            size="small"
            onClick={() => setActiveView('raw')}
          >
            {__('Raw XML', 'prorank-seo')}
          </ProrankButton>
          <ProrankButton
            variant="secondary"
            size="small"
            className="prorank-copy-button"
            onClick={copyToClipboard}
          >
            {__('Copy XML', 'prorank-seo')}
          </ProrankButton>
          <ProrankButton
            variant="secondary"
            size="small"
            onClick={downloadSitemap}
          >
            {__('Download', 'prorank-seo')}
          </ProrankButton>
        </div>
      </div>

      <div className="prorank-preview-content">
        {loading ? (
          <div className="prorank-preview-loading">
            <Spinner />
            <p>{__('Generating preview...', 'prorank-seo')}</p>
          </div>
        ) : (
          <div className="prorank-preview-code">
            {activeView === 'formatted' ? (
              <pre 
                className="prorank-xml-formatted"
                dangerouslySetInnerHTML={{ __html: generateFormattedPreview() }}
              />
            ) : (
              <pre className="prorank-xml-raw">{preview}</pre>
            )}
          </div>
        )}
      </div>

    </div>
  );
};

export default SitemapPreview;