/* OPHI-118 — OBS WebSocket connection helper with auto-reconnect.
 *
 * Most overlays connect to OBS WS to receive `mpd:state` events. This
 * wraps the connect-then-retry-on-close dance so each page doesn't
 * repeat it inline.
 *
 *   OBSWSBootstrap.onState(handler, { onClose, onConnect })
 *   OBSWSBootstrap.connect({ onConnect, onClose })
 *
 * Both forms return the underlying OBSWSMini instance via the promise
 * resolved by onConnect (or directly from connect()).
 */
(function (root) {
  'use strict';

  function _connect(opts) {
    const { onConnect, onClose } = opts || {};
    if (!root.__OBSWS || !root.OBSWSMini) {
      onClose && onClose(new Error('vendor/obs-config.js missing'));
      return;
    }
    const obs = new root.OBSWSMini(root.__OBSWS.url, root.__OBSWS.password);
    obs.connect().then(() => {
      onConnect && onConnect(obs);
    }).catch((err) => {
      onClose && onClose(err);
      setTimeout(() => _connect(opts), 2500);
    });
    obs.addEventListener('close', () => {
      onClose && onClose(new Error('connection closed'));
      setTimeout(() => _connect(opts), 2000);
    });
  }

  function onState(handler, opts) {
    _connect({
      onConnect: (obs) => {
        obs.onCustom('mpd:state', handler);
        opts?.onConnect && opts.onConnect(obs);
      },
      onClose: opts?.onClose,
    });
  }

  root.OBSWSBootstrap = { connect: _connect, onState };
})(typeof window !== 'undefined' ? window : globalThis);
