import { ratioPercent } from './format'

/** Structural mirror of systray adapter's `AccountLimitView` (collector/src/adapters/systray.ts). */
export interface LimitMeterAccount {
  slug: string
  provider?: 'codex' | 'claude'
  label?: string
  percent: number | null
  status: string
  capEtaMinutes: number | null
}

export interface LimitMeterProps {
  account: LimitMeterAccount
  /** Percent at/above which the meter switches to warn styling. */
  warnAt?: number
  /** Percent at/above which the meter switches to critical styling. */
  critAt?: number
}

const DEFAULT_WARN_AT = 75
const DEFAULT_CRIT_AT = 90

/** `.lim`/`.lbar` — one account's usage percent + remaining-time bar. */
export function LimitMeter({ account, warnAt = DEFAULT_WARN_AT, critAt = DEFAULT_CRIT_AT }: LimitMeterProps) {
  const { percent, capEtaMinutes, status } = account
  const broken = percent === null && status !== 'ok'
  const tier = broken
    ? 'crit'
    : percent === null
      ? 'ok'
      : percent >= critAt
        ? 'crit'
        : percent >= warnAt
          ? 'warn'
          : 'ok'
  const textClass = tier === 'crit' ? 'text-danger' : tier === 'warn' ? 'text-warning' : 'text-success'
  const fillClass = tier === 'crit' ? 'bg-danger' : tier === 'warn' ? 'bg-warning' : 'bg-success'
  const summary =
    percent === null
      ? broken
        ? status
        : '—'
      : capEtaMinutes === null
        ? `${Math.round(percent)}%`
        : `${Math.round(percent)}% · ~${Math.round(capEtaMinutes)}m left`

  const displayName = account.label ?? account.slug

  return (
    <div className="mb-2.5">
      <div className="mb-1 flex justify-between text-[12px]">
        <b className="font-medium">{displayName}</b>
        <span className={textClass}>{summary}</span>
      </div>
      <div className="h-1.5 rounded-[3px] bg-[var(--mod-color-track)]">
        <i
          className={`block h-full rounded-[3px] ${fillClass}`}
          style={{ width: `${ratioPercent(percent ?? 0, 100)}%` }}
        />
      </div>
    </div>
  )
}
