import i18next from 'i18next'
import { settingsRepository } from '../db/repositories/settingsRepository.js'

const LANG_MAP = { en: 'en-US', fr: 'fr-FR', da: 'da-DK' }

export function useSpeech() {
  const isSupported = typeof window !== 'undefined' && 'speechSynthesis' in window
  let enabled = true

  async function init() {
    const val = await settingsRepository.get('voice_enabled')
    enabled = val === null ? true : val === 'true'
  }

  function speak(text, { volume = 1.0 } = {}) {
    if (!enabled || !isSupported) return
    try {
      window.speechSynthesis.cancel()
      const utterance = new window.SpeechSynthesisUtterance(text)
      utterance.lang = LANG_MAP[i18next.language] || 'en-US'
      utterance.volume = volume
      window.speechSynthesis.speak(utterance)
    } catch (_e) {
      // Ignore speech errors — announcement is best-effort
    }
  }

  function cancel() {
    if (isSupported) window.speechSynthesis.cancel()
  }

  return { init, speak, cancel, isSupported }
}
