export interface AmplificationGate {
  runId: number
  computeMin: number
  wallMin: number
}

export interface AmplificationSparkProps {
  repo: string
  gates: AmplificationGate[]
  historyComplete: boolean
  warmedAt: string | null
}

function median(values: number[]): number | null {
  if (values.length === 0) return null

  const sorted = [...values].sort((left, right) => left - right)
  const middle = Math.floor(sorted.length / 2)
  if (sorted.length % 2 === 1) return sorted[middle]!
  return (sorted[middle - 1]! + sorted[middle]!) / 2
}

function validMinutes(value: number): boolean {
  return Number.isFinite(value) && value >= 0
}

function formatMinutes(value: number): string {
  return validMinutes(value) ? `${value.toLocaleString()} minutes` : 'unavailable'
}

function barWidth(value: number, maxMinutes: number): string {
  if (!validMinutes(value) || maxMinutes <= 0) return '0%'
  return `${(value / maxMinutes) * 100}%`
}

function formatMultiplier(value: number): string {
  return Number.isInteger(value) ? String(value) : value.toFixed(1)
}

function HistoryGap({
  historyComplete,
  warmedAt,
}: Pick<AmplificationSparkProps, 'historyComplete' | 'warmedAt'>) {
  let message = 'Amplification history warming up'
  if (!historyComplete) {
    message = warmedAt === null
      ? 'History unavailable — warming up after restart'
      : 'Run history incomplete — warming up'
  }

  return (
    <p role="status" className="rounded-xl border border-border bg-surface p-4 text-sm text-fg-muted">
      {message}
    </p>
  )
}

export function AmplificationSpark({
  repo,
  gates,
  historyComplete,
  warmedAt,
}: AmplificationSparkProps) {
  const visibleGates = gates.slice(0, 10)
  const multiplier = median(
    visibleGates
      .filter(
        (gate) =>
          Number.isFinite(gate.computeMin) &&
          gate.computeMin > 0 &&
          Number.isFinite(gate.wallMin),
      )
      .map((gate) => gate.wallMin / gate.computeMin),
  )
  const maxMinutes = Math.max(
    0,
    ...visibleGates.flatMap((gate) => [gate.computeMin, gate.wallMin]).filter(validMinutes),
  )

  return (
    <section aria-label={`CI amplification for ${repo}`} className="min-w-0">
      <div className="mb-3 flex flex-wrap items-end justify-between gap-2">
        <div>
          <h3 className="text-sm font-bold text-fg">{repo}</h3>
          <p className="text-xs text-fg-muted">Last 10 gated runs</p>
        </div>
        {multiplier !== null && historyComplete && visibleGates.length > 0 ? (
          <p className="text-lg font-bold tabular-nums text-fg">
            wall = {formatMultiplier(multiplier)}× compute
          </p>
        ) : null}
      </div>

      {!historyComplete || visibleGates.length === 0 ? (
        <HistoryGap historyComplete={historyComplete} warmedAt={warmedAt} />
      ) : (
        <>
          {multiplier === null ? (
            <p role="status" className="mb-3 text-xs font-semibold text-warning">
              Multiplier unavailable — no valid compute samples
            </p>
          ) : null}
          <div
            className="mb-2 flex flex-wrap gap-3 text-xs text-fg-muted"
            aria-label="Amplification legend"
          >
            <span className="flex items-center gap-1">
              <i aria-hidden className="h-2 w-2 rounded-sm bg-accent" />Compute
            </span>
            <span className="flex items-center gap-1">
              <i aria-hidden className="h-2 w-2 rounded-sm bg-info" />Wall
            </span>
          </div>
          <ol className="space-y-2" aria-label={`Amplification runs for ${repo}`}>
            {visibleGates.map((gate) => (
              <li
                key={gate.runId}
                data-run-id={gate.runId}
                className="grid grid-cols-[5rem_1fr] items-center gap-3"
              >
                <span className="text-xs tabular-nums text-fg-muted">Run {gate.runId}</span>
                <div className="space-y-1">
                  <div
                    aria-label={`Compute ${formatMinutes(gate.computeMin)}`}
                    className="h-2 rounded-sm bg-accent"
                    style={{ width: barWidth(gate.computeMin, maxMinutes) }}
                  />
                  <div
                    aria-label={`Wall ${formatMinutes(gate.wallMin)}`}
                    className="h-2 rounded-sm bg-info"
                    style={{ width: barWidth(gate.wallMin, maxMinutes) }}
                  />
                </div>
              </li>
            ))}
          </ol>
        </>
      )}
    </section>
  )
}
