import type { LoudTrace, MasterInfo } from '@/types'
import { fmtDb, loudFrac } from '@/lib/format'

interface Props {
  master: MasterInfo
  loud: LoudTrace
  currentTime: number
}

function Stat({ label, value, warn }: { label: string; value: string; warn?: boolean }) {
  return (
    <div className="flex flex-col">
      <span className="text-[10px] uppercase tracking-wide text-ink-faint">{label}</span>
      <span className={`font-mono text-sm tnum ${warn ? 'text-blocked' : 'text-ink'}`}>{value}</span>
    </div>
  )
}

/** Loudness instrument: live momentary-LUFS bar (with integrated target mark) + I/LRA/TP. */
export function Meter({ master, loud, currentTime }: Props) {
  const i = Math.min(loud.trace.length - 1, Math.max(0, Math.floor(currentTime / loud.stepS)))
  const m = loud.trace[i] ?? -70
  const frac = loudFrac(m)
  const targetFrac = master.I != null ? loudFrac(master.I) : null
  const tpWarn = master.TP != null && master.TP > -1

  return (
    <div className="flex items-center gap-4">
      {/* momentary meter */}
      <div className="min-w-0 flex-1">
        <div className="mb-1 flex items-baseline justify-between">
          <span className="text-[10px] uppercase tracking-wide text-ink-faint">Momentary</span>
          <span className="font-mono text-xs text-ink-muted tnum">{fmtDb(m, ' LUFS')}</span>
        </div>
        <div className="relative h-2 overflow-hidden rounded-full bg-overlay">
          <div
            className="h-full rounded-full bg-ink transition-[width] duration-75"
            style={{ width: `${frac * 100}%` }}
          />
          {targetFrac != null && (
            <div
              className="absolute inset-y-0 w-px bg-magenta"
              style={{ left: `${targetFrac * 100}%` }}
              title={`integrated ${fmtDb(master.I)} LUFS`}
            />
          )}
        </div>
      </div>
      <div className="flex shrink-0 gap-4">
        <Stat label="Integrated" value={fmtDb(master.I, ' LUFS')} />
        <Stat label="LRA" value={fmtDb(master.LRA, ' LU')} />
        <Stat label="True pk" value={fmtDb(master.TP, ' dB')} warn={tpWarn} />
      </div>
    </div>
  )
}
