const speechState = {
  mode: 'auto',
  language: 'da',
  speaking: false
};

let onStartCallback = null;
let onEndCallback = null;

export function initSpeech(options = {}) {
  speechState.mode = options.mode || 'auto';
  speechState.language = options.language || 'da';
  onStartCallback = options.onStart || null;
  onEndCallback = options.onEnd || null;
}

export function setSpeechMode(mode) {
  speechState.mode = ['off','click','auto'].includes(mode) ? mode : 'auto';
  if (speechState.mode === 'off') stopSpeech();
}

export function setSpeechLanguage(language) {
  speechState.language = language === 'en' ? 'en' : 'da';
}

export function getSpeechMode() {
  return speechState.mode;
}

export function canSpeak() {
  return 'speechSynthesis' in window && 'SpeechSynthesisUtterance' in window;
}

export function stopSpeech() {
  if (canSpeak()) window.speechSynthesis.cancel();
  speechState.speaking = false;
  if (onEndCallback) onEndCallback();
}

export function speakText(text, force = false) {
  if (!canSpeak() || !text) return false;
  if (!force && speechState.mode === 'off') return false;
  if (!force && speechState.mode === 'click') return false;

  window.speechSynthesis.cancel();

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = speechState.language === 'da' ? 'da-DK' : 'en-GB';
  utterance.rate = speechState.language === 'da' ? 0.88 : 0.92;
  utterance.pitch = 1.08;
  utterance.volume = 1;

  utterance.onstart = () => {
    speechState.speaking = true;
    if (onStartCallback) onStartCallback();
  };

  utterance.onend = utterance.onerror = () => {
    speechState.speaking = false;
    if (onEndCallback) onEndCallback();
  };

  window.speechSynthesis.speak(utterance);
  return true;
}

export function speakNow(text) {
  if (!canSpeak() || !text || speechState.mode === 'off') return false;

  window.speechSynthesis.cancel();

  const utterance = new SpeechSynthesisUtterance(text);
  utterance.lang = speechState.language === 'da' ? 'da-DK' : 'en-GB';
  utterance.rate = speechState.language === 'da' ? 0.88 : 0.92;
  utterance.pitch = 1.08;
  utterance.volume = 1;

  utterance.onstart = () => {
    speechState.speaking = true;
    if (onStartCallback) onStartCallback();
  };

  utterance.onend = utterance.onerror = () => {
    speechState.speaking = false;
    if (onEndCallback) onEndCallback();
  };

  window.speechSynthesis.speak(utterance);
  return true;
}
