'use client';

/**
 * Bangla text-to-speech via the browser SpeechSynthesis API (free, offline,
 * no key). Picks a bn-BD / bn voice when available, otherwise the default.
 * A cloud TTS endpoint can be layered in later behind the same speak() call.
 */

let preferred: SpeechSynthesisVoice | null = null;

function ready(): SpeechSynthesis | null {
  if (typeof window === 'undefined' || !('speechSynthesis' in window)) return null;
  return window.speechSynthesis;
}

function pickVoice(synth: SpeechSynthesis): SpeechSynthesisVoice | null {
  if (preferred) return preferred;
  const voices = synth.getVoices();
  preferred =
    voices.find((v) => v.lang === 'bn-BD') ??
    voices.find((v) => v.lang?.startsWith('bn')) ??
    voices.find((v) => v.lang?.startsWith('hi')) ?? // Hindi voices read Bangla script tolerably
    null;
  return preferred;
}

export function isTtsSupported(): boolean {
  return ready() !== null;
}

/** Speak text aloud. Cancels any in-progress speech first. */
export function speak(text: string, opts: { rate?: number; pitch?: number } = {}) {
  const synth = ready();
  if (!synth || !text) return;
  try {
    synth.cancel();
    const u = new SpeechSynthesisUtterance(text);
    const v = pickVoice(synth);
    if (v) u.voice = v;
    u.lang = v?.lang ?? 'bn-BD';
    u.rate = opts.rate ?? 0.95;
    u.pitch = opts.pitch ?? 1.05;
    synth.speak(u);
  } catch {
    /* speech is best-effort */
  }
}

export function stopSpeaking() {
  ready()?.cancel();
}

// Some browsers load voices asynchronously; refresh the cached pick.
if (typeof window !== 'undefined' && 'speechSynthesis' in window) {
  window.speechSynthesis.onvoiceschanged = () => {
    preferred = null;
  };
}
