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

import { useAudioInstructionsStore } from "@/modules/watcher/store/audio-instructions.store";

import { useAudioStore } from "../lib/audio.store";

export const AlarmPlayer: FC = () => {
	const store = useAudioStore();
	const ref = useRef(new Audio("/audio/alarm.ogg") as HTMLAudioElement);
	const { isShowedAudioInstructions } = useAudioInstructionsStore();

	useEffect(() => {
		const play = async (audioElement: HTMLAudioElement) => {
			try {
				if (import.meta.env.DEV) {
					audioElement.volume = 0.02;
				} else {
					audioElement.volume = 1.0;
				}

				audioElement.loop = true;

				await audioElement.play();
			} catch (error: unknown) {
				console.warn("Audio playback error:", error);
				store.setIsShowError(true);
			}
		};

		const stop = (audioElement: HTMLAudioElement) => {
			audioElement.pause();
		};

		if (store.isPlaying) {
			stop(ref.current);
			play(ref.current);
		} else {
			stop(ref.current);
		}
	}, [store.isPlaying, isShowedAudioInstructions]);

	return <audio src="/audio/alarm.ogg" loop ref={ref} />;
};
