import './GaugeRing.css';

interface GaugeRingProps {
  value: number;
  max?: number;
  label: string;
  sublabel?: string;
  color?: string;
  size?: number;
}

export default function GaugeRing({
  value,
  max = 100,
  label,
  sublabel,
  color = 'var(--neon-cyan)',
  size = 100,
}: GaugeRingProps) {
  const clampedValue = Math.min(max, Math.max(0, value));
  const pct = max > 0 ? Math.min(100, Math.max(0, (value / max) * 100)) : 0;
  const circumference = 2 * Math.PI * 42;
  const offset = circumference - (pct / 100) * circumference;

  return (
    <div className="gauge-ring" style={{ width: size, height: size }}>
      <svg viewBox="0 0 100 100" className="gauge-ring-svg">
        <defs>
          <linearGradient id={`gauge-grad-${label.replace(/\s/g, '')}`} x1="0%" y1="0%" x2="100%" y2="100%">
            <stop offset="0%" stopColor={color} stopOpacity="1" />
            <stop offset="100%" stopColor="var(--brass)" stopOpacity="0.8" />
          </linearGradient>
          <filter id="gauge-glow">
            <feGaussianBlur stdDeviation="2" result="blur" />
            <feMerge>
              <feMergeNode in="blur" />
              <feMergeNode in="SourceGraphic" />
            </feMerge>
          </filter>
        </defs>
        <circle className="gauge-ring-track" cx="50" cy="50" r="42" />
        <circle
          className="gauge-ring-fill"
          cx="50"
          cy="50"
          r="42"
          stroke={`url(#gauge-grad-${label.replace(/\s/g, '')})`}
          strokeDasharray={circumference}
          strokeDashoffset={offset}
          filter="url(#gauge-glow)"
        />
      </svg>
      <div className="gauge-ring-center">
        <span className="gauge-ring-value font-tech">{formatValue(clampedValue, max)}</span>
        <span className="gauge-ring-label">{label}</span>
        {sublabel && <span className="gauge-ring-sub">{sublabel}</span>}
      </div>
    </div>
  );
}

function formatValue(v: number, max: number): string {
  if (max <= 100 && max > 1) return `${v.toFixed(0)}%`;
  if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
  if (v >= 1_000) return `${(v / 1_000).toFixed(1)}K`;
  return v.toFixed(0);
}
