(function (root, factory) {
  if (typeof module === 'object' && module.exports) module.exports = factory;
  else root.createUpdateTriageLauncher = factory;
})(typeof self !== 'undefined' ? self : this, function createUpdateTriageLauncher(options) {
  let pending = null;

  function open() {
    if (pending) return pending;
    options.selectUpdates();
    options.announce('Checking all unread updates…');
    pending = Promise.resolve()
      .then(() => options.discover())
      .then(discovery => {
        if (!options.isUpdatesSelected()) return 'cancelled';
        if (discovery === false || discovery?.complete === false) {
          options.announce('Updates check paused. Retry to check older unread updates.');
          return 'incomplete';
        }
        if (discovery?.complete) options.applySnapshot?.(discovery);
        if (options.hasMore()) {
          options.announce('Updates check paused. Retry to check older unread updates.');
          return 'incomplete';
        }
        const opened = options.hasCheckpoint() ? options.resume() : options.start();
        if (!opened) options.announce('No unread updates are ready.');
        return opened ? 'opened' : 'empty';
      })
      .catch(() => {
        if (options.isUpdatesSelected()) {
          options.announce('Updates check paused. Retry to check older unread updates.');
        }
        return 'incomplete';
      })
      .finally(() => { pending = null; });
    return pending;
  }

  return {open};
});
