/* EireneEduCloud — Audio narration ("Listen to this lesson")
   Eirene Technologies Limited
   Gives EVERY lesson an offline audio version using the browser's built-in
   Web Speech API (SpeechSynthesis) — no audio files to ship, works without internet.
   Optional: a lesson may instead provide a bundled audio file (audio.file) or a
   podcast embed (handled separately). This module powers the on-device narration. */
(function (w, d) {
  var synth = w.speechSynthesis || null;

  function splitSentences(text) {
    // keep it simple & robust across browsers
    var clean = String(text || '').replace(/\s+/g, ' ').trim();
    if (!clean) return [];
    var parts = clean.match(/[^.!?]+[.!?]*/g) || [clean];
    return parts.map(function (s) { return s.trim(); }).filter(Boolean);
  }

  var EireneAudio = {
    supported: function () { return !!synth && typeof w.SpeechSynthesisUtterance === 'function'; },
    _queue: [], _i: 0, _playing: false, _paused: false, _rate: 1, _onsentence: null, _ondone: null, _voice: null,

    pickVoice: function () {
      if (!synth) return null;
      var voices = synth.getVoices() || [];
      if (!voices.length) return null;
      // prefer an English voice; Kenyan/African English if present, else en-GB/US
      var pref = voices.filter(function (v) { return /en[-_]?(KE|GB|US|ZA)/i.test(v.lang); });
      this._voice = (pref[0] || voices.filter(function (v) { return /^en/i.test(v.lang); })[0] || voices[0]);
      return this._voice;
    },

    speak: function (text, opts) {
      opts = opts || {};
      if (!this.supported()) { if (opts.onunsupported) opts.onunsupported(); return false; }
      this.stop();
      this._queue = splitSentences(text);
      this._i = 0; this._playing = true; this._paused = false;
      this._rate = opts.rate || this._rate || 1;
      this._onsentence = opts.onsentence || null;
      this._ondone = opts.ondone || null;
      if (!this._voice) this.pickVoice();
      this._next();
      return true;
    },

    _next: function () {
      var self = this;
      if (!this._playing || this._i >= this._queue.length) {
        this._playing = false;
        if (this._ondone) this._ondone();
        return;
      }
      var u = new w.SpeechSynthesisUtterance(this._queue[this._i]);
      u.rate = this._rate; u.pitch = 1; u.lang = (this._voice && this._voice.lang) || 'en-GB';
      if (this._voice) u.voice = this._voice;
      if (this._onsentence) this._onsentence(this._i, this._queue.length, this._queue[this._i]);
      u.onend = function () { if (self._playing) { self._i++; self._next(); } };
      u.onerror = function () { if (self._playing) { self._i++; self._next(); } };
      try { synth.speak(u); } catch (e) { this._i++; this._next(); }
    },

    pause: function () { if (synth && this._playing) { synth.pause(); this._paused = true; } },
    resume: function () { if (synth && this._paused) { synth.resume(); this._paused = false; } },
    setRate: function (r) {
      this._rate = r;
      if (this._playing) { // apply from next sentence
        var resumeAt = this._i;
        var q = this._queue, done = this._ondone, sent = this._onsentence;
        this.stop();
        this._queue = q; this._i = resumeAt; this._playing = true; this._paused = false;
        this._ondone = done; this._onsentence = sent; this._next();
      }
    },
    stop: function () {
      this._playing = false; this._paused = false;
      if (synth) { try { synth.cancel(); } catch (e) {} }
    },
    isPlaying: function () { return this._playing && !this._paused; }
  };

  // Some browsers load voices asynchronously
  if (synth && typeof synth.onvoiceschanged !== 'undefined') {
    synth.onvoiceschanged = function () { EireneAudio.pickVoice(); };
  }

  w.EireneAudio = EireneAudio;
})(window, document);
