(function () {
  'use strict';

  function bind(btn) {
    if (btn.dataset.confirmBound === '1') return;
    btn.dataset.confirmBound = '1';

    btn.addEventListener('click', function () {
      var form = btn.closest('form');
      if (!form) return;

      var title = form.getAttribute('data-confirm-title') || 'Usun pozycje';
      var message = form.getAttribute('data-confirm-message') || 'Czy na pewno chcesz usunac ten wpis?';

      if (window.OrderProAlerts && typeof window.OrderProAlerts.confirm === 'function') {
        var submitted = false;
        var doSubmit = function () {
          if (submitted) return;
          submitted = true;
          form.submit();
        };
        var result = window.OrderProAlerts.confirm({
          title: title,
          message: message,
          danger: true,
          confirmLabel: 'Usun',
          onConfirm: doSubmit
        });
        if (result && typeof result.then === 'function') {
          result.then(function (ok) { if (ok) doSubmit(); });
        }
      } else if (window.confirm(message)) {
        form.submit();
      }
    });
  }

  function init() {
    document.querySelectorAll('.js-delete-btn').forEach(bind);
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', init);
  } else {
    init();
  }
})();
