import { bucketMetaFor, type ForensicsAttribution } from './forensics-types'
import { formatDurationMs, ratioPercent } from './format'

export interface PhaseBarsProps {
  attribution: ForensicsAttribution[]
}

/** `.twt .trow` — "Where the time went": attribution buckets as relative bars, longest = 100% width. */
export function PhaseBars({ attribution }: PhaseBarsProps) {
  const sorted = [...attribution].sort((a, b) => b.totalMs - a.totalMs)
  const maxMs = sorted[0]?.totalMs ?? 0
  const totalMs = sorted.reduce((sum, row) => sum + row.totalMs, 0)

  return (
    <div>
      {sorted.map((row) => {
        const meta = bucketMetaFor(row.cat)
        const sharePct = totalMs > 0 ? Math.round((row.totalMs / totalMs) * 100) : 0
        return (
          <div key={row.cat} className="grid grid-cols-[130px_1fr_86px] items-center gap-3 py-1 text-[12px]">
            <span className="flex items-center gap-[7px] text-fg-muted">
              <i className="h-[9px] w-[9px] flex-shrink-0 rounded-[3px]" style={{ background: meta.colorVar }} />
              {meta.label}
            </span>
            <div>
              <div
                className="h-[13px] rounded"
                style={{ width: `${ratioPercent(row.totalMs, maxMs)}%`, background: meta.colorVar }}
              />
            </div>
            <span className="text-right text-[11.5px] text-fg-muted">
              {formatDurationMs(row.totalMs)} · {sharePct}%
            </span>
          </div>
        )
      })}
    </div>
  )
}