import { Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'
import type { RiskFactor } from '@/lib/engine/risk'

/**
 * The decision lens (§45).
 *
 * What the platform is weighting when it looks at this asset, as shares of one hundred.
 * The bar is deliberately a single stacked strip rather than a chart: the question is
 * "what is driving this", and a strip answers it in one glance where six separate bars
 * make the reader do the addition.
 */
const TONE = ['bg-critical', 'bg-warning', 'bg-watch', 'bg-info', 'bg-accent', 'bg-brand']

export async function DecisionLens({
  factors,
  className,
}: {
  factors: RiskFactor[]
  className?: string
}) {
  const { t, locale } = await getI18n()

  const total = factors.reduce((sum, factor) => sum + Math.max(0, factor.contribution), 0)
  if (total <= 0) return null

  const shares = factors
    .map((factor) => ({ ...factor, share: (Math.max(0, factor.contribution) / total) * 100 }))
    .sort((a, b) => b.share - a.share)

  return (
    <Panel className={className}>
      <PanelHeader title={t('decisionLens.title')} subtitle={t('decisionLens.hint')} />
      <PanelBody className="space-y-3 pt-0">
        <div className="flex h-3 w-full overflow-hidden rounded-full" aria-hidden>
          {shares.map((factor, index) => (
            <div
              key={factor.key}
              className={cn(TONE[index % TONE.length])}
              style={{ width: `${factor.share}%` }}
            />
          ))}
        </div>

        <ul className="space-y-1.5">
          {shares.map((factor, index) => (
            <li key={factor.key} className="flex items-baseline justify-between gap-3 text-[11px]">
              <span className="flex items-center gap-2 text-text-muted">
                <span aria-hidden className={cn('size-2 rounded-sm', TONE[index % TONE.length])} />
                {t(`riskFactor.${factor.key}`)}
              </span>
              <span className="tnum font-medium text-text">
                {formatNumber(locale, factor.share, { maximumFractionDigits: 0 })}%
              </span>
            </li>
          ))}
        </ul>
      </PanelBody>
    </Panel>
  )
}
