/**
 * ProRank SEO - SERPPreviewPro Component
 *
 * Live Google SERP preview with real-time updates
 * Includes CTR prediction gauge and character counters
 *
 * @package ProRank\SEO
 */

import { useState, useEffect, useMemo } from '@wordpress/element';
import CharacterBar, { CharacterBarPresets } from './CharacterBar.jsx';

/**
 * Calculate estimated CTR based on title and description optimization
 */
const calculateCTR = (title, description, hasRichSnippet = false) => {
  let ctr = 2.5; // Base CTR for position 1

  // Title optimization factors
  if (title.length >= 30 && title.length <= 60) ctr += 1.5;
  if (title.length > 60) ctr -= 0.5;
  if (title.includes('|') || title.includes('-')) ctr += 0.3;

  // Description optimization factors
  if (description.length >= 120 && description.length <= 160) ctr += 1.2;
  if (description.length > 160) ctr -= 0.3;

  // Power words boost
  const powerWords = ['free', 'best', 'guide', 'how to', 'tips', 'easy', 'quick', 'new', '2024', '2025'];
  const titleLower = title.toLowerCase();
  powerWords.forEach(word => {
    if (titleLower.includes(word)) ctr += 0.2;
  });

  // Rich snippet boost
  if (hasRichSnippet) ctr += 2.0;

  // Cap at realistic values
  return Math.min(Math.max(ctr, 0.5), 15);
};

/**
 * Truncate text at pixel width (approximate)
 */
const truncateText = (text, maxChars, type = 'title') => {
  if (!text) return '';
  if (text.length <= maxChars) return text;
  return text.substring(0, maxChars) + '...';
};

/**
 * CTR Gauge Component
 */
const CTRGauge = ({ ctr = 0, animate = true }) => {
  const [animatedCTR, setAnimatedCTR] = useState(0);

  useEffect(() => {
    if (!animate) {
      setAnimatedCTR(ctr);
      return;
    }

    const duration = 1000;
    const startTime = Date.now();
    const startValue = animatedCTR;

    const animateGauge = () => {
      const elapsed = Date.now() - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      setAnimatedCTR(startValue + (ctr - startValue) * eased);

      if (progress < 1) {
        requestAnimationFrame(animateGauge);
      }
    };

    requestAnimationFrame(animateGauge);
  }, [ctr, animate]);

  // Gauge calculations
  const maxCTR = 15;
  const percentage = (animatedCTR / maxCTR) * 100;
  const angle = (percentage / 100) * 180 - 90; // -90 to 90 degrees

  const getGaugeColor = (value) => {
    if (value >= 8) return 'var(--pr-ctr-excellent, #2563eb)';
    if (value >= 5) return 'var(--pr-ctr-high, #3b82f6)';
    if (value >= 3) return 'var(--pr-ctr-medium, #F59E0B)';
    return 'var(--pr-ctr-low, #EF4444)';
  };

  const gaugeColor = getGaugeColor(animatedCTR);

  const containerStyle = {
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    gap: '4px',
  };

  const svgStyle = {
    overflow: 'visible',
  };

  const valueStyle = {
    fontSize: '18px',
    fontWeight: 700,
    color: gaugeColor,
    fontVariantNumeric: 'tabular-nums',
  };

  const labelStyle = {
    fontSize: '11px',
    color: 'var(--pr-text-muted, #9CA3AF)',
    fontWeight: 500,
  };

  return (
    <div style={containerStyle}>
      <svg width="80" height="48" viewBox="0 0 80 48" style={svgStyle}>
        {/* Background arc */}
        <path
          d="M 8 44 A 32 32 0 0 1 72 44"
          fill="none"
          stroke="var(--pr-border, #E5E7EB)"
          strokeWidth="6"
          strokeLinecap="round"
        />
        {/* Colored arc */}
        <path
          d="M 8 44 A 32 32 0 0 1 72 44"
          fill="none"
          stroke={gaugeColor}
          strokeWidth="6"
          strokeLinecap="round"
          strokeDasharray="100.53"
          strokeDashoffset={100.53 - (percentage / 100) * 100.53}
          style={{ transition: 'stroke-dashoffset 0.3s ease, stroke 0.3s ease' }}
        />
        {/* Needle */}
        <line
          x1="40"
          y1="44"
          x2="40"
          y2="20"
          stroke={gaugeColor}
          strokeWidth="2"
          strokeLinecap="round"
          style={{
            transformOrigin: '40px 44px',
            transform: 'rotate(' + angle + 'deg)',
            transition: 'transform 0.5s ease',
          }}
        />
        {/* Center dot */}
        <circle cx="40" cy="44" r="4" fill={gaugeColor} />
      </svg>
      <span style={valueStyle}>~{animatedCTR.toFixed(1)}%</span>
      <span style={labelStyle}>Est. CTR</span>
    </div>
  );
};

/**
 * SERPPreviewPro Component
 */
const SERPPreviewPro = ({
  title = '',
  description = '',
  url = '',
  showCTR = true,
  showCharBars = true,
  device = 'desktop',
  animate = true,
  className = '',
}) => {
  const [previewDevice, setPreviewDevice] = useState(device);

  // Truncation limits
  const limits = useMemo(() => ({
    desktop: { title: 60, description: 160 },
    mobile: { title: 55, description: 120 },
  }), []);

  const currentLimits = limits[previewDevice];
  const estimatedCTR = calculateCTR(title, description);

  // Format URL for display
  const formatUrl = (urlString) => {
    if (!urlString) return 'example.com';
    try {
      const urlObj = new URL(urlString);
      return urlObj.hostname + urlObj.pathname;
    } catch {
      return urlString.replace(/^https?:\/\//, '').replace(/\/$/, '');
    }
  };

  const displayTitle = truncateText(title || 'Your SEO Title Here', currentLimits.title, 'title');
  const displayDesc = truncateText(description || 'Add a compelling meta description to improve your click-through rate in search results.', currentLimits.description, 'description');
  const displayUrl = formatUrl(url);

  const isTitleTruncated = title.length > currentLimits.title;
  const isDescTruncated = description.length > currentLimits.description;

  // Styles
  const containerStyle = {
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  };

  const previewBoxStyle = {
    background: 'white',
    border: '1px solid var(--pr-border, #E5E7EB)',
    borderRadius: '8px',
    padding: '16px',
    fontFamily: 'Arial, sans-serif',
  };

  const deviceToggleStyle = {
    display: 'flex',
    gap: '4px',
    marginBottom: '12px',
  };

  const deviceBtnStyle = (isActive) => ({
    padding: '6px 12px',
    border: '1px solid ' + (isActive ? 'var(--pr-accent, #3b82f6)' : 'var(--pr-border, #E5E7EB)'),
    borderRadius: '6px',
    background: isActive ? 'var(--pr-accent-bg, rgba(49, 162, 76, 0.08))' : 'white',
    color: isActive ? 'var(--pr-accent, #3b82f6)' : 'var(--pr-text-secondary, #6B7280)',
    fontSize: '12px',
    fontWeight: 500,
    cursor: 'pointer',
    transition: 'all 150ms ease',
  });

  const serpTitleStyle = {
    color: '#1A0DAB',
    fontSize: previewDevice === 'mobile' ? '18px' : '20px',
    lineHeight: 1.3,
    marginBottom: '4px',
    cursor: 'pointer',
    textDecoration: 'none',
    display: 'block',
    wordBreak: 'break-word',
  };

  const serpUrlStyle = {
    color: '#2563eb',
    fontSize: '14px',
    marginBottom: '4px',
    display: 'flex',
    alignItems: 'center',
    gap: '4px',
  };

  const serpDescStyle = {
    color: '#4D5156',
    fontSize: '14px',
    lineHeight: 1.58,
    wordBreak: 'break-word',
  };

  const truncatedStyle = {
    color: '#EF4444',
    fontStyle: 'italic',
  };

  const metricsRowStyle = {
    display: 'flex',
    gap: '24px',
    alignItems: 'flex-start',
  };

  const charBarsStyle = {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    gap: '12px',
  };

  return (
    <div className={'pr:serp-preview-pro ' + className} style={containerStyle}>
      {/* SERP Preview Box */}
      <div style={previewBoxStyle}>
        {/* Device Toggle */}
        <div style={deviceToggleStyle}>
          <button
            style={deviceBtnStyle(previewDevice === 'desktop')}
            onClick={() => setPreviewDevice('desktop')}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
              <rect x="2" y="3" width="20" height="14" rx="2" ry="2" />
              <line x1="8" y1="21" x2="16" y2="21" />
              <line x1="12" y1="17" x2="12" y2="21" />
            </svg>
            Desktop
          </button>
          <button
            style={deviceBtnStyle(previewDevice === 'mobile')}
            onClick={() => setPreviewDevice('mobile')}
          >
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" style={{ marginRight: '4px', verticalAlign: 'middle' }}>
              <rect x="5" y="2" width="14" height="20" rx="2" ry="2" />
              <line x1="12" y1="18" x2="12" y2="18" />
            </svg>
            Mobile
          </button>
        </div>

        {/* SERP Result */}
        <div>
          <a href="#" style={serpTitleStyle} onClick={(e) => e.preventDefault()}>
            {displayTitle}
            {isTitleTruncated && <span style={truncatedStyle}> (truncated)</span>}
          </a>
          <div style={serpUrlStyle}>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none">
              <circle cx="12" cy="12" r="10" stroke="#2563eb" strokeWidth="1.5" />
              <path d="M2 12h20M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z" stroke="#2563eb" strokeWidth="1.5" />
            </svg>
            {displayUrl}
          </div>
          <div style={serpDescStyle}>
            {displayDesc}
            {isDescTruncated && <span style={truncatedStyle}> ...</span>}
          </div>
        </div>
      </div>

      {/* Metrics Row */}
      <div style={metricsRowStyle}>
        {/* Character Bars */}
        {showCharBars && (
          <div style={charBarsStyle}>
            <CharacterBar
              current={title.length}
              {...CharacterBarPresets.seoTitle}
              showStatus={true}
              animate={animate}
            />
            <CharacterBar
              current={description.length}
              {...CharacterBarPresets.metaDescription}
              showStatus={true}
              animate={animate}
            />
          </div>
        )}

        {/* CTR Gauge */}
        {showCTR && (
          <CTRGauge ctr={estimatedCTR} animate={animate} />
        )}
      </div>
    </div>
  );
};

export default SERPPreviewPro;
export { CTRGauge, calculateCTR };
