import {
  BAND_STYLE,
  bandTicks,
  classifyMetric,
  meterFraction,
} from '../../lib/metricBands';

/**
 * One labelled metric.
 *
 * Optionally carries a quality meter: pass `metric` (a key in METRIC_BANDS) and
 * the numeric `raw` value. The meter is the answer to "2.72 — is that good?" —
 * a track showing where the value sits, ticks at the band edges, and the band
 * word. Colour never travels alone; the word is always rendered beside it.
 *
 * Every tile is the same size. Hierarchy comes from grouping and section
 * labels, not from shrinking one row — two sizes read as inconsistent rather
 * than as a deliberate ranking.
 */
export function StatTile({
  label,
  value,
  valueClass = 'text-gray-100',
  sub,
  title,
  metric,
  raw,
}: {
  label: string;
  value: string;
  valueClass?: string;
  sub?: string;
  /** Native tooltip — how the metric is defined. */
  title?: string;
  /** Key into METRIC_BANDS; enables the quality meter. */
  metric?: string;
  /** Numeric value the meter reads (the formatted `value` is display-only). */
  raw?: number | null;
}) {
  const band = metric ? classifyMetric(metric, raw) : null;
  const style = band ? BAND_STYLE[band] : null;

  return (
    <div className="glass flex flex-col p-4" title={title}>
      <p className="section-index">{label}</p>
      <p className={`num mt-1.5 text-2xl font-semibold ${valueClass}`}>{value}</p>

      {style && metric && (
        <div className="mt-2.5">
          <div className="relative h-1.5 overflow-hidden rounded-full bg-white/[0.07]">
            <div
              className={`h-full rounded-full ${style.fill}`}
              style={{ width: `${meterFraction(metric, raw) * 100}%` }}
            />
            {/* Band edges — where "fair" becomes "good", and so on. */}
            {bandTicks(metric).map((t) => (
              <span
                key={t}
                className="absolute top-0 h-full w-px bg-black/50"
                style={{ left: `${t * 100}%` }}
              />
            ))}
          </div>
          <p className={`mt-1.5 text-[11px] font-medium ${style.text}`}>{style.label}</p>
        </div>
      )}

      {sub && <p className="mt-1 text-xs text-gray-500">{sub}</p>}
    </div>
  );
}
