/**
 * SERP Preview Component
 *
 * Live preview of how the page will appear in Google search results.
 *
 * @package
 * @since   1.0.0
 */

import { useState, useEffect } from '@wordpress/element';
import { __ } from '@wordpress/i18n';
import { Toggle } from '../ui';
import './styles.css';

const SerpPreview = ({ 
  title = '', 
  description = '', 
  url = '',
  titleTemplate = '',
  descriptionTemplate = '',
  variables = {},
  onTitleChange,
  onDescriptionChange 
}) => {
  const [isMobile, setIsMobile] = useState(false);
  const [processedTitle, setProcessedTitle] = useState('');
  const [processedDescription, setProcessedDescription] = useState('');
  
  // Character limits
  const TITLE_LIMIT = isMobile ? 55 : 60;
  const TITLE_WARNING = isMobile ? 50 : 55;
  const DESC_LIMIT = isMobile ? 120 : 160;
  const DESC_WARNING = isMobile ? 110 : 150;
  
  // Process templates with variables
  const processTemplate = (template, vars) => {
    if (!template) return '';
    
    let processed = template;
    Object.keys(vars).forEach(key => {
      const regex = new RegExp(`[{%]${key}[}%]`, 'g');
      processed = processed.replace(regex, vars[key] || '');
    });
    
    // Clean up any remaining variables
    processed = processed.replace(/[{%][^}%]+[}%]/g, '');
    processed = processed.replace(/\s+/g, ' ').trim();
    
    return processed;
  };
  
  useEffect(() => {
    const finalTitle = title || processTemplate(titleTemplate, variables);
    const finalDesc = description || processTemplate(descriptionTemplate, variables);
    
    setProcessedTitle(finalTitle);
    setProcessedDescription(finalDesc);
  }, [title, description, titleTemplate, descriptionTemplate, variables]);
  
  // Truncate text for display
  const truncateText = (text, limit) => {
    if (!text) return '';
    if (text.length <= limit) return text;
    return text.substring(0, limit - 3) + '...';
  };
  
  // Format URL for display
  const formatUrl = (fullUrl) => {
    if (!fullUrl) return 'example.com › page';
    
    try {
      const urlObj = new URL(fullUrl);
      const domain = urlObj.hostname.replace('www.', '');
      const path = urlObj.pathname.replace(/\/$/, '');
      const breadcrumb = path
        .split('/')
        .filter(p => p)
        .map(p => p.charAt(0).toUpperCase() + p.slice(1))
        .join(' › ');
      
      return breadcrumb ? `${domain} › ${breadcrumb}` : domain;
    } catch (e) {
      return fullUrl;
    }
  };
  
  // Get character count status
  const getCharStatus = (length, warning, limit) => {
    if (length > limit) return 'error';
    if (length > warning) return 'warning';
    return 'good';
  };

  return (
    <div className="prorank-serp-preview">
      <div className="serp-preview-header">
        <h3>{__('SERP Preview', 'prorank-seo')}</h3>
        <Toggle
          label={isMobile ? __('Mobile', 'prorank-seo') : __('Desktop', 'prorank-seo')}
          checked={isMobile}
          onChange={setIsMobile}
          size="sm"
        />
      </div>
      
      <div className={`serp-preview-container ${isMobile ? 'mobile' : 'desktop'}`}>
        <div className="serp-result">
          <div className="serp-url">
            {formatUrl(url)}
          </div>
          
          <div className="serp-title-wrapper">
            <h3 className="serp-title">
              {truncateText(processedTitle || __('Page Title', 'prorank-seo'), TITLE_LIMIT)}
            </h3>
            <div className={`char-counter ${getCharStatus(processedTitle.length, TITLE_WARNING, TITLE_LIMIT)}`}>
              {processedTitle.length}/{TITLE_LIMIT}
            </div>
          </div>
          
          <div className="serp-description-wrapper">
            <div className="serp-description">
              {truncateText(processedDescription || __('Meta description will appear here...', 'prorank-seo'), DESC_LIMIT)}
            </div>
            <div className={`char-counter ${getCharStatus(processedDescription.length, DESC_WARNING, DESC_LIMIT)}`}>
              {processedDescription.length}/{DESC_LIMIT}
            </div>
          </div>
        </div>
      </div>
      
      {onTitleChange && (
        <div className="serp-editor">
          <div className="serp-field">
            <label>{__('SEO Title', 'prorank-seo')}</label>
            <input
              type="text"
              value={title}
              onChange={(e) => onTitleChange(e.target.value)}
              placeholder={processedTitle || __('Enter SEO title...', 'prorank-seo')}
              className={getCharStatus(title.length || processedTitle.length, TITLE_WARNING, TITLE_LIMIT)}
            />
            <span className="field-help">
              {__('Use variables like {sitename}, {sep}, {title}', 'prorank-seo')}
            </span>
          </div>
          
          <div className="serp-field">
            <label>{__('Meta Description', 'prorank-seo')}</label>
            <textarea
              value={description}
              onChange={(e) => onDescriptionChange(e.target.value)}
              placeholder={processedDescription || __('Enter meta description...', 'prorank-seo')}
              rows={3}
              className={getCharStatus(description.length || processedDescription.length, DESC_WARNING, DESC_LIMIT)}
            />
            <span className="field-help">
              {__('Describe your page in 150-160 characters', 'prorank-seo')}
            </span>
          </div>
        </div>
      )}
      
      <div className="serp-preview-tips">
        <h4>{__('Optimization Tips', 'prorank-seo')}</h4>
        <ul>
          {processedTitle.length > TITLE_LIMIT && (
            <li className="tip-error">
              {__('Title is too long and will be truncated', 'prorank-seo')}
            </li>
          )}
          {processedTitle.length < 30 && (
            <li className="tip-warning">
              {__('Title is too short, consider adding more keywords', 'prorank-seo')}
            </li>
          )}
          {processedDescription.length > DESC_LIMIT && (
            <li className="tip-error">
              {__('Description is too long and will be truncated', 'prorank-seo')}
            </li>
          )}
          {processedDescription.length < 100 && (
            <li className="tip-warning">
              {__('Description is too short, add more details', 'prorank-seo')}
            </li>
          )}
          {processedTitle.length >= 30 && processedTitle.length <= TITLE_LIMIT && 
           processedDescription.length >= 100 && processedDescription.length <= DESC_LIMIT && (
            <li className="tip-success">
              {__('Great! Your title and description are optimized', 'prorank-seo')}
            </li>
          )}
        </ul>
      </div>
    </div>
  );
};

export default SerpPreview;