// components/admin/Sparkline.tsx
// Simple, dependency-free SVG sparkline of paid purchases per minute. Server-safe
// (pure render), accessible (role=img + a text summary + a hidden data table so
// the trend is not color/shape-only).

import * as React from "react";

interface SparkPoint {
  minute: string; // ISO
  paid: number;
}

export function Sparkline({
  points,
  height = 80,
}: {
  points: SparkPoint[];
  height?: number;
}) {
  if (points.length === 0) {
    return (
      <p className="font-body text-body-md text-muted">
        Sin compras pagadas en la ventana mostrada.
      </p>
    );
  }

  const width = 600;
  const max = Math.max(1, ...points.map((p) => p.paid));
  const total = points.reduce((a, p) => a + p.paid, 0);
  const peak = points.reduce(
    (best, p) => (p.paid > best.paid ? p : best),
    points[0],
  );
  const stepX = width / Math.max(1, points.length - 1);

  const path = points
    .map((p, i) => {
      const x = i * stepX;
      const y = height - (p.paid / max) * (height - 4) - 2;
      return `${i === 0 ? "M" : "L"}${x.toFixed(1)},${y.toFixed(1)}`;
    })
    .join(" ");

  const summary = `Compras pagadas por minuto. Total ${total} en ${points.length} minutos. Pico de ${peak.paid} en ${formatMinute(peak.minute)}.`;

  return (
    <figure className="m-0">
      <svg
        viewBox={`0 0 ${width} ${height}`}
        width="100%"
        height={height}
        preserveAspectRatio="none"
        role="img"
        aria-label={summary}
        className="block"
      >
        <path
          d={path}
          fill="none"
          stroke="var(--color-primary, #dc0d15)"
          strokeWidth={2}
          strokeLinejoin="round"
          strokeLinecap="round"
        />
      </svg>
      <figcaption className="mt-2 font-body text-caption text-muted">
        {summary}
      </figcaption>
      {/* Hidden data table: trend is never color/shape-only (WCAG). */}
      <details className="mt-2">
        <summary className="cursor-pointer font-body text-caption text-steelblue">
          Ver datos por minuto
        </summary>
        <div className="mt-2 max-h-48 overflow-auto">
          <table className="w-full text-left">
            <caption className="sr-only">
              Compras pagadas por minuto
            </caption>
            <thead>
              <tr>
                <th scope="col" className="font-body text-micro text-muted-label">
                  Minuto
                </th>
                <th scope="col" className="font-body text-micro text-muted-label">
                  Pagadas
                </th>
              </tr>
            </thead>
            <tbody>
              {points
                .filter((p) => p.paid > 0)
                .map((p) => (
                  <tr key={p.minute}>
                    <td className="font-body text-micro text-ink-strong">
                      {formatMinute(p.minute)}
                    </td>
                    <td className="font-body text-micro text-ink-strong">
                      {p.paid}
                    </td>
                  </tr>
                ))}
            </tbody>
          </table>
        </div>
      </details>
    </figure>
  );
}

function formatMinute(iso: string): string {
  try {
    return new Date(iso).toLocaleTimeString("es-PE", {
      hour: "2-digit",
      minute: "2-digit",
      timeZone: "America/Lima",
    });
  } catch {
    return iso;
  }
}
