import type { ScoreBreakdown } from '../../lib/types';

interface DimensionBreakdownPanelProps {
  breakdown: ScoreBreakdown;
}

function formatWeight(weight: number): string {
  return `${Math.round(weight * 100)}%`;
}

function formatRawValue(value: number | string | null): string {
  if (value === null) return '—';
  if (typeof value === 'string') return value;
  return Number.isInteger(value) ? value.toString() : value.toFixed(2);
}

export function DimensionBreakdownPanel({ breakdown }: DimensionBreakdownPanelProps) {
  return (
    <div className="space-y-3">
      {/* Sub-score rows */}
      {breakdown.sub_scores.length > 0 && (
        <div className="space-y-1.5">
          {breakdown.sub_scores.map((sub) => (
            <div
              key={sub.name}
              data-testid="sub-score-row"
              className="flex items-center justify-between gap-2 text-sm"
            >
              <span className="text-gray-400 min-w-0 truncate">{sub.name}</span>
              <div className="flex items-center gap-2 shrink-0">
                <span className="text-gray-200 tabular-nums">{sub.score.toFixed(1)}</span>
                <span className="rounded bg-white/10 px-1.5 py-0.5 text-[10px] font-medium text-gray-400">
                  {formatWeight(sub.weight)}
                </span>
                <span className="text-gray-500 text-xs tabular-nums w-16 text-right">
                  {formatRawValue(sub.raw_value)}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}

      {/* Formula description */}
      {breakdown.formula && (
        <p className="text-xs text-gray-500 leading-relaxed">{breakdown.formula}</p>
      )}

      {/* Unavailable sub-scores */}
      {breakdown.unavailable.length > 0 && (
        <div className="space-y-1">
          {breakdown.unavailable.map((item) => (
            <div
              key={item.name}
              data-testid="unavailable-row"
              className="flex items-center justify-between text-sm"
            >
              <span className="text-gray-600">{item.name}</span>
              <span className="text-gray-600 text-xs italic">{item.reason}</span>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
