(function () {
  "use strict";

  function getItems(container) {
    return Array.from(container.querySelectorAll('.pdf-gallery-item'));
  }

  function sortDomItems(container, by, dir) {
    const items = getItems(container);
    if (!items.length) return;

    // Restore server order
    if (!by || by === 'none') {
      items
        .sort((a, b) => {
          const ia = parseInt(a.getAttribute('data-original-index') || '0', 10);
          const ib = parseInt(b.getAttribute('data-original-index') || '0', 10);
          return ia - ib;
        })
        .forEach((it) => container.appendChild(it));
      return;
    }

    const factor = (dir || 'asc').toLowerCase() === 'desc' ? -1 : 1;
    const keyFn = (el) => {
      if (by === 'title') {
        const t = el.querySelector('.pdf-title');
        return (t && (t.getAttribute('title') || t.textContent) || '').trim().toLowerCase();
      }
      if (by === 'filename') {
        const u = el.getAttribute('data-url') || '';
        return u.split('/').pop().toLowerCase();
      }
      return '';
    };

    items
      .sort((a, b) => {
        const ka = keyFn(a);
        const kb = keyFn(b);
        if (ka < kb) return -1 * factor;
        if (ka > kb) return 1 * factor;
        // stable fallback
        const ia = parseInt(a.getAttribute('data-original-index') || '0', 10);
        const ib = parseInt(b.getAttribute('data-original-index') || '0', 10);
        return ia - ib;
      })
      .forEach((it) => container.appendChild(it));
  }

  function initContainer(wrapper) {
    const container = wrapper.querySelector('.pdf-gallery-container');
    if (!container) return;

    const controls = wrapper.querySelector('.pdf-gallery-controls');
    if (!controls) return;

    const selBy = controls.querySelector('.pdf-gallery-sort-by');
    const selOrder = controls.querySelector('.pdf-gallery-sort-order');
    const btnReset = controls.querySelector('.pdf-gallery-reset');

    // Tag original order (server-authoritative) so "Reset" can restore it.
    getItems(container).forEach((it, idx) => {
      if (!it.hasAttribute('data-original-index')) {
        it.setAttribute('data-original-index', String(idx));
      }
    });

    const initialBy = (container.getAttribute('data-order-by') || 'none').toLowerCase();
    const initialDir = (container.getAttribute('data-order') || 'asc').toLowerCase();

    if (selBy) selBy.value = initialBy;
    if (selOrder) selOrder.value = initialDir;

    // Apply initial sorting (if any)
    sortDomItems(container, initialBy, initialDir);

    function applyFromControls() {
      const by = (selBy && selBy.value) ? selBy.value : 'none';
      const dir = (selOrder && selOrder.value) ? selOrder.value : 'asc';
      sortDomItems(container, by, dir);
    }

    if (selBy) selBy.addEventListener('change', applyFromControls);
    if (selOrder) selOrder.addEventListener('change', applyFromControls);

    if (btnReset) {
      btnReset.addEventListener('click', () => {
        if (selBy) selBy.value = initialBy;
        if (selOrder) selOrder.value = initialDir;
        sortDomItems(container, initialBy, initialDir);
      });
    }
  }

  document.addEventListener('DOMContentLoaded', function () {
    const wrappers = document.querySelectorAll('.pdf-gallery-wrapper');
    wrappers.forEach(initContainer);
  });
})();
