import { useEffect, useRef } from "react";
import { playSound, type PeonSound } from "../usePeonSounds";

/**
 * Plays a sound when data changes from a background refetch (not from a user mutation).
 * The `mutationGuard` ref should be set to `true` before a mutation and is automatically
 * cleared after the next data change so the mutation's own refetch doesn't double-trigger.
 */
export function useExternalChangeSound<T>(
  data: T | undefined,
  sound: PeonSound,
  mutationGuard: React.MutableRefObject<boolean>
) {
  const prevRef = useRef<T | undefined>(undefined);
  const initialLoadDone = useRef(false);

  useEffect(() => {
    if (data === undefined) return;

    if (!initialLoadDone.current) {
      prevRef.current = data;
      initialLoadDone.current = true;
      return;
    }

    const prev = prevRef.current;
    prevRef.current = data;

    // Shallow compare — works for arrays (new reference = new data from server)
    if (prev === data) return;

    if (mutationGuard.current) {
      mutationGuard.current = false;
      return;
    }

    playSound(sound, 0.3);
  }, [data, sound, mutationGuard]);
}
