(function () {
  'use strict';

  var progress = document.querySelector('[data-scan-progress]');
  if (progress) {
    var fallback = progress.querySelector('.fallback');
    if (fallback) fallback.hidden = true;
    var running = false;
    var step = function () {
      if (running) return;
      running = true;
      var body = new URLSearchParams();
      body.set('csrf', progress.getAttribute('data-csrf'));
      fetch(progress.getAttribute('data-step-url'), {
        method: 'POST',
        credentials: 'same-origin',
        headers: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
        body: body.toString()
      }).then(function (response) {
        return response.json().then(function (data) {
          if (!response.ok) throw new Error(data.message || 'No se pudo continuar.');
          return data;
        });
      }).then(function (data) {
        var state = data.progress;
        progress.querySelector('[data-current]').textContent = state.current;
        progress.querySelector('[data-percent]').textContent = state.percent + '%';
        progress.querySelector('[data-count]').textContent = state.done + ' de ' + state.total + ' fases';
        progress.querySelector('[data-progress-bar]').style.width = state.percent + '%';
        progress.querySelector('.progress-track').setAttribute('aria-valuenow', state.percent);
        if (state.complete) {
          window.location.reload();
          return;
        }
        running = false;
        window.setTimeout(step, 180);
      }).catch(function (error) {
        progress.querySelector('[data-current]').textContent = error.message + ' Usa el botón para reintentar.';
        running = false;
      });
    };
    step();
  }

  var filters = document.querySelectorAll('[data-filter]');
  if (filters.length) {
    Array.prototype.forEach.call(filters, function (button) {
      button.addEventListener('click', function () {
        var selected = button.getAttribute('data-filter');
        Array.prototype.forEach.call(filters, function (item) { item.classList.toggle('active', item === button); });
        Array.prototype.forEach.call(document.querySelectorAll('[data-kind]'), function (finding) {
          finding.hidden = selected !== 'all' && finding.getAttribute('data-kind') !== selected;
        });
      });
    });
  }
}());
