"use client";
import { usePilotConnectionStore } from "_store/pilot/connectionStore";
import { useMrtStore } from "_store/pilot/MrtStore";
import { useEffect, useRef } from "react";

export const useSounds = () => {
	const mrtState = useMrtStore((state) => state);
	const { connectedAircraft, selectedStation } = usePilotConnectionStore(
		(state) => state,
	);

	const setPage = useMrtStore((state) => state.setPage);
	const MRTstatusSoundRef = useRef<HTMLAudioElement>(null);
	const MrtMessageReceivedSoundRef = useRef<HTMLAudioElement>(null);

	useEffect(() => {
		if (typeof window !== "undefined") {
			MRTstatusSoundRef.current = new Audio("/sounds/MRT-status.mp3");
			MrtMessageReceivedSoundRef.current = new Audio(
				"/sounds/MRT-message-received.mp3",
			);
			MRTstatusSoundRef.current.onended = () => {
				if (!selectedStation || !connectedAircraft?.fmsStatus) return;
				setPage({
					page: "home",
					station: selectedStation,
					fmsStatus: connectedAircraft?.fmsStatus,
				});
			};
			MrtMessageReceivedSoundRef.current.onended = () => {
				if (!selectedStation || !connectedAircraft?.fmsStatus) return;
				setPage({
					page: "home",
					station: selectedStation,
					fmsStatus: connectedAircraft?.fmsStatus,
				});
			};
		}
	}, [connectedAircraft?.fmsStatus, selectedStation, setPage]);

	const fmsStatus = connectedAircraft?.fmsStatus || "NaN";

	useEffect(() => {
		if (!connectedAircraft) return;
		if (mrtState.page === "new-status") {
			if (fmsStatus === "J" || fmsStatus === "c") {
				MrtMessageReceivedSoundRef.current?.play();
			} else {
				MRTstatusSoundRef.current?.play();
			}
		}
	}, [mrtState, fmsStatus, connectedAircraft, selectedStation]);
};
