/**
 * Speaks turn instructions for guidance events via the device TTS
 * (expo-speech). On the REAL native bridge the SDK's own VoiceGuidance
 * (AVSpeechSynthesizer / Android TextToSpeech) speaks natively and this
 * hook must stay silent for it — the native module emits voiceState with
 * `speaking`; we key off the mock instead: the mock never produces audio,
 * so JS speech fills that gap for demos and Expo Go.
 *
 * Speaks on banner-instruction *changes* (not every 1Hz tick), honours the
 * persisted mute + volume settings, and announces arrival.
 */
import { useEffect, useRef } from "react";
import type { GuidanceEvent } from "../../../modules/mapmap-react-native/src/MapmapNav.types";
import { isMockActive } from "../mapmapNav/useMapmapNav";
import { speak, stopSpeaking } from "./speak";

export function useSpokenGuidance(
  guidance: GuidanceEvent | undefined,
  muted: boolean,
  volume: number
): void {
  const lastSpoken = useRef<string | null>(null);

  useEffect(() => {
    if (!guidance || muted || !isMockActive()) return;

    const utterance =
      guidance.state === "arrived"
        ? "You have arrived at your destination."
        : guidance.state === "rerouting"
          ? "Rerouting."
          : guidance.banner?.primary;

    if (!utterance || utterance === lastSpoken.current) return;
    lastSpoken.current = utterance;

    speak(utterance, volume);
  }, [guidance, muted, volume]);

  // Stop talking the moment guidance unmounts or mute flips on.
  useEffect(() => {
    if (muted) stopSpeaking();
    return () => {
      stopSpeaking();
    };
  }, [muted]);
}
