(function (global) {
  global.ARQ = global.ARQ || {};
  var $overlay = null;
  var $overlayText = null;
  var $pctLabel = null;
  var $progressTrack = null;
  var $progressFill = null;
  var criticalActive = false;
  var criticalId = null;

  function ensureOverlay() {
    if ($overlay && $overlay.length) return;
    $overlay = $('<div class="arq-op-overlay" id="arq-op-overlay" hidden aria-live="polite" aria-busy="true"/>');
    var $inner = $('<div class="arq-op-overlay__box"/>');
    $overlayText = $('<p class="arq-op-overlay__text"/>');
    $inner.append($overlayText);
    $pctLabel = $('<div class="arq-op-overlay__pct" aria-hidden="true">—</div>');
    $inner.append($pctLabel);
    var $progress = $('<div class="arq-op-progress" role="progressbar" aria-valuemin="0" aria-valuemax="100"/>');
    $progressTrack = $('<div class="arq-op-progress__track"/>');
    $progressFill = $('<div class="arq-op-progress__fill"/>');
    $progressTrack.append($progressFill);
    $progress.append($progressTrack);
    $inner.append($progress);
    $overlay.append($inner);
    $('body').append($overlay);
  }

  function setPctText(text) {
    if ($pctLabel && $pctLabel.length) $pctLabel.text(text);
  }

  function setProgressIndeterminate(on) {
    if (!$progressFill || !$progressTrack) return;
    if (on) {
      $progressFill.addClass('arq-op-progress__fill--indeterminate').removeAttr('style');
      $progressTrack.closest('.arq-op-progress').attr('aria-valuetext', 'En curso');
      setPctText('—');
    } else {
      $progressFill.removeClass('arq-op-progress__fill--indeterminate');
    }
  }

  function setProgressValue(pct) {
    if (!$progressFill || !$progressTrack) return;
    var n = Math.max(0, Math.min(100, Math.round(Number(pct) || 0)));
    $progressFill.removeClass('arq-op-progress__fill--indeterminate').css('width', n + '%');
    var $bar = $progressTrack.closest('.arq-op-progress');
    $bar.attr('aria-valuenow', n);
    $bar.attr('aria-valuetext', n + '%');
    setPctText(String(n) + ' %');
  }

  function showCritical(label) {
    ensureOverlay();
    criticalActive = true;
    $overlayText.text(label || 'Procesando…');
    setProgressIndeterminate(true);
    setPctText('—');
    $overlay.removeAttr('hidden');
    var root = $overlay[0];
    if (root) root.hidden = false;
  }

  function hideCritical() {
    criticalActive = false;
    criticalId = null;
    if ($overlay && $overlay.length) {
      $overlay.attr('hidden', 'hidden');
      var el = $overlay[0];
      if (el) el.hidden = true;
    }
  }

  ARQ.opsFeedback = {
    init: function () {
      var self = this;
      ARQ.bus.on(ARQ.EVENTS.OP_STARTED, function (p) {
        if (!p) return;
        if (p.blocking === 'critical') {
          criticalId = p.id;
          showCritical(p.label);
          if (typeof p.progress === 'number' && !isNaN(p.progress)) {
            setProgressValue(p.progress);
          }
        } else if (p.blocking === 'medium' && (p.id === 'save' || (p.label || '').indexOf('Guardando') >= 0)) {
          $('#editor-autosave-pill').addClass('is-saving').text(p.label || 'Guardando…');
        } else if (p.blocking === 'nonblocking' && p.label) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, p.label);
        }
      });
      ARQ.bus.on(ARQ.EVENTS.OP_STEP, function (p) {
        if (!p) return;
        if (criticalActive && p.id === criticalId && $overlayText) {
          $overlayText.text(p.label || p.step || '');
          if (typeof p.progress === 'number' && !isNaN(p.progress)) {
            setProgressValue(p.progress);
          } else {
            setProgressIndeterminate(true);
          }
        }
      });
      ARQ.bus.on(ARQ.EVENTS.OP_SUCCESS, function (p) {
        if (!p) return;
        if (criticalActive && p.id === criticalId) hideCritical();
        if (p.id === 'save') {
          $('#editor-autosave-pill').removeClass('is-saving');
        }
      });
      ARQ.bus.on(ARQ.EVENTS.OP_ERROR, function (p) {
        if (!p) return;
        if (criticalActive && (!criticalId || p.id === criticalId)) hideCritical();
        if (p.id === 'save') {
          $('#editor-autosave-pill').removeClass('is-saving');
        }
        var msg = p.error || 'Error';
        if (msg && ARQ.bus.emit) {
          ARQ.bus.emit(ARQ.EVENTS.TOAST, msg);
        }
      });
      ARQ.bus.on(ARQ.EVENTS.OP_CANCELLED, function (p) {
        if (p && criticalId === p.id) hideCritical();
      });
    },
  };
})(typeof window !== 'undefined' ? window : this);
