import { useMemo } from 'react'
import type { RoleGroup, Take } from '@/types'
import { loudFrac } from '@/lib/format'

interface Props {
  take: Take
  roleGroups: RoleGroup[]
  currentTime: number
  activeDb: number
}

/**
 * The orbit-group rail: five labelled lanes (role families), showing the orbits
 * active in THIS take, lit by their RMS at the playhead. Per-track, grouped by
 * measured register. Color reinforces label + glyph + lane (never hue alone).
 */
export function OrbitRail({ take, roleGroups, currentTime, activeDb }: Props) {
  const bin = Math.max(0, Math.floor(currentTime / take.binS))
  const byGroup = useMemo(() => {
    const m: Record<string, Take['orbits']> = {}
    for (const o of take.orbits) (m[o.group] ??= []).push(o)
    return m
  }, [take])

  return (
    <div className="flex flex-col gap-px overflow-hidden rounded-md border border-hairline">
      {roleGroups.map((g) => {
        const orbits = byGroup[g.key] ?? []
        const anyLive = orbits.some((o) => (o.activity[bin] ?? -240) > activeDb)
        return (
          <div key={g.key} className="flex items-stretch gap-2 bg-raised px-2 py-1.5">
            <div
              className="flex w-20 shrink-0 items-center gap-1.5 text-xs font-medium"
              style={{ color: anyLive ? g.color : 'var(--color-ink-faint)' }}
            >
              <span aria-hidden className="text-sm leading-none">{g.glyph}</span>
              <span>{g.label}</span>
            </div>
            <div className="flex min-w-0 flex-wrap items-center gap-1.5">
              {orbits.length === 0 && (
                <span className="text-xs text-ink-faint/60">—</span>
              )}
              {orbits.map((o) => {
                const db = o.activity[bin] ?? -240
                const live = db > activeDb
                const frac = loudFrac(db)
                return (
                  <span
                    key={o.orbit}
                    title={`orbit-${o.orbit} · ${o.label} · ${isFinite(db) ? db.toFixed(0) : '−∞'} dB`}
                    className="relative flex items-center gap-1 overflow-hidden rounded-full
                               border px-2 py-0.5 font-mono text-[11px] tnum transition-colors"
                    style={{
                      borderColor: live ? g.color : 'var(--color-hairline)',
                      color: live ? g.color : 'var(--color-ink-faint)',
                      background: live ? `${g.color}1a` : 'transparent',
                    }}
                  >
                    {/* level fill — reinforces loudness without relying on hue alone */}
                    {live && (
                      <span
                        aria-hidden
                        className="absolute inset-y-0 left-0"
                        style={{ width: `${frac * 100}%`, background: `${g.color}14` }}
                      />
                    )}
                    <span className="relative">{o.label}</span>
                    <span className="relative opacity-60">·{o.orbit}</span>
                  </span>
                )
              })}
            </div>
          </div>
        )
      })}
    </div>
  )
}
