import React from 'react';
import { useShadeRuntimeTheme } from '../../ShadeRuntimeProvider.js';

export interface SpeedReadoutProps {
  bytesPerSecond: number;
  className?: string;
  style?: React.CSSProperties;
}

export function SpeedReadout({
  bytesPerSecond,
  className,
  style,
}: SpeedReadoutProps): React.ReactElement {
  const theme = useShadeRuntimeTheme();
  return (
    <span
      className={className}
      style={{
        fontFamily: theme.fontMono,
        fontSize: 12,
        color: theme.textMuted,
        ...style,
      }}
    >
      {formatBytesPerSecond(bytesPerSecond)}
    </span>
  );
}

export function formatBytesPerSecond(bps: number): string {
  if (!Number.isFinite(bps) || bps <= 0) return '— B/s';
  if (bps < 1024) return `${bps.toFixed(0)} B/s`;
  if (bps < 1024 * 1024) return `${(bps / 1024).toFixed(1)} KB/s`;
  if (bps < 1024 * 1024 * 1024) return `${(bps / (1024 * 1024)).toFixed(2)} MB/s`;
  return `${(bps / (1024 * 1024 * 1024)).toFixed(2)} GB/s`;
}
