/**
 * Looping Sonic alert for visitors that need attention.
 * Stops on admin redirect, when criteria no longer match, or when sound is off.
 */
var AlertSound = (function () {
  "use strict";

  var SOUND_URL = "sounds/Sonic Rings Dropping Sound Effect.mp3";
  var STORAGE_KEY = "scii_admin_sound_enabled";
  var audio = null;
  var playing = false;
  var wantsPlay = false;
  var unlocked = false;
  var enabled = true;

  function readEnabled() {
    try {
      var v = localStorage.getItem(STORAGE_KEY);
      if (v === "0" || v === "false") return false;
      if (v === "1" || v === "true") return true;
    } catch (e) {}
    return true;
  }

  function persistEnabled(on) {
    try {
      localStorage.setItem(STORAGE_KEY, on ? "1" : "0");
    } catch (e) {}
  }

  enabled = readEnabled();

  function getAudio() {
    if (!audio) {
      audio = new Audio(encodeURI(SOUND_URL));
      audio.preload = "auto";
      audio.volume = 0.7;
      audio.loop = true;
    }
    return audio;
  }

  function unlock() {
    var el = getAudio();
    return el
      .play()
      .then(function () {
        el.pause();
        el.currentTime = 0;
        unlocked = true;
        if (wantsPlay && enabled && !playing) {
          startInternal();
        }
        return true;
      })
      .catch(function () {
        return false;
      });
  }

  function isPanelControlClick(e) {
    if (!e || !e.target || !e.target.closest) return false;
    return !!e.target.closest(
      ".visitor-action-tile, .visitor-filter-btn, .visitor-card-toggle, " +
        "#mode-awake, #mode-sleep, #visitor-filter-bar, .panel-mode-btn, " +
        "#login-form, #login-overlay button"
    );
  }

  function bindUnlockOnce() {
    if (bindUnlockOnce.done) return;
    bindUnlockOnce.done = true;
    function tryUnlock(e) {
      if (isPanelControlClick(e)) return;
      unlock().then(function (ok) {
        if (ok) {
          document.removeEventListener("click", tryUnlock, true);
          document.removeEventListener("keydown", tryUnlock, true);
          document.removeEventListener("touchstart", tryUnlock, true);
        }
      });
    }
    document.addEventListener("click", tryUnlock, true);
    document.addEventListener("keydown", tryUnlock, true);
    document.addEventListener("touchstart", tryUnlock, true);
  }

  function startInternal() {
    if (!enabled || !wantsPlay || playing) return;
    var el = getAudio();
    playing = true;
    el.currentTime = 0;
    var playPromise = el.play();
    if (playPromise && typeof playPromise.catch === "function") {
      playPromise.catch(function () {
        playing = false;
      });
    }
  }

  function start() {
    if (!enabled) return;
    wantsPlay = true;
    bindUnlockOnce();
    if (!unlocked) {
      unlock().then(function (ok) {
        if (ok && wantsPlay && enabled) startInternal();
      });
      return;
    }
    startInternal();
  }

  function stop() {
    wantsPlay = false;
    playing = false;
    if (audio) {
      audio.pause();
      audio.currentTime = 0;
    }
  }

  function setEnabled(on) {
    enabled = !!on;
    persistEnabled(enabled);
    if (!enabled) stop();
    else if (wantsPlay) start();
  }

  function isEnabled() {
    return enabled;
  }

  function isPlaying() {
    return playing && audio && !audio.paused;
  }

  bindUnlockOnce();

  return {
    start: start,
    stop: stop,
    setEnabled: setEnabled,
    isEnabled: isEnabled,
    isPlaying: isPlaying,
    unlock: unlock,
  };
})();
