import type { Chapter } from "../api/videos";

interface ChapterMarkersProps {
  chapters: Chapter[];
  duration: number;
  onSeek: (time: number) => void;
  currentTime?: number;
}

/** Format seconds as m:ss */
function formatTime(seconds: number): string {
  if (!Number.isFinite(seconds) || seconds < 0) return "0:00";
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m}:${s.toString().padStart(2, "0")}`;
}

const PIN_COLOR_CLASS: Record<string, string> = {
  technique: "chapter-marker__pin--technique",
  settings: "chapter-marker__pin--settings",
  reasoning: "chapter-marker__pin--reasoning",
  workflow: "chapter-marker__pin--workflow",
};

/**
 * Absolutely-positioned overlay that renders color-coded circle pins
 * on the seek bar for each chapter. Pins are clickable and show a
 * rich tooltip on hover. The active pin (matching current playback
 * position) is enlarged.
 */
export default function ChapterMarkers({
  chapters,
  duration,
  onSeek,
  currentTime,
}: ChapterMarkersProps) {
  if (!duration || chapters.length === 0) return null;

  return (
    <div className="chapter-markers">
      {chapters.map((ch) => {
        const leftPct = (ch.start_time / duration) * 100;
        const isActive =
          currentTime != null &&
          ch.start_time <= currentTime &&
          currentTime <= ch.end_time;

        const colorClass = PIN_COLOR_CLASS[ch.content_type] ?? "";
        const activeClass = isActive ? " chapter-marker__pin--active" : "";

        return (
          <button
            key={ch.id}
            className={`chapter-marker__pin${colorClass ? ` ${colorClass}` : ""}${activeClass}`}
            style={{ left: `${leftPct}%` }}
            onClick={(e) => {
              e.stopPropagation();
              onSeek(ch.start_time);
            }}
            aria-label={`Jump to chapter: ${ch.title}`}
            type="button"
          >
            <span className="chapter-marker__tooltip">
              {ch.title} · {formatTime(ch.start_time)}–{formatTime(ch.end_time)} · {ch.content_type}
            </span>
          </button>
        );
      })}
    </div>
  );
}
