import { cn } from '@/lib/utils';
import { compactNumber, percent } from '@/lib/api';

/**
 * How much of a capacity block is sold, how much is merely held, and how much
 * is still sellable.
 *
 * Sold and held are drawn as separate segments because a full-looking bar made
 * mostly of unconverted holds is a lie a seller would act on — held hours are
 * a claim someone can walk away from, sold hours are revenue.
 *
 * The track is `bg-surface-2`. One of the two copies of this bar had drifted to
 * `bg-surface`, which inside the allocation sheet's `bg-surface-2` panel
 * measured 1.02:1 against its own container: an invisible track, at the exact
 * moment someone commits GPU-hours to a customer.
 */
export function UtilisationBar({
  sold,
  held,
  total,
  label,
  className,
}: {
  /** GPU-hours sold. */
  sold: number;
  /** GPU-hours held but not yet sold. */
  held: number;
  /** GPU-hours committed in total. Zero renders an empty track, not a full one. */
  total: number;
  /** What the bar is about, e.g. the block's name. Prefixes the spoken label. */
  label?: string;
  className?: string;
}) {
  const soldPct = total > 0 ? sold / total : 0;
  const heldPct = total > 0 ? held / total : 0;
  const available = Math.max(0, total - sold - held);

  // Held is clamped against sold so a book that has over-held a block renders a
  // full bar rather than a segment running past the end of its track.
  const soldWidth = Math.min(100, soldPct * 100);
  const heldWidth = Math.max(0, Math.min(100 - soldWidth, heldPct * 100));

  const spoken = `${percent(soldPct)} sold, ${percent(heldPct)} held, ${compactNumber(available)} GPU-hours sellable`;

  return (
    <div
      className={cn('flex h-2 min-w-0 overflow-hidden rounded-full bg-surface-2', className)}
      role="img"
      aria-label={label ? `${label}: ${spoken}` : spoken}
    >
      <div className="bg-primary" style={{ width: `${soldWidth}%` }} />
      <div className="bg-primary/35" style={{ width: `${heldWidth}%` }} />
    </div>
  );
}
