import React from 'react';

/**
 * ScoreTrend — compact score-history bar chart (pure SVG, no chart lib).
 *
 * Bars reveal a plot-anchored red→green spectrum: a bar's height is its
 * score, so taller (better) bars reach into the green band while short
 * ones stay red. The latest bar renders at full opacity, the rest dimmed.
 *
 * <ScoreTrend data={[{ score: 64, label: '27 May', title: '64 — 27 May 2026' }, ...]} />
 *
 * Data must be ordered oldest → newest. Renders null with fewer than 2 points.
 */
let trendInstance = 0;

const ScoreTrend = ({ data = [], width = 226, height = 96, className = '' }) => {
  const gradientId = React.useMemo(() => `prorankScoreTrend-${++trendInstance}`, []);

  const points = (Array.isArray(data) ? data : [])
    .filter((d) => d && Number.isFinite(Number(d.score)))
    .slice(-12);

  if (points.length < 2) {
    return null;
  }

  const yLabelWidth = 24;
  const xLabelHeight = 15;
  const plotTop = 9; // headroom so the "100" axis label isn't clipped at the SVG edge
  const plotLeft = 0;
  const plotWidth = width - yLabelWidth - plotLeft;
  const plotHeight = height - plotTop - xLabelHeight;
  const plotBottom = plotTop + plotHeight;

  const slot = plotWidth / points.length;
  const barWidth = Math.max(6, Math.min(18, slot * 0.62));

  return (
    <svg width={width} height={height} viewBox={`0 0 ${width} ${height}`} className={className} role="img" aria-label="score history">
      <defs>
        <linearGradient
          id={gradientId}
          gradientUnits="userSpaceOnUse"
          x1="0"
          y1={plotTop}
          x2="0"
          y2={plotBottom}
        >
          <stop offset="0%" stopColor="#54a45a" />
          <stop offset="28%" stopColor="#9abe45" />
          <stop offset="50%" stopColor="#d9c843" />
          <stop offset="70%" stopColor="#df9d3c" />
          <stop offset="100%" stopColor="#d65e44" />
        </linearGradient>
      </defs>
      {[0, 50, 100].map((tick) => {
        const y = plotBottom - (tick / 100) * plotHeight;
        return (
          <g key={tick}>
            <line x1={plotLeft} y1={y} x2={plotLeft + plotWidth} y2={y} stroke="#eceff3" strokeWidth="1" />
            <text
              x={width}
              y={y}
              textAnchor="end"
              dominantBaseline="middle"
              fontSize="10"
              fill="#94a3b8"
            >
              {tick}
            </text>
          </g>
        );
      })}
      {points.map((point, index) => {
        const score = Math.max(0, Math.min(100, Number(point.score)));
        const barHeight = Math.max(1.5, (score / 100) * plotHeight);
        const x = plotLeft + index * slot + (slot - barWidth) / 2;
        const isLatest = index === points.length - 1;
        return (
          <g key={index}>
            <rect
              x={x}
              y={plotBottom - barHeight}
              width={barWidth}
              height={barHeight}
              rx="2"
              fill={`url(#${gradientId})`}
              opacity={isLatest ? 1 : 0.45}
            >
              {point.title && <title>{point.title}</title>}
            </rect>
          </g>
        );
      })}
      {points.map((point, index) => {
        if (!point.label) return null;
        const isFirst = index === 0;
        const isLast = index === points.length - 1;
        if (!isFirst && !isLast) return null;
        const center = plotLeft + index * slot + slot / 2;
        return (
          <text
            key={`label-${index}`}
            x={isFirst ? Math.max(plotLeft, center - barWidth / 2) : Math.min(plotLeft + plotWidth, center + barWidth / 2)}
            y={height - 3}
            textAnchor={isFirst ? 'start' : 'end'}
            fontSize="10"
            fill="#94a3b8"
          >
            {point.label}
          </text>
        );
      })}
    </svg>
  );
};

export default ScoreTrend;
