"use client";

import { useTranslations } from "next-intl";
import type { MouseEvent } from "react";

import { formatTimelineTime } from "@/lib/studio-timeline";

interface TimeRulerProps {
  totalDuration: number;
  pxPerSecond: number;
  currentTime?: number;
  onSeek?: (time: number) => void;
}

function getRulerConfig(totalDuration: number): { major: number; minor: number } {
  if (totalDuration <= 20)  return { major: 5,   minor: 1  };
  if (totalDuration <= 60)  return { major: 10,  minor: 5  };
  if (totalDuration <= 150) return { major: 30,  minor: 10 };
  if (totalDuration <= 300) return { major: 60,  minor: 30 };
  if (totalDuration <= 600) return { major: 60,  minor: 30 };
  return                           { major: 120, minor: 60 };
}

function formatLabel(seconds: number, totalDuration: number): string {
  if (seconds === 0) return "0:00";
  if (totalDuration < 60) return `${seconds}s`;
  return formatTimelineTime(seconds);
}

export function TimeRuler({
  totalDuration,
  pxPerSecond,
  currentTime,
  onSeek,
}: TimeRulerProps) {
  const t = useTranslations("auto.componentsStudioTimelineTimeRuler");
  const safeDuration = Math.max(totalDuration, 5);
  const width = safeDuration * pxPerSecond + 160;

  const { major, minor } = getRulerConfig(safeDuration);
  const tickCount = Math.ceil(safeDuration / minor) + 2;

  const handleClick = (event: MouseEvent<HTMLDivElement>) => {
    if (!onSeek) return;
    const rect = event.currentTarget.getBoundingClientRect();
    const x = event.clientX - rect.left;
    onSeek(Math.max(0, Math.min(totalDuration, x / pxPerSecond)));
  };

  return (
    <div
      role="slider"
      aria-label={t("rulerAriaLabel")}
      aria-valuemin={0}
      aria-valuemax={totalDuration}
      aria-valuenow={currentTime ?? 0}
      tabIndex={0}
      onClick={handleClick}
      className="relative h-7 shrink-0 cursor-pointer select-none border-b border-gray-200 bg-gray-50"
      style={{ width }}
    >
      {Array.from({ length: tickCount }, (_, i) => {
        const s = i * minor;
        if (s > safeDuration + minor) return null;
        const isMajor = s % major === 0;
        const left = s * pxPerSecond;

        return (
          <div key={s} className="absolute top-0 h-full" style={{ left }}>
            {/* Tick line */}
            <div
              className={isMajor ? "absolute bottom-0 left-0 w-px bg-gray-400" : "absolute bottom-0 left-0 w-px bg-gray-200"}
              style={{ height: isMajor ? 10 : 5 }}
            />
            {/* Label on major ticks only */}
            {isMajor && (
              <span className="absolute left-1 top-0.5 whitespace-nowrap text-[9px] tabular-nums leading-none text-gray-400">
                {formatLabel(s, totalDuration)}
              </span>
            )}
          </div>
        );
      })}

      {/* Playhead */}
      {currentTime != null && currentTime >= 0 && (
        <div
          aria-hidden
          className="pointer-events-none absolute top-0 h-full w-px bg-blue-500"
          style={{ left: currentTime * pxPerSecond }}
        />
      )}
    </div>
  );
}
