'use client';

import { useState } from 'react';

/** Single-series column chart with hover/focus tooltip. Colour: one validated hue; values in text tokens. */
export function BarChart({ data, label, unit = '' }: { data: { x: string; y: number }[]; label: string; unit?: string }) {
  const [hover, setHover] = useState<number | null>(null);
  if (!data.length) return <p className="py-10 text-center text-sm text-muted">No data for this period yet.</p>;
  const max = Math.max(1, ...data.map((d) => d.y));
  // Round the axis up to a friendly number so gridlines land on integers
  const step = Math.max(1, Math.ceil(max / 4));
  const top = step * 4;
  const ticks = [0, step, step * 2, step * 3, top];
  const w = 100 / data.length;
  const every = Math.ceil(data.length / 6);
  return (
    <figure>
      <figcaption className="sr-only">{label}</figcaption>
      <div className="relative h-48 pl-8">
        {ticks.map((t) => (
          <div key={t} className="absolute left-8 right-0 border-t border-dashed border-rule" style={{ bottom: `${(t / top) * 100}%` }}>
            <span className="num absolute -left-8 -top-2 w-6 text-right text-[10px] text-muted">{t}</span>
          </div>
        ))}
        <div className="relative flex h-full items-end" onMouseLeave={() => setHover(null)}>
          {data.map((d, i) => (
            <div
              key={d.x}
              tabIndex={0}
              aria-label={`${d.x}: ${d.y}${unit}`}
              className="relative flex h-full items-end justify-center outline-none"
              style={{ width: `${w}%` }}
              onMouseEnter={() => setHover(i)}
              onFocus={() => setHover(i)}
              onBlur={() => setHover(null)}
            >
              <div
                className="w-[68%] max-w-6 rounded-t-[3px] transition-opacity"
                style={{ height: `${(d.y / top) * 100}%`, minHeight: d.y ? 2 : 0, background: 'var(--g-expertise)', opacity: hover == null || hover === i ? 1 : 0.45 }}
              />
              {hover === i && (
                <div className="pointer-events-none absolute bottom-full z-10 mb-1.5 whitespace-nowrap rounded-md border border-rule bg-surface px-2 py-1 text-xs shadow-md">
                  <span className="text-muted">{d.x}</span> <span className="num font-semibold">{d.y}{unit}</span>
                </div>
              )}
            </div>
          ))}
        </div>
      </div>
      <div className="mt-1.5 flex h-4 pl-8 text-[10px] text-muted">
        {data.map((d, i) => (
          <span key={d.x} className="num relative" style={{ width: `${w}%` }}>
            {i % every === 0 && <span className="absolute left-1/2 -translate-x-1/2 whitespace-nowrap">{d.x}</span>}
          </span>
        ))}
      </div>
      <details className="mt-3 text-xs text-muted">
        <summary className="inline-flex cursor-pointer items-center gap-1 rounded px-1 hover:text-ink">Show as table</summary>
        <div className="mt-2 max-h-56 overflow-y-auto rounded-lg border border-rule">
          <table className="tbl">
            <tbody>
              {data.map((d) => (
                <tr key={d.x}>
                  <td>{d.x}</td>
                  <td className="num text-right">
                    {d.y}
                    {unit}
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </details>
    </figure>
  );
}
