"use client";

import type { ReasonCode } from "@/lib/api-types";
import { getReasonLabel } from "@/lib/scoring-reasons";
import type { WizardLocale } from "@/lib/i18n/wizard-labels";

interface Props {
  factors: ReasonCode[];
  locale?: WizardLocale;
  maxItems?: number;
  className?: string;
}

export default function ShapFactorsChart({
  factors,
  locale = "uz",
  maxItems = 5,
  className = "",
}: Props) {
  const items = factors.slice(0, maxItems);
  if (items.length === 0) return null;

  const maxAbs = Math.max(
    ...items.map((f) => Math.abs(f.contribution ?? 0)),
    1,
  );

  return (
    <div className={`space-y-2.5 ${className}`} role="list" aria-label="Score factors">
      {items.map((factor, i) => {
        const value = factor.contribution ?? 0;
        const widthPct = (Math.abs(value) / maxAbs) * 100;
        const isPositive = factor.direction === "positive" || value >= 0;
        const label = getReasonLabel(factor.code, locale) || factor.feature || factor.code;

        return (
          <div key={factor.code ?? i} role="listitem" className="space-y-1">
            <div className="flex items-center justify-between gap-2">
              <span className="font-inter text-xs text-[#042718]/70 text-left line-clamp-2">
                {label}
              </span>
              <span
                className={`font-inter text-xs font-medium shrink-0 ${
                  isPositive ? "text-[#198F38]" : "text-red-500"
                }`}
              >
                {isPositive && value > 0 ? "+" : ""}
                {value.toFixed(1)}
              </span>
            </div>
            <div className="h-2 rounded-full bg-[#042718]/5 overflow-hidden">
              <div
                className={`h-full rounded-full transition-all duration-500 ${
                  isPositive ? "bg-[#198F38]" : "bg-red-400"
                }`}
                style={{ width: `${widthPct}%` }}
                aria-hidden="true"
              />
            </div>
          </div>
        );
      })}
    </div>
  );
}
