window.tmSpeak = {
    _voice: null,
    _ready: false,

    init() {
        if (!('speechSynthesis' in window)) return false;
        const pick = () => {
            const voices = window.speechSynthesis.getVoices();
            // Prefer English voices; fall back to default
            this._voice = voices.find(v => /en-/i.test(v.lang) && v.default)
                       || voices.find(v => /en-/i.test(v.lang))
                       || voices[0] || null;
            this._ready = true;
        };
        pick();
        window.speechSynthesis.onvoiceschanged = pick;
        return true;
    },

    speak(text) {
        try {
            if (!('speechSynthesis' in window)) return;
            const u = new SpeechSynthesisUtterance(text);
            if (this._voice) u.voice = this._voice;
            u.rate = 1.0; u.pitch = 1.0; u.volume = 1.0;
            window.speechSynthesis.speak(u);
        } catch { }
    },

    // Browsers block speech until a user gesture — call this on a button click
    prime() {
        try {
            const u = new SpeechSynthesisUtterance(' ');
            u.volume = 0;
            window.speechSynthesis.speak(u);
        } catch { }
    }
};

if (document.readyState !== 'loading') window.tmSpeak.init();
else document.addEventListener('DOMContentLoaded', () => window.tmSpeak.init());
