/**
 * LatencyBadge — 4-bar cell-signal style indicator for WebSocket RTT.
 *
 * Bar fill thresholds:
 *   4 bars (green)  : < 50 ms   — excellent
 *   3 bars (cyan)   : < 150 ms  — good
 *   2 bars (amber)  : < 400 ms  — fair
 *   1 bar  (red)    : ≥ 400 ms  — poor
 *   0 bars (grey)   : no data   — waiting for first pong
 */

interface Props {
  ms?: number;
  /** Compact variant — bars only, no ms label */
  compact?: boolean;
}

function latencyLevel(ms: number): 0 | 1 | 2 | 3 | 4 {
  if (ms < 50)  return 4;
  if (ms < 150) return 3;
  if (ms < 400) return 2;
  return 1;
}

const LEVEL_COLORS: Record<number, string> = {
  4: '#39ff14',   // neon green
  3: '#00f5ff',   // cyan
  2: '#ffb020',   // amber
  1: '#ff4466',   // red
  0: '#444',      // grey
};

const BAR_HEIGHTS = [5, 8, 11, 14]; // px, bottom-aligned

export default function LatencyBadge({ ms, compact = false }: Props) {
  const level = ms !== undefined ? latencyLevel(ms) : 0;
  const color = LEVEL_COLORS[level];
  const label = ms !== undefined ? `${ms}ms` : '—';

  return (
    <span
      title={ms !== undefined ? `Latency: ${ms} ms` : 'Latency unknown — waiting for ping'}
      style={{
        display: 'inline-flex',
        alignItems: 'flex-end',
        gap: '2px',
        verticalAlign: 'middle',
        lineHeight: 1,
      }}
    >
      {BAR_HEIGHTS.map((h, i) => {
        const filled = (i + 1) <= level;
        return (
          <span
            key={i}
            style={{
              display: 'inline-block',
              width: 3,
              height: h,
              borderRadius: 1,
              background: filled ? color : 'rgba(255,255,255,0.12)',
              transition: 'background 0.4s ease',
            }}
          />
        );
      })}
      {!compact && ms !== undefined && (
        <span
          style={{
            fontSize: '0.7rem',
            fontFamily: 'monospace',
            color,
            marginLeft: 3,
            lineHeight: 1,
            letterSpacing: '-0.02em',
          }}
        >
          {label}
        </span>
      )}
    </span>
  );
}
