import { useRef, useEffect, useCallback } from "react";
import {
  computeBoundingBox,
  computeTargetScale,
  computeTargetPan,
  updateQueues,
  computeAverages,
} from "../utilities/autozoomUtils.js";

// Default queue values
const makeDefaultQueues = () => ({
  scale: [1, 1, 1, 1, 1, 1],
  x:     [0, 0, 0, 0, 0, 0],
  y:     [0, 0, 0, 0, 0, 0],
});

/**
 * useAutozoom — Automatically zooms and pans the radar to keep all alive
 * players in view, with 6-frame smoothing.
 *
 * @param {object}  params
 * @param {boolean} params.enabled         — settings.autoZoom
 * @param {Array}   params.playerArray     — full player list
 * @param {object|null} params.mapData     — map metadata
 * @param {{ w: number, h: number }} params.imgStyle
 * @param {React.MutableRefObject<boolean>} params.manualZoomRef
 * @param {Function} params.setZoom
 * @param {Function} params.setPan
 * @param {Function} params.clamp          — (panX, panY, scale) => { x, y }
 * @param {object}  params.settings        — radar settings
 *
 * @returns {{ resetQueues: Function }}
 */
export function useAutozoom({
  enabled,
  playerArray,
  mapData,
  imgStyle,
  manualZoomRef,
  setZoom,
  setPan,
  clamp,
  settings,
}) {
  const queuesRef = useRef(makeDefaultQueues());

  const resetQueues = useCallback(() => {
    queuesRef.current = makeDefaultQueues();
  }, []);

  useEffect(() => {
    // Guard: disabled or user is in manual zoom mode
    if (!enabled || manualZoomRef.current === true) return;
    // Guard: no image dimensions yet
    if (!imgStyle || imgStyle.w === 0) return;

    const alivePlayers = playerArray ?? [];

    const bounds = computeBoundingBox(alivePlayers, mapData);
    if (!bounds) return;

    const { scale: targetScale, reset } = computeTargetScale(bounds, settings);

    if (reset) {
      setZoom(1);
      setPan({ x: 0, y: 0 });
      queuesRef.current = makeDefaultQueues();
      return;
    }

    const { x: targetPanX, y: targetPanY } = computeTargetPan(bounds, imgStyle, targetScale);

    updateQueues(queuesRef.current, targetScale, targetPanX, targetPanY);
    const avg = computeAverages(queuesRef.current);

    setZoom(avg.scale);
    setPan(clamp(avg.x, avg.y, avg.scale));
  }, [playerArray, enabled, mapData, imgStyle, settings]); // eslint-disable-line react-hooks/exhaustive-deps

  return { resetQueues };
}
