const ui_filters = document.querySelectorAll('.ui-filter-button');
ui_filters.forEach(filter => {
    const filterElement = document.querySelector(`#${filter.dataset.element}`);
    if (!filterElement.classList.contains('hidden')) {
        filter.classList.replace('far', 'fas');
    }
    filter.addEventListener("click", function () {
        const url = new URL(window.location.href);
        const keyAttrib = this.dataset.element + '--filter';
        url.searchParams.delete(keyAttrib);
        if (this.classList.contains('far')) {
            // Open filter options
            this.classList.replace('far', 'fas');
            url.searchParams.set(keyAttrib, 1);
        } else {
            // Close filter options
            this.classList.replace('fas', 'far');
            url.searchParams.set(keyAttrib, 0);
        }
        const newUrl = url.href;
        window.history.pushState({ path: newUrl }, '', newUrl);
    });
});

const DUEL_SCREEN_RESIZER = 1395;
const resizers = document.querySelectorAll('[data-resizer]');
if (resizers.length > 0) {
    window.addEventListener("resize", function () {
        // Remove the custom styling if the screen 
        const screenWidth = window.innerWidth;
        const duelParent = document.querySelector('.ui-panel-duel-resizeable')
        console.warn(duelParent);
        if (duelParent !== null) {
            if (screenWidth <= DUEL_SCREEN_RESIZER && duelParent.hasAttribute('style')) {
                duelParent.removeAttribute('style');
            }
        }
    });
    resizers.forEach(resizer => {
        resizer.addEventListener("mousedown", function (e) {
            const parent = this.parentElement
            const left = parent.children[0];
            const right = parent.children[2];

            const leftStyles = window.getComputedStyle(left);
            const leftWidth = parseInt(leftStyles.width, 10);

            const rightStyles = window.getComputedStyle(right);
            const rightWidth = parseInt(rightStyles.width, 10);

            const x = e.clientX;

            const mouseMoveHandler = function (ev) {
                // How far the mouse has been moved
                const dx = ev.clientX - x;
                parent.style.gridTemplateColumns = `calc(${leftWidth}px + ${dx}px) 2px calc(${rightWidth}px - ${dx}px)`;
            };

            const mouseUpHandler = function () {
                document.removeEventListener('mousemove', mouseMoveHandler);
                document.removeEventListener('mouseup', mouseUpHandler);
            };

            document.addEventListener('mousemove', mouseMoveHandler);
            document.addEventListener('mouseup', mouseUpHandler);
        });
    });
}
