require(['jquery', 'Magento_Customer/js/customer-data'], function($, customerData) {
const productGrid = $('#product-card-grid');
const sortBySelect = $('#sorter');
const dirInput = $('#sort-dir');
const arrowSpan = $('#sort-arrow');
const sortToggle = $('#sort-toggle');
const productCards = productGrid.children('.product-card').toArray();
function updateArrowClass(dir) {
sortToggle.removeClass('sort-asc sort-desc');
if (dir === 'asc') {
sortToggle.addClass('sort-asc');
arrowSpan.text('↑ ASC');
} else {
sortToggle.addClass('sort-desc');
arrowSpan.text('↓ DESC');
}
}
function sortProducts(sortBy, sortDir) {
productCards.sort(function(a, b) {
let aValue, bValue;
if (sortBy === 'name') {
aValue = $(a).find('.product-name').text().toLowerCase();
bValue = $(b).find('.product-name').text().toLowerCase();
return sortDir === 'asc' ? aValue.localeCompare(bValue) : bValue.localeCompare(aValue);
} else if (sortBy === 'price') {
const priceRegex = /\$([\d,\.]+)/;
aValue = $(a).find('.now-price').text().match(priceRegex);
bValue = $(b).find('.now-price').text().match(priceRegex);
aValue = aValue ? parseFloat(aValue[1].replace(/,/g, '')) : 0;
bValue = bValue ? parseFloat(bValue[1].replace(/,/g, '')) : 0;
return sortDir === 'asc' ? aValue - bValue : bValue - aValue;
} else {
return 0;
}
});
productGrid.empty();
productCards.forEach(card => productGrid.append(card));
}
sortBySelect.on('change', function() {
const sortBy = sortBySelect.val();
const dir = dirInput.val();
sortProducts(sortBy, dir);
});
sortToggle.on('click', function(e) {
e.preventDefault();
const newDir = dirInput.val() === 'asc' ? 'desc' : 'asc';
dirInput.val(newDir);
updateArrowClass(newDir);
const sortBy = sortBySelect.val();
sortProducts(sortBy, newDir);
});
updateArrowClass(dirInput.val());
$('.product-listing-wrapper').on('submit', '.ajax-add-to-cart', function(e) {
e.preventDefault();
e.stopPropagation();
const $form = $(this);
const formData = $form.serialize();
$.ajax({
url: 'https://www.easternserenity.com/checkout/cart/add/',
type: 'POST',
data: formData,
success: function(res) {
customerData.reload(['cart'], true);
alert('✅ Product added to cart!');
},
error: function(xhr) {
alert('❌ Failed to add product to cart');
console.error(xhr.responseText);
}
});
});
});