<style type="text/css">
  .bulk-action-bar {
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 10px 14px;
    margin-bottom: 10px;
    background: #fff3cd;
    border: 1px solid #ffc107;
    border-radius: 4px;
  }

  .bulk-action-bar__info {
    font-weight: 600;
    color: #856404;
  }

  .table-col-bulk-check {
    width: 36px;
    padding-left: 10px !important;
    padding-right: 10px !important;
  }

  .product-archive-thumb-wrap {
    display: inline-block;
  }

  .product-archive-thumb-image {
    width: 72px;
    height: 42px;
    object-fit: cover;
    border-radius: 4px;
    cursor: zoom-in;
  }

  .product-archive-thumb-popup {
    position: fixed;
    top: 0;
    left: 0;
    width: min(70vw, 760px);
    max-height: 80vh;
    padding: 6px;
    border-radius: 6px;
    background: #fff;
    box-shadow: 0 14px 30px rgba(0, 0, 0, .35);
    z-index: 3000;
    opacity: 0;
    visibility: hidden;
    pointer-events: none;
    transition: opacity .1s ease;
  }

  .product-archive-thumb-popup.is-visible {
    opacity: 1;
    visibility: visible;
  }

  .product-archive-thumb-popup img {
    display: block;
    width: 100%;
    max-height: calc(80vh - 12px);
    object-fit: contain;
    border-radius: 4px;
  }
</style>

<script type="text/javascript">
  (function($) {
    if (!$) {
      return;
    }

    $('.product-archive-thumb-popup').remove();
    var $popup = $('<div class="product-archive-thumb-popup" aria-hidden="true"><img src="" alt=""></div>');
    var $popupImage = $popup.find('img');
    $('body').append($popup);

    function positionPopup(event) {
      var offset = 18;
      var viewportWidth = $(window).width();
      var viewportHeight = $(window).height();
      var popupWidth = $popup.outerWidth();
      var popupHeight = $popup.outerHeight();
      var left = (event.clientX || 0) + offset;
      var top = (event.clientY || 0) + offset;

      if (left + popupWidth + 12 > viewportWidth) {
        left = Math.max(12, (event.clientX || 0) - popupWidth - offset);
      }

      if (top + popupHeight + 12 > viewportHeight) {
        top = Math.max(12, viewportHeight - popupHeight - 12);
      }

      $popup.css({ left: left + 'px', top: top + 'px' });
    }

    $(document).off('.productArchiveThumbPopup');

    $(document).on('mouseenter.productArchiveThumbPopup', '.js-product-archive-thumb-preview', function(event) {
      var src = $(this).data('previewSrc');
      if (!src) {
        return;
      }

      $popupImage.attr('src', String(src));
      $popup.addClass('is-visible');
      positionPopup(event);
    });

    $(document).on('mousemove.productArchiveThumbPopup', '.js-product-archive-thumb-preview', function(event) {
      if ($popup.hasClass('is-visible')) {
        positionPopup(event);
      }
    });

    $(document).on('mouseleave.productArchiveThumbPopup', '.js-product-archive-thumb-preview', function() {
      $popup.removeClass('is-visible');
      $popupImage.attr('src', '');
    });

    // --- Bulk select ---
    var $table = $('.table-list-table');
    var $bar   = $('#js-bulk-action-bar');
    var $label = $bar.find('.js-bulk-count-label');

    // Inject select-all checkbox into _checkbox column header
    $table.find('thead th.table-col-bulk-check').html(
      '<input type="checkbox" id="js-bulk-select-all" title="Zaznacz wszystkie">'
    );

    function updateBar() {
      var count = $table.find('.js-bulk-check:checked').length;
      if (count > 0) {
        $label.text('Zaznaczono: ' + count);
        $bar.show();
      } else {
        $bar.hide();
      }
    }

    $(document).on('change.bulkSelect', '#js-bulk-select-all', function() {
      var checked = $(this).is(':checked');
      $table.find('.js-bulk-check').prop('checked', checked);
      updateBar();
    });

    $(document).on('change.bulkSelect', '.js-bulk-check', function() {
      var total   = $table.find('.js-bulk-check').length;
      var checked = $table.find('.js-bulk-check:checked').length;
      $('#js-bulk-select-all').prop('indeterminate', checked > 0 && checked < total);
      $('#js-bulk-select-all').prop('checked', checked === total && total > 0);
      updateBar();
    });

    $(document).on('click.bulkDelete', '.js-bulk-delete-btn', function() {
      var ids = [];
      $table.find('.js-bulk-check:checked').each(function() {
        ids.push($(this).val());
      });
      if (ids.length === 0) {
        return;
      }

      var confirmMsg = 'UWAGA! Operacja nieodwracalna!\n\n'
        + 'Wybrane produkty (' + ids.length + ' szt.) zostaną trwale usunięte razem ze wszystkimi zdjęciami i załącznikami z serwera.\n\n'
        + 'Czy na pewno chcesz usunąć zaznaczone produkty?';

      var doDelete = function() {
        var $btn = $('.js-bulk-delete-btn');
        $btn.prop('disabled', true).text('Usuwanie…');

        var formData = [];
        for (var i = 0; i < ids.length; i++) {
          formData.push('ids%5B%5D=' + encodeURIComponent(ids[i]));
        }

        $.ajax({
          url: '/admin/product_archive/bulk_delete_permanent/',
          type: 'POST',
          data: formData.join('&'),
          contentType: 'application/x-www-form-urlencoded',
          dataType: 'json',
          success: function(resp) {
            if (resp && resp.deleted > 0) {
              window.location.reload();
            } else {
              alert('Nie udało się usunąć produktów. Spróbuj ponownie.');
              $btn.prop('disabled', false).html('<i class="fa fa-trash-o"></i> Usuń zaznaczone trwale');
            }
          },
          error: function() {
            alert('Błąd podczas usuwania produktów. Spróbuj ponownie.');
            $btn.prop('disabled', false).html('<i class="fa fa-trash-o"></i> Usuń zaznaczone trwale');
          }
        });
      };

      if (typeof $.confirm === 'function') {
        $.confirm({
          title: 'Potwierdzenie',
          content: confirmMsg,
          type: 'red',
          boxWidth: '560px',
          useBootstrap: false,
          animation: 'scale',
          closeAnimation: 'scale',
          backgroundDismissAnimation: 'shake',
          container: 'body',
          theme: 'modern',
          columnClass: '',
          typeAnimated: true,
          lazyOpen: false,
          draggable: false,
          closeIcon: true,
          containerFluid: true,
          escapeKey: true,
          backgroundDismiss: true,
          buttons: {
            cancel: {
              text: 'Anuluj',
              btnClass: 'btn-default'
            },
            confirm: {
              text: 'Tak, usuń trwale',
              btnClass: 'btn-danger',
              action: doDelete
            }
          }
        });
      } else if (window.confirm(confirmMsg)) {
        doDelete();
      }
    });
  })(window.jQuery);
</script>
