import React from 'react';
import { useTranslation } from '../../i18n/LanguageContext';

const truncate = (value, maxLength = 26) =>
  value.length > maxLength ? `${value.slice(0, maxLength - 1)}…` : value;

export default function GapBarChart({ metrics = [] }) {
  const t = useTranslation();

  const data = [...metrics]
    .sort((left, right) => right.priorityScore - left.priorityScore)
    .slice(0, 8);

  if (!data.length) {
    return (
      <div className="rounded-2xl border border-dashed border-gray-300 dark:border-gray-700 bg-white/70 dark:bg-gray-900/70 p-4 text-sm text-gray-600 dark:text-gray-300">
        {t('gapchart.no_data')}
      </div>
    );
  }

  const width = 760;
  const leftPad = 220;
  const rightPad = 24;
  const rowHeight = 38;
  const topPad = 20;
  const bottomPad = 24;
  const height = topPad + bottomPad + rowHeight * data.length;

  const maxScore = Math.max(...data.map((item) => item.priorityScore), 0.01);
  const chartWidth = width - leftPad - rightPad;

  return (
    <div className="rounded-2xl border border-gray-200 dark:border-gray-800 bg-white dark:bg-gray-900 p-4 shadow-sm h-full flex flex-col">
      <h3 className="text-sm font-semibold text-gray-800 dark:text-gray-100 mb-3">{t('gapchart.title')}</h3>
      <svg viewBox={`0 0 ${width} ${height}`} className="w-full h-auto" role="img" aria-label={t('gapchart.aria')}>
        {data.map((item, index) => {
          const y = topPad + index * rowHeight;
          const barWidth = (item.priorityScore / maxScore) * chartWidth;

          return (
            <g key={item.name}>
              <text
                x={10}
                y={y + 20}
                className="fill-gray-700 dark:fill-gray-200"
                style={{ fontSize: 12, fontWeight: 500 }}
              >
                {truncate(item.name)}
              </text>

              <rect
                x={leftPad}
                y={y + 8}
                width={chartWidth}
                height={16}
                rx={8}
                className="fill-gray-200 dark:fill-gray-800"
              />

              <rect
                x={leftPad}
                y={y + 8}
                width={Math.max(3, barWidth)}
                height={16}
                rx={8}
                className="fill-rose-500"
              />

              <text
                x={leftPad + Math.max(8, barWidth) + 8}
                y={y + 20}
                className="fill-gray-700 dark:fill-gray-300"
                style={{ fontSize: 11, fontWeight: 600 }}
              >
                {item.priorityScore.toFixed(2)}
              </text>
            </g>
          );
        })}
      </svg>
    </div>
  );
}
