"use client";

import { Loader2, RefreshCw } from "lucide-react";

import { playerViewportFixedBarClass } from "@/lib/player-viewport";
import { cn } from "@/lib/utils";

interface PullToRefreshIndicatorProps {
  pullDistance: number;
  isRefreshing: boolean;
  threshold: number;
}

/**
 * Visual indicator for pull-to-refresh.
 * Renders a fixed bar at the top that grows as the user pulls down.
 */
export function PullToRefreshIndicator({
  pullDistance,
  isRefreshing,
  threshold,
}: PullToRefreshIndicatorProps) {
  if (pullDistance === 0 && !isRefreshing) return null;

  const percent = Math.min(pullDistance / threshold, 1);

  return (
    <div
      className={cn(
        playerViewportFixedBarClass,
        "pointer-events-none z-[60] flex items-center justify-center overflow-hidden transition-[height] duration-100 ease-out",
      )}
      style={{
        top: "env(safe-area-inset-top, 0px)",
        height: isRefreshing ? 40 : pullDistance,
      }}
    >
      <div
        className={cn(
          "flex items-center gap-1.5 text-xs font-bold text-[#32518d] transition-opacity",
          pullDistance > 5 || isRefreshing ? "opacity-100" : "opacity-0",
        )}
      >
        {isRefreshing ? (
          <Loader2 className="size-4 animate-spin" aria-hidden />
        ) : (
          <RefreshCw
            className="size-4 transition-transform"
            style={{ transform: `rotate(${percent * 360}deg)` }}
            aria-hidden
          />
        )}
        <span>{isRefreshing ? "…" : ""}</span>
      </div>
    </div>
  );
}
