class SortBy {
    constructor(dataStore) {
        this.dataStore = dataStore;
        this.sortByElement = null;
        this.sortOptions = [
            { field: 'advertise_price', order: 'asc', label: 'Price: Low to High' },
            { field: 'advertise_price', order: 'desc', label: 'Price: High to Low' },
            { field: 'year', order: 'asc', label: 'Year: Low to High' },
            { field: 'year', order: 'desc', label: 'Year: High to Low' },
            { field: 'make', order: 'asc', label: 'Make Name: A to Z' },
            { field: 'make', order: 'desc', label: 'Make Name: Z to A' },
            { field: 'model', order: 'asc', label: 'Model Name: A to Z' },
            { field: 'model', order: 'desc', label: 'Model Name: Z to A' },
            { field: 'finance', order: 'asc', label: 'Finance: Low to High' },
            { field: 'finance', order: 'desc', label: 'Finance: High to Low' }
        ];
        this.init();
    }

    init() {
        // Get the ul element
        const sortOptionsList = document.getElementById('sort-options-list');

        // Dynamically create list items
        this.sortOptions.forEach(option => {
            const listItem = document.createElement('li');
            listItem.className = 'mdc-list-item';
            listItem.setAttribute('aria-selected', 'false');
            listItem.setAttribute('data-value', JSON.stringify([option.field, option.order])); // Use field and order properties

            const rippleSpan = document.createElement('span');
            rippleSpan.className = 'mdc-list-item__ripple';

            const textSpan = document.createElement('span');
            textSpan.className = 'mdc-list-item__text';
            textSpan.textContent = option.label; // Use label property

            listItem.appendChild(rippleSpan);
            listItem.appendChild(textSpan);

            sortOptionsList.appendChild(listItem);
        });


        this.sortByElement = new mdc.select.MDCSelect(document.querySelector('#order-by'));

        this.sortByElement.listen('MDCSelect:change', this.handleSortChange.bind(this));
    }

    handleSortChange(event) {

        const selectedOption = this.sortByElement.value;
        if (selectedOption) {
            const [sortBy, order] = JSON.parse(selectedOption);
            if (sortBy === 'finance') {
                this.dataStore.sortByFinance(order);
            } else {
                this.dataStore.sortBy(sortBy, order);
            }
            this.dataStore.sortBy(sortBy, order);
        }


        
    }
}
