document.addEventListener('DOMContentLoaded', () => {
  // jede Tabelle separat behandeln
  document.querySelectorAll('.boxyfy-amz-table').forEach(wrapper => {
    const table      = wrapper.querySelector('table');
    if (!table) return;

    const tbody      = table.querySelector('tbody');
    const sortBtns   = wrapper.querySelectorAll('.tssort-btn');
    const resetBtns  = wrapper.querySelectorAll('.tsreset-btn');
    const original   = Array.from(tbody.children);      // Ursprungs-Reihenfolge

    /* sortieren --------------------------------------------------------- */
    sortBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        const order = btn.dataset.order;                // asc | desc
        [...tbody.children]
          .sort((a, b) => {
            const pa = parseFloat(a.dataset.price) || 0;
            const pb = parseFloat(b.dataset.price) || 0;
            return order === 'asc' ? pa - pb : pb - pa;
          })
          .forEach(row => tbody.appendChild(row));
        table.classList.add('sorted');
      });
    });

    /* zurücksetzen ------------------------------------------------------ */
    resetBtns.forEach(btn => {
      btn.addEventListener('click', () => {
        original.forEach(row => tbody.appendChild(row));
        table.classList.remove('sorted');
      });
    });
  });
});