import { useRef, useEffect, useCallback } from "react";
import { getRadarPosition } from "../utilities/utilities";

/**
 * usePovLock — Lock radar to follow one specific player (center + rotate).
 *
 * Features:
 *  - Cumulative rotation: survives player switches and respawns
 *  - Smooth lerp via rAF (no re-render per frame)
 *  - Updates when player dies/respawns/calls setLockedPlayerIdx(null)
 *  - Configurable zoom level via `zoom` prop
 *
 * Props:
 *  zoom — zoom level to apply when locking (default 3.5)
 *
 * Returns:
 *  rotation     — current cumulative rotation in degrees (for Player counter-rotate)
 *  targetRot   — lerp target (90 - eye_angle)   ← use this as rAF target
 *  isLocked     — boolean
 *  cumulativeRotRef — mutable ref: update with rotateDelta(d) to add manual drag rotation
 */
export function usePovLock({ lockedPlayerIdx, playerArray, mapData, imgStyle, setZoom, setPan, zoom = 3.5 }) {
  const cumulativeRotRef = useRef(0);

  // ── Step 1: center + set zoom on selection / respawn ────────────────────
  useEffect(() => {
    if (lockedPlayerIdx === null) {
      cumulativeRotRef.current = 0;
      return;
    }
    if (!playerArray || !mapData || !imgStyle.w) return;

    const lockedPlayer = playerArray.find(p => p.m_idx === lockedPlayerIdx && !p.m_is_dead);
    if (!lockedPlayer) return;          // still dead — keep current view

    const pos = getRadarPosition(mapData, lockedPlayer.m_position ?? lockedPlayer);
    setZoom(zoom);
    setPan({
      x: (0.5 - pos.x) * imgStyle.w * zoom,
      y: (0.5 - pos.y) * imgStyle.h * zoom,
    });
  }, [lockedPlayerIdx, playerArray, mapData, imgStyle, setZoom, setPan, zoom]);

  // ── Step 2: compute target yaw for rAF lerp ─────────────────────────────
  const rawTarget = (() => {
    if (!lockedPlayerIdx || !playerArray || !mapData) return 0;
    const p = playerArray.find(pl => pl.m_idx === lockedPlayerIdx && !pl.m_is_dead);
    if (!p) return 0;
    // CS2 yaw 0=East, 90=North, increasing = turning LEFT (CCW).
    // To bring the player's forward to screen-up, the map must rotate by
    // (90 - yaw) because the yaw direction is reversed from CSS rotation.
    return (p.m_eye_angle || 0) - 90;
  })();

  // isLocked
  const isLocked = lockedPlayerIdx !== null &&
    playerArray?.some(p => p.m_idx === lockedPlayerIdx && !p.m_is_dead);

  return {
    rotation: cumulativeRotRef.current,
    targetRot: rawTarget,
    isLocked,
    cumulativeRotRef,
    /** rawTarget = yaw - 90 (no cumulative offset).
     *  Use this in radar.jsx rAF when followYourselfRotation=true. */
    rawTarget,
  };
}