<?php if(count($args['categories']) > 1) { ?>
    <div class="productCategorySelector">
        <div class="header">
            <h3>
                <?php echo $args['currentCategoryName']; ?>
            </h3>
        </div>
        <div class="content" style="margin-top:10px;">
            <ul>
            <?php foreach($args['categories'] as $item) {
                if($item['name'] != $args['currentCategoryName']){ ?>
                    <li>
                        <a href="<?php echo $item['link'] ?>"><?php echo $item['name']; ?></a>
                    </li>
                <?php } 
            } ?>
            </ul>
        </div>
    </div>
<?php } ?>

<div class="productSearch">
    <div class="header">
        <h3>
            Affiner la recherche<br />
            <!--<span class="nbrProduct"><?php echo $args['nbrProducts']; ?> Produits</span>-->
        </h3>
    </div>
    <div class="content" style="margin-top:10px;">
        <div class="searchCriterias" style="display:none;">
            <h3>Critères de recherche</h3>
            <ul class="content">
            </ul>
        </div>

        <input type="hidden" name="pageUrl" value="<?php echo $args["pageUrl"] ?>" />
        <input type="hidden" name="ajaxUrl" value="<?php echo $args["ajaxUrl"] ?>" />
        <form method="GET" class="productSearchForm">
            <input type="hidden" name="product_cat" value="<?php echo $args['productCategory']; ?>" />
            <div class="formRow">
                <label>Sexe</label>
                <select name="sex">
                    <option value=""><?php echo __("Tous", "twcommerce") ?></option>
                    <?php foreach($args['customTaxonomies']['pa_sex'] as $slug => $name) { ?>
                        <?php if(isset($args['params']['sex']) &&  $args['params']['sex'] == $slug) { ?>
                            <option selected="selected" value="<?php echo $slug; ?>"><?php echo $name; ?></option>
                        <?php } else { ?>
                            <option value="<?php echo $slug; ?>"><?php echo $name; ?></option>
                        <?php } ?>
                    <?php } ?>
                </select>
            </div>

            <div class="formRow">
                <label>Taille</label>
                <select name="size">
                    <option value=""><?php echo __("Toutes", "twcommerce") ?></option>
                    <?php foreach($args['customTaxonomies']['pa_size'] as $slug => $name) { ?>
                        <?php if(isset($args['params']['size']) && $args['params']['size'] == $slug) { ?>
                            <option selected="selected" value="<?php echo $slug; ?>"><?php echo $name; ?></option>
                        <?php } else { ?>
                            <option value="<?php echo $slug; ?>"><?php echo $name; ?></option>
                        <?php } ?>
                    <?php } ?>
                </select>
            </div>

            <div class="formRow">
                <label>Marque</label>
                <select name="brand">
                    <option value=""><?php echo __("Toutes", "twcommerce") ?></option>
                    <?php foreach($args['customAttributes']['_productattribute_brand'] as $name) { ?>
                        <?php if(isset($args['params']['brand']) && $args['params']['brand'] == $name) { ?>
                            <option selected="selected" value="<?php echo $name; ?>"><?php echo $name; ?></option>
                        <?php } else { ?>
                            <option value="<?php echo $name; ?>"><?php echo $name; ?></option>
                        <?php } ?>
                    <?php } ?>
                </select>
            </div>

            <div class="formRow priceFormRow">
                <label>Prix</label>

                <div id="productPriceSliderContainer" style="display:none;">
                    <input type="text" name="price" id="productPriceSlider" />
                    <div id="productPriceSliderDetail">
                        <label><span class="min">
                            <?php
                                if(isset($args['params']['priceMin'])){ 
                                    echo $args['params']['priceMin'];
                                } else {
                                    echo $args['min'];
                                }
                            ?>
                            </span> €</label>
                        <label> - </label>
                        <label><span class="max">
                            <?php
                                if(isset($args['params']['priceMax'])){ 
                                    echo $args['params']['priceMax'];
                                } else {
                                    echo $args['max'];
                                }
                            ?>
                        </span> €</label>
                    </div>
                </div>
            </div>

            <!--<button type="submit">Rechercher</button>-->
        </form>
    </div>
</div>

<script type="text/javascript">
    /**
     * 
     * Quand on modifie le form (à voir pour les catégories)
on prends l'url courante auquel on enlève tous les param et la page
on réapplique les params en ajax

on réinjecte le contenu du widget dans la structure de la page

quand on clique sur un lien 
on appelle la page et on réinjecte son contenu en ajax
l'élement en question est productLoopGrid
     * 
     */
    document.addEventListener("DOMContentLoaded", function(event) {
        let formIsSubmitting = false; 
        let searchCriterias = {};
        let initialParams = JSON.parse(<?php echo "'" . json_encode($args['params'], JSON_HEX_QUOT|JSON_HEX_APOS) . "'"; ?>);
        const min = <?php echo $args['min'] ?>;
        const max = <?php echo $args['max'] ?>;

        function submitForm()
        {   
            const form = document.querySelector('.productSearchForm');
            const currentUrl = window.location.href;
            let ajaxUrl = "/wp-admin/admin-ajax.php?action=ajax_product_search";
            let params = tw_serialize_form_data(new FormData(form));

            Object.keys(params).forEach((key) => {
                ajaxUrl += '&' + key + '=' + encodeURIComponent(params[key]);
            });

            formIsSubmitting = true;
            fetch(ajaxUrl, {
                method: "GET"
            }).then(function(resp){
                resp.text().then((htmlContent) => {
                    document.querySelector('.productListColumn .productLoopGrid').innerHTML = htmlContent;
                    hasSubmittedForm = true;
                });

                /*
                let urlParser = new URL(currentUrl);;
                let searchParameters = new URLSearchParams();
                let browserUrl = urlParser.protocol + '//' + urlParser.hostname + urlParser.pathname;

                Object.keys(params).forEach((key) => {
                    searchParameters.append(key, params[key]);
                });
                browserUrl = browserUrl +  '?' + searchParameters.toString();

                history.replaceState(null, "", browserUrl);
                */
                formIsSubmitting = false;
            });
        }

        function initSearchCriterias()
        { 
            if(typeof(initialParams['price']) != "undefined") {
                const selectedPriceMin = parseInt(initialParams['price'].split(',')[0]);
                const selectedPriceMax = parseInt(initialParams['price'].split(',')[1]);
                searchCriterias['price'] = {'type':'range', 'label':'Prix', 'key':'price', 'title':'price', 'min':selectedPriceMin, 'max':selectedPriceMax};

                delete initialParams['priceMin'];
                delete initialParams['priceMax'];
                delete initialParams['price'];
            }

            Object.keys(initialParams).forEach((paramName) => {
                if(paramName != "product_cat") {
                    const elem = document.querySelector('.productSearchForm [name="' + paramName + '"]');
                    let label = elem.closest('.formRow').querySelector('label').textContent;

                    searchCriterias[paramName] = {'key': paramName, 'label':label, 'title':paramName, 'value':initialParams[paramName]};
                }
            });
            renderSearchCriterias();
        }
        initSearchCriterias();

        function renderSearchCriterias()
        {
            let container = document.querySelector('.productSearch .searchCriterias ul');
            container.innerHTML = "";

            let criteriaKeys = Object.getOwnPropertyNames(searchCriterias);
            if(criteriaKeys.length < 1) {
                container.closest('.searchCriterias').style.display = "none";
            } else {
                container.closest('.searchCriterias').style.display = "block";
                Object.entries(searchCriterias).forEach((crit) => {
                    container.insertAdjacentHTML('beforeend', '<li>' + crit[1].label + '<span data-key="' + crit[1].key + '" class="remove"><i class="fa-solid fa-xmark fa-fw"></i></span></li>');
                });
            }

            document.querySelectorAll('.productSearch .searchCriterias .remove').forEach((item) => {
                item.removeEventListener('click', clearSearchCriterias);
                item.addEventListener('click', clearSearchCriterias);
            });
        }

        function clearSearchCriterias(event)
        {
            const criteriaKey = event.currentTarget.getAttribute('data-key');
            const criteriaValue = searchCriterias[criteriaKey];
            let criteriaElement = document.querySelector('.productSearch [name="' + criteriaKey + '"]');

            if(typeof(criteriaValue['type']) == "undefined" || criteriaValue['type'] != "range") {
                const tagName = criteriaElement.tagName;
                if(tagName == "SELECT") {
                    const firstOptionValue = criteriaElement.querySelectorAll('option')[0].value;
                    criteriaElement.value = firstOptionValue;
                } else {
                    criteriaElement.value = "";
                }

                delete searchCriterias[criteriaKey];
                renderSearchCriterias();
                criteriaElement.dispatchEvent(new Event('change'));
            } else {
                document.querySelector('#productPriceSlider').value = min + "," + max;
                productPriceSlider.setValues(min,max);

                document.querySelector('#productPriceSliderDetail .min').innerHTML = min;
                document.querySelector('#productPriceSliderDetail .max').innerHTML = max;

                delete searchCriterias[criteriaKey];
                renderSearchCriterias();
            }
        }

        document.querySelector('#productPriceSliderContainer').style.display = "block";

        let priceMin = min;
        <?php if(isset($args['params']['priceMin']) && !empty($args['params']['priceMin'])) { ?>
            priceMin = <?php echo $args['params']['priceMin'] ?>;
        <?php } ?>

        let priceMax = max;
        <?php if(isset($args['params']['priceMax']) && !empty($args['params']['priceMax'])) { ?>
            priceMax = <?php echo $args['params']['priceMax'] ?>;
        <?php } ?>

        //TODO probleme rangeslider recharge la page tout seul
        //http://local.boutiquerando.fr/categorie-produit/vetement/page/3/

        //TOOD réécrire proprement les urls a partir de leur base et des params dans le replacestate
        let productPriceSlider = new rSlider({
            target: '#productPriceSlider',
            values: {min: min, max: max},
            step:50,
            range: true,
            tooltip: false,
            scale: true,
            labels: false,
            set: [priceMin, priceMax],
            onChange: function(values, hasBeenManuallyAdjusted){     
                if(!hasBeenManuallyAdjusted) {
                    return;
                }
                
                const selectedPriceMin = parseInt(values.split(',')[0]);
                const selectedPriceMax = parseInt(values.split(',')[1]);

                document.querySelector('#productPriceSliderDetail .min').innerHTML = selectedPriceMin;
                document.querySelector('#productPriceSliderDetail .max').innerHTML = selectedPriceMax;

                const inputName = "price";
                if(typeof(searchCriterias[inputName]) != "undefined") {
                    delete searchCriterias[inputName];
                }

                if(selectedPriceMin != min || selectedPriceMax != max) {
                    searchCriterias[inputName] = {'type':'range', 'label':'Prix', 'key':inputName, 'title':inputName, 'min':selectedPriceMax, 'max':selectedPriceMax};
                }
                renderSearchCriterias();
                submitForm();
            }
        });

        document.querySelectorAll('.productSearchForm select').forEach((item) => {
            item.addEventListener('change', (e) => {
                const inputName = e.target.getAttribute('name');
                const inputLabel = e.target.closest('.formRow').querySelector('label').textContent;
                const inputValue = e.target.value;
                if(typeof(searchCriterias[inputName]) != "undefined") {
                    delete searchCriterias[inputName];
                }

                if(typeof(inputValue) != "undefined" && inputValue.trim() != "") {
                    searchCriterias[inputName] = {'key': inputName, 'label': inputLabel, 'title':inputName, 'value': inputValue};
                }
                renderSearchCriterias();
                submitForm();
            })
        });

        document.querySelector('.productListColumn').addEventListener('click', (event) => {
            let target = event.srcElement;
            let isPaginationLink = false;

            if(typeof(target.closest('.elementor-pagination')) != "undefined" && target.closest('.elementor-pagination') !== null) {       
                let link = target.getAttribute('href');
                const pageUrl = document.querySelector('input[name="pageUrl"]').value;
                const ajaxUrl = document.querySelector('input[name="ajaxUrl"]').value;

                let urlParser = new URL(link);
                let pageFromUrl = null;
                let basePath = null;

                let pageIndex = urlParser.pathname.indexOf('/page/');
                if(pageIndex != -1) {
                    let diff = urlParser.pathname.length - pageIndex;
                    pageFromUrl = urlParser.pathname.substr(pageIndex, diff);
                    pageFromUrl = pageFromUrl.replace('/page/', '');
                    pageFromUrl = pageFromUrl.replace('/', '');
                    basePath = urlParser.pathname.substr(0, pageIndex);

                    urlParser.searchParams.append("page", pageFromUrl);
                }

                let ajaxUrlParser = new URL(ajaxUrl);
                urlParser.searchParams.forEach((value,key) => {
                    ajaxUrlParser.searchParams.append(key, value);
                });

                link = ajaxUrlParser.href;

                console.log('----------------');
                console.log(link);

                if(link !== null) {
                    fetch(link, {
                        method: "GET"
                    }).then(function(resp){
                        resp.text().then((htmlContent) => {
                            document.querySelector('.productListColumn .productLoopGrid').innerHTML = htmlContent;
                        });

                        /*
                        const browserHistoryUrl = target.getAttribute('href');
                        history.replaceState(null, "",browserHistoryUrl);
                        */
                    });
                }

                event.preventDefault();
                event.stopPropagation();
                return false;
            }
        });
    });
</script>