'use client';

interface GaugeBarProps {
  label: React.ReactNode;
  value: number;
  max: number;
  color: string;
  tooltip?: string;
}

function formatValue(value: number, max: number): string {
  if (max > 1000) {
    // Fortune etc. — thousands separator, no decimals
    return Math.round(value).toLocaleString('fr-FR');
  }
  return String(Math.round(value));
}

export function GaugeBar({ label, value, max, color, tooltip }: GaugeBarProps) {
  const percent = Math.min(100, Math.max(0, (value / max) * 100));

  // Dynamic color based on threshold
  let fillColor = color;
  if (percent > 80) fillColor = '#ef4444';
  else if (percent > 60) fillColor = '#f97316';

  return (
    <div
      className="grid group relative cursor-default select-none"
      style={{ justifyItems: 'center', gap: '3px', minWidth: '58px' }}
      title={tooltip}
    >
      <span className="leading-none flex items-center justify-center" style={{ height: '16px' }} aria-hidden>
        {label}
      </span>
      <div
        className="relative overflow-hidden"
        style={{
          width: '58px',
          height: '4px',
          borderRadius: '2px',
          background: 'linear-gradient(180deg, rgba(0,0,0,0.5), var(--bg-tertiary))',
          border: '1px solid var(--border-dark)',
          boxShadow: 'inset 0 1px 1px rgba(0,0,0,0.55)',
        }}
      >
        <div
          className="absolute inset-y-0 left-0 transition-all duration-500"
          style={{
            width: `${percent}%`,
            borderRadius: '2px',
            background: `linear-gradient(90deg, ${fillColor}66, ${fillColor})`,
            boxShadow: `0 0 4px ${fillColor}66`,
          }}
        />
      </div>
      <span
        className="leading-none tabular-nums"
        style={{
          fontFamily: 'var(--font-subtitle)',
          fontSize: '11px',
          fontWeight: 700,
          letterSpacing: '0.04em',
          color: fillColor,
        }}
      >
        {formatValue(value, max)}
      </span>

      {/* Tooltip */}
      {tooltip && (
        <div
          className="absolute top-full left-1/2 -translate-x-1/2 mt-2 px-2 py-1 rounded text-[10px] whitespace-nowrap opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-50"
          style={{
            background: 'var(--bg-panel)',
            color: 'var(--text-primary)',
            border: '1px solid var(--border-dark)',
          }}
        >
          {tooltip}: {max > 1000 ? value.toLocaleString('fr-FR') : value}/{max > 1000 ? '∞' : max}
        </div>
      )}
    </div>
  );
}
