/**
 * Shared device-TTS helper (expo-speech). Lazily requires `expo-speech` and
 * no-ops when the currently installed dev-client predates it — the same
 * defensive pattern as `useSpokenGuidance`, so both can share one module
 * instead of loading `expo-speech` twice.
 */
let Speech: { speak: (t: string, o?: object) => void; stop: () => void } | null = null;
try {
  // eslint-disable-next-line @typescript-eslint/no-var-requires
  Speech = require("expo-speech");
} catch {
  Speech = null;
}

/** Speaks `text` at `volume` (0–1) in en-GB, cancelling anything mid-utterance first. No-op if `expo-speech` is unavailable. */
export function speak(text: string, volume: number): void {
  if (!Speech) return;
  Speech.stop();
  Speech.speak(text, {
    language: "en-GB",
    volume,
    rate: 1.0,
  });
}

/** Stops any in-flight speech. No-op if `expo-speech` is unavailable. */
export function stopSpeaking(): void {
  Speech?.stop();
}

/** Speaks a short sample instruction at `volume` (0–1) — used by the
 * Settings "Test voice" action so users can preview volume/mute changes
 * without starting a real guidance session. */
export function speakSample(volume: number): void {
  speak("In 200 metres, turn right onto High Street.", volume);
}
