import { useCallback, useEffect, useRef } from "react";

import HowlManager, { type HowlLoadOptions } from "@/helpers/howler";
import { useStore } from "@/store";

import useFirstInteraction from "./useFirstInteraction";

export default function useHowler() {
  const isMuted = useStore.use.isMuted();
  const howlManager = useRef(HowlManager.getInstance());
  const didInteract = useFirstInteraction();

  useEffect(() => {
    const unsubscribeIsMuted = useStore.subscribe((state) => {
      Howler.mute(state.isMuted);
    });

    const unsubscribeAudioAllowed = useStore.subscribe((state) => {
      if (!state.audioAllowed) {
        Howler.stop();
      }
    });

    return () => {
      unsubscribeIsMuted();
      unsubscribeAudioAllowed();
    };
  }, []);

  const load = useCallback(
    (src: string | string[], options?: HowlLoadOptions) => {
      howlManager.current.load(src, options);
    },
    [],
  );

  const play = useCallback(() => {
    if (isMuted || !didInteract) return;
    howlManager.current.play();
  }, [isMuted, didInteract]);

  const stop = useCallback(() => {
    howlManager.current.stop();
  }, []);

  return { load, play, stop };
}
