import { Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import type { ScoredStrategy } from '@/lib/engine/optimize'

/**
 * The strategy trade-off, plotted (§55).
 *
 * Cost on one axis, risk removed on the other, bubble size for customers affected. The
 * table beside it has the same numbers, but the plot answers a question the table cannot:
 * *why this one* — because the recommended strategy is the point furthest up and to the
 * left, and an operator can see that in a second without comparing nine columns.
 */
const W = 420
const H = 260
const PAD = 42

export async function StrategyMatrix({
  strategies,
  className,
}: {
  strategies: ScoredStrategy[]
  className?: string
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'

  const points = strategies.filter((strategy) => strategy.kind !== 'none')
  if (points.length === 0) return null

  const maxCost = Math.max(...points.map((strategy) => strategy.costSar), 1)
  const maxReduction = Math.max(
    ...points.map((strategy) => strategy.evaluation.riskReduction),
    1,
  )
  const maxImpact = Math.max(...points.map((strategy) => strategy.customerImpact), 1)

  const x = (cost: number) => PAD + (cost / maxCost) * (W - PAD * 1.5)
  const y = (reduction: number) => H - PAD - (reduction / maxReduction) * (H - PAD * 1.6)

  return (
    <Panel className={className}>
      <PanelHeader title={t('strategyMatrix.title')} subtitle={t('strategyMatrix.hint')} />
      <PanelBody className="pt-0">
        <div className="overflow-x-auto">
          <svg viewBox={`0 0 ${W} ${H}`} className="h-auto w-full min-w-[22rem]" role="img" aria-label={t('strategyMatrix.title')}>
            <line x1={PAD} y1={H - PAD} x2={W - PAD * 0.5} y2={H - PAD} stroke="currentColor" className="text-border-strong" strokeWidth="1" />
            <line x1={PAD} y1={PAD * 0.6} x2={PAD} y2={H - PAD} stroke="currentColor" className="text-border-strong" strokeWidth="1" />

            <text x={W / 2} y={H - 10} textAnchor="middle" className="fill-current text-[9px] text-text-faint">
              {t('strategyMatrix.cost')}
            </text>
            <text
              x={12}
              y={H / 2}
              textAnchor="middle"
              transform={`rotate(-90 12 ${H / 2})`}
              className="fill-current text-[9px] text-text-faint"
            >
              {t('strategyMatrix.reduction')}
            </text>

            {points.map((strategy) => {
              const cx = x(strategy.costSar)
              const cy = y(strategy.evaluation.riskReduction)
              const r = 6 + (strategy.customerImpact / maxImpact) * 14
              return (
                <g key={strategy.key}>
                  <circle
                    cx={cx}
                    cy={cy}
                    r={r}
                    fill={strategy.isRecommended ? '#24d07f' : '#38bdf8'}
                    fillOpacity={strategy.isRecommended ? 0.32 : 0.16}
                    stroke={strategy.isRecommended ? '#24d07f' : '#38bdf8'}
                    strokeWidth={strategy.isRecommended ? 2 : 1}
                  />
                  <text
                    x={cx}
                    y={cy - r - 5}
                    textAnchor="middle"
                    className="fill-current text-[8px] text-text-muted"
                  >
                    {(ar ? strategy.labelAr : strategy.label).slice(0, 22)}
                  </text>
                </g>
              )
            })}
          </svg>
        </div>

        <ul className="mt-3 space-y-1 border-t border-border/60 pt-3">
          {points.map((strategy) => (
            <li key={strategy.key} className="flex flex-wrap items-baseline justify-between gap-2 text-[11px]">
              <span className={strategy.isRecommended ? 'font-medium text-brand' : 'text-text-muted'}>
                {ar ? strategy.labelAr : strategy.label}
              </span>
              <span className="tnum text-text-faint">
                {formatNumber(locale, strategy.costSar)} {t('common.sar')} ·{' '}
                −{formatNumber(locale, strategy.evaluation.riskReduction, { maximumFractionDigits: 1 })} ·{' '}
                {formatNumber(locale, strategy.customerImpact)} {t('common.customers')}
              </span>
            </li>
          ))}
        </ul>
      </PanelBody>
    </Panel>
  )
}
