import { athenaConfigOptions } from '../../global/athena-config.js';
import { handleHtml } from '../../global/helpers/athena-global-helper.js';

/**
 * Append View Mode
 *
 * @param viewMode
 * @param products
 */
function appendViewMode(viewMode, products) {
    athenaConfigOptions.viewModeContainer.innerHTML = '';
    //Get witch athena view mode is active
    const viewModeActive =  localStorage.getItem('athena-view-mode');
    if(products.length > 0) {
        viewMode.forEach((item) => {
            //Get witch athena view mode is active
            const viewModeActive =  localStorage.getItem('athena-view-mode') ? localStorage.getItem('athena-view-mode') : item.selected ? item.option_value : '';

            athenaConfigOptions.viewModeContainer.append(
                handleHtml(`
                    <div class="view-mode${viewModeActive === item.option_value ? ' active-view-mode' : ''}">
                        <span data-view-mode='${item.option_value}'>
                            ${item.option_label}
                        </span>
                    </div>
                `, '.view-mode')
            );


            if(localStorage.getItem('athena-view-mode')) {
                athenaConfigOptions.productsWrapper?.classList.add(localStorage.getItem('athena-view-mode'));
            } else if(item.selected) {
                athenaConfigOptions.productsWrapper?.classList.add(item.option_value);
            }
        });

        let viewModeBtn = athenaConfigOptions.viewModeContainer.querySelectorAll(`.view-mode span`);
        viewModeBtn.forEach((element) =>{
           element.addEventListener('click', () => {

               //Add or Remove Class Based on the Click
               Array.from(athenaConfigOptions.viewModeContainer.children).map(child => {
                    child?.classList.contains('active-view-mode') ? child?.classList.remove('active-view-mode') : '';
               });
               element.parentElement?.classList.add('active-view-mode');

               athenaConfigOptions.productsWrapper?.classList.remove('grid');
               athenaConfigOptions.productsWrapper?.classList.remove('list');
               athenaConfigOptions.productsWrapper?.classList.add(element.getAttribute('data-view-mode'));
               localStorage.setItem('athena-view-mode', element.getAttribute('data-view-mode'));
           })
        });
    }
}

//Exporting all Functions
export {
    appendViewMode
}