/**
 * ProRank SEO - ProgressRing Component
 *
 * Animated SVG progress ring with smooth fill animation
 * Supports custom colors, sizes, and score-based gradients
 *
 * @package ProRank\SEO
 */

import { useState, useEffect, useRef } from '@wordpress/element';

/**
 * Get score color based on value
 */
const getScoreColor = (score) => {
  if (score >= 80) return 'var(--pr-score-excellent, #3b82f6)';
  if (score >= 60) return 'var(--pr-score-good, #3b82f6)';
  if (score >= 40) return 'var(--pr-score-average, #F59E0B)';
  return 'var(--pr-score-poor, #EF4444)';
};

/**
 * Get score glow color based on value
 */
const getScoreGlow = (score) => {
  if (score >= 80) return 'var(--pr-score-glow-excellent, rgba(16, 185, 129, 0.35))';
  if (score >= 60) return 'var(--pr-score-glow-good, rgba(49, 162, 76, 0.35))';
  if (score >= 40) return 'var(--pr-score-glow-average, rgba(245, 158, 11, 0.35))';
  return 'var(--pr-score-glow-poor, rgba(239, 68, 68, 0.35))';
};

/**
 * ProgressRing Component
 */
const ProgressRing = ({
  value = 0,
  size = 120,
  strokeWidth = 8,
  color,
  bgColor = 'var(--pr-ring-bg, #E5E7EB)',
  animate = true,
  animationDelay = 0,
  showGlow = true,
  showValue = true,
  label,
  onClick,
  className = '',
}) => {
  const [animatedValue, setAnimatedValue] = useState(animate ? 0 : value);
  const [isAnimating, setIsAnimating] = useState(false);
  const ringRef = useRef(null);
  const prevValueRef = useRef(value);

  // Calculate ring dimensions
  const radius = (size - strokeWidth) / 2;
  const circumference = 2 * Math.PI * radius;
  const center = size / 2;

  // Determine color based on score or custom color
  const ringColor = color || getScoreColor(value);
  const glowColor = getScoreGlow(value);

  // Calculate stroke dashoffset
  const normalizedValue = Math.min(100, Math.max(0, animatedValue));
  const strokeDashoffset = circumference - (normalizedValue / 100) * circumference;

  // Animate value changes
  useEffect(() => {
    if (!animate) {
      setAnimatedValue(value);
      return;
    }

    const startValue = prevValueRef.current;
    const endValue = value;
    const duration = 1200;
    const startTime = Date.now() + animationDelay;

    const animateValue = () => {
      const now = Date.now();
      if (now < startTime) {
        requestAnimationFrame(animateValue);
        return;
      }

      const elapsed = now - startTime;
      const progress = Math.min(elapsed / duration, 1);
      const eased = 1 - Math.pow(1 - progress, 3);
      const currentValue = startValue + (endValue - startValue) * eased;
      setAnimatedValue(currentValue);

      if (progress < 1) {
        setIsAnimating(true);
        requestAnimationFrame(animateValue);
      } else {
        setIsAnimating(false);
        prevValueRef.current = value;
      }
    };

    requestAnimationFrame(animateValue);
  }, [value, animate, animationDelay]);

  const shouldPulse = showGlow && value > prevValueRef.current + 5;

  const containerStyle = {
    position: 'relative',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    width: size,
    height: size,
    cursor: onClick ? 'pointer' : 'default',
  };

  const svgStyle = {
    transform: 'rotate(-90deg)',
    filter: showGlow && value >= 60 ? 'drop-shadow(0 0 8px ' + glowColor + ')' : 'none',
  };

  const labelStyle = {
    position: 'absolute',
    top: '50%',
    left: '50%',
    transform: 'translate(-50%, -50%)',
    textAlign: 'center',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  };

  const valueStyle = {
    color: ringColor,
    fontSize: size * 0.22,
    fontWeight: 700,
    lineHeight: 1,
    fontVariantNumeric: 'tabular-nums',
  };

  const captionStyle = {
    color: 'var(--pr-text-muted, #9CA3AF)',
    marginTop: 2,
    fontWeight: 500,
    fontSize: size * 0.1,
  };

  return (
    <div
      className={'pr:ring-container ' + className}
      onClick={onClick}
      style={containerStyle}
    >
      <svg
        ref={ringRef}
        width={size}
        height={size}
        style={svgStyle}
      >
        <circle
          cx={center}
          cy={center}
          r={radius}
          strokeWidth={strokeWidth}
          stroke={bgColor}
          fill="none"
        />
        <circle
          cx={center}
          cy={center}
          r={radius}
          strokeWidth={strokeWidth}
          stroke={ringColor}
          fill="none"
          strokeLinecap="round"
          strokeDasharray={circumference}
          strokeDashoffset={strokeDashoffset}
          style={{
            transition: animate ? 'none' : 'stroke-dashoffset 0.3s ease',
            animation: shouldPulse ? 'pr:ring-pulse 0.6s ease' : 'none',
          }}
        />
      </svg>

      {showValue && (
        <div style={labelStyle}>
          <span style={valueStyle}>
            {Math.round(animatedValue)}
          </span>
          {label && (
            <span style={captionStyle}>
              {label}
            </span>
          )}
        </div>
      )}
    </div>
  );
};

export default ProgressRing;
export { getScoreColor, getScoreGlow };
