import { Meter, Panel, PanelBody, PanelHeader, Badge } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import type { DecisionConfidence } from '@/lib/engine/quality'

/**
 * The four confidences behind one decision (§15).
 *
 * Shown separately rather than averaged into a headline, because they fail differently:
 * a confident model reading thin data is a specific problem, and the operator needs to
 * see which of the four is the weak one.
 */
const KEYS = ['recommendation', 'data', 'prediction', 'simulation'] as const

function stateFor(value: number) {
  if (value >= 80) return 'normal' as const
  if (value >= 62) return 'watch' as const
  if (value >= 45) return 'warning' as const
  return 'critical' as const
}

export async function ConfidencePanel({
  confidence,
  warning,
  className,
}: {
  confidence: DecisionConfidence
  warning?: string | null
  className?: string
}) {
  const { t, locale } = await getI18n()

  return (
    <Panel className={className}>
      <PanelHeader
        title={t('confidence.title')}
        subtitle={t('confidence.cappedHint')}
        action={
          <Badge tone={confidence.isLowData ? 'accent' : 'muted'}>
            {t(`confidence.band.${confidence.band}`)}
          </Badge>
        }
      />
      <PanelBody className="space-y-3 pt-0">
        <div className="flex items-baseline gap-2 border-b border-border/70 pb-3">
          <p className="tnum text-3xl font-semibold tracking-tight text-text">
            {formatNumber(locale, confidence.overall, { maximumFractionDigits: 0 })}%
          </p>
          <p className="text-xs text-text-muted">{t('confidence.overall')}</p>
        </div>

        {KEYS.map((key) => (
          <Meter
            key={key}
            value={confidence[key]}
            state={stateFor(confidence[key])}
            label={t(`confidence.${key}`)}
            showValue
          />
        ))}

        {confidence.isLowData ? (
          <p className="rounded-lg border border-critical/30 bg-critical/8 px-3 py-2 text-[11px] leading-relaxed text-critical">
            {t('confidence.lowData')}
            {warning ? ` — ${warning}` : ''}
          </p>
        ) : warning ? (
          <p className="text-[11px] leading-relaxed text-text-muted">{warning}</p>
        ) : null}
      </PanelBody>
    </Panel>
  )
}
