document.addEventListener('DOMContentLoaded', () => {

    const overlayType = 'overlay';
    const activatorType = 'dialog-activator-';
    const contentType = 'dialog-content-';
    const closeType = 'dialog-close-';

    const overlay = document.querySelector(`[data-type=${overlayType}]`);

    const closeActiveContent = () => {
        const activeContent = document.querySelector(`[data-active=true][data-type^=${contentType}]`);
        if (activeContent) activeContent.dataset.active = 'false';
        if (overlay) overlay.dataset.active = 'false';
        document.body.style.overflow = 'auto';
    }

    document.addEventListener('click', () => {
        closeActiveContent();
    });

    const activators = document.querySelectorAll(`[data-type^=${activatorType}]`);
    activators.forEach(activator => {
        const key = activator.dataset.type.replace(activatorType, '');
        const content = document.querySelector(`[data-type=${contentType}${key}]`);
        const close = document.querySelector(`[data-type=${closeType}${key}]`);
        const zIndex = activator.dataset.overlayZ ?? '40';
        const scroll = (activator.dataset.dialogScroll ?? 'true') === 'true';

        if (activator) activator.addEventListener('click', (e) => {
            e.stopPropagation();

            if (content?.dataset.active === 'false') {
                closeActiveContent();
                if (content) content.dataset.active = 'true';
                if (overlay) {
                    overlay.dataset.active = 'true';
                    overlay.style.zIndex = zIndex;
                }
                if (!scroll) document.body.style.overflow = 'hidden';
                if (key === "searchbar-mobile") content.querySelector("input").focus();
            } else {
                closeActiveContent();
            }
        });

        if (content) content.addEventListener('click', (e) => {
            e.stopPropagation();
        });

        if (close) close.addEventListener('click', () => {
            closeActiveContent();
        });
    });
});

document.addEventListener('DOMContentLoaded', () => {

    const menuType = 'menu';
    const activatorType = 'menu-activator-';
    const contentType = 'menu-content-';

    const menu = document.querySelector(`[data-type^=${menuType}]`);
    if (!menu) return;

    const activators = menu.querySelectorAll(`[data-type^=${activatorType}]`);

    const activeItem = (index) => {
        const activator = activators[index];
        const key = activator.dataset.type.replace(activatorType, '');
        const content = menu.querySelector(`[data-type^=${contentType}${key}]`);

        if (activator.dataset.active === 'false') {
            const activeItem = menu.querySelector(`[data-active=true][data-type^=${activatorType}]`);
            const activeContent = menu.querySelector(`[data-active=true][data-type^=${contentType}]`);
            if (activeItem) activeItem.dataset.active = 'false';
            if (activeContent) activeContent.dataset.active = 'false';

            activator.dataset.active = 'true';
            content.dataset.active = 'true';
        }
    }

    for (let i = 0; i < activators.length; i++) {
        const activator = activators[i];
        activator.addEventListener('mouseenter', () => activeItem(i));

        // active first item
        if (i === 0) activeItem(i);
    }
});

document.addEventListener('DOMContentLoaded', () => {

    const menuType = 'menu-mobile';
    const activatorType = 'menu-activator-';
    const contentType = 'menu-content-';
    const backType = 'menu-back';

    const menu = document.querySelector(`[data-type=${menuType}]`);
    if (!menu) return;

    const back = menu.querySelector(`[data-type=${backType}]`);

    const activators = menu.querySelectorAll(`[data-type^=${activatorType}]`);

    let itemKeyPath = [];

    const activeItem = (index = undefined, key = undefined) => {
        if (!key) {
            const activator = activators[index];
            key = activator.dataset.type.replace(activatorType, '');
        }
        const content = menu.querySelector(`[data-type=${contentType}${key}]`);
        const depth = content.dataset.depth;

        if (content.dataset.state !== 'visible') {
            const visibleContent = menu.querySelector(`[data-state=visible][data-type^=${contentType}]`);
            const visibleDepth = visibleContent.dataset.depth;
            if (visibleContent && depth > visibleDepth) {
                visibleContent.dataset.state = 'back';
                itemKeyPath.push(visibleContent.dataset.type.replace(contentType, ''));
                back.dataset.active = 'true';
            }
            if (visibleContent && depth < visibleDepth) {
                visibleContent.dataset.state = 'invisible';
                itemKeyPath.pop();
                if (depth === '1') back.dataset.active = 'false';
            }
            content.dataset.state = 'visible';
        }
    }

    for (let i = 0; i < activators.length; i++) {
        const activator = activators[i];
        activator.addEventListener('click', () => activeItem(i));
    }

    const content = menu.querySelector(`[data-type=${contentType}0]`);
    content.dataset.state = 'visible';

    back.addEventListener('click', () => {
        activeItem(undefined, itemKeyPath[itemKeyPath.length - 1]);
    })
});

document.addEventListener('DOMContentLoaded', () => {

    const detailType = 'detail';
    const activatorType = 'detail-activator';
    const contentType = 'detail-content';

    const details = document.querySelectorAll(`[data-type=${detailType}]`);
    details.forEach(detail => {
        const activator = detail.querySelector(`[data-type=${activatorType}]`);
        const content = detail.querySelector(`[data-type=${contentType}]`);

        if (!activator || !content) return;

        activator.addEventListener('click', () => {
            if (activator.dataset.active === 'false') {
                activator.dataset.active = 'true';
                content.dataset.active = 'true';
            } else {
                activator.dataset.active = 'false';
                content.dataset.active = 'false';
            }
        });
    });
});

document.addEventListener('DOMContentLoaded', () => {

    const linkType = 'link';
    const formType = 'form';

    const links = document.querySelectorAll(`[data-type=${linkType}]`);
    links.forEach(link => {
        link.addEventListener('click', () => {
            const url = link.dataset.href;
            if (url) {
                window.history.pushState(undefined, "", url);
                window.location.reload();
            }
        });
    });

    const forms = document.querySelectorAll(`[data-type=${formType}]`);
    forms.forEach(form => {
        form.addEventListener('submit', (e) => {
            e.preventDefault();

            const url = new URL(form.action);
            const formData = new FormData(form);

            for (let [name, value] of formData.entries()) {
                url.searchParams.append(name, value);
            }

            window.history.pushState(undefined, "", url);
            window.location.reload();
        });
    });
});

function prepare_paginations(comment) {
    const commentsPaginationType = 'pagination-comments';
    const post_id = comment.dataset.postId;
    const paginations = comment.querySelectorAll(`[data-type=${commentsPaginationType}]`);

    paginations.forEach(pagination => {
        const page = pagination.dataset.page;
        pagination.addEventListener('click', async () => {
            if (comment.dataset.loading === 'true')
                return;

            const formData = new URLSearchParams();
            formData.append('action', 'ajax_comments');
            formData.append('security', ajax_comments_object.nonce);
            formData.append('page_number', page);
            formData.append('post_id', post_id);

            comment.dataset.loading = 'true';
            comment.scrollIntoView({behavior: 'smooth', block: 'start'});
            const response = await fetch(ajax_comments_object.url, {
                method: "POST",
                body: formData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            });
            comment.dataset.loading = 'false';

            if (!response.ok) {
                // TODO toast
                return;
            }

            const data = await response.json();
            const template = document.createElement('template');
            template.innerHTML = data.data.html;
            comment.innerHTML = template.content.firstElementChild.innerHTML;
            comment.offsetHeight; // Reflow trick
            prepare_paginations(comment);
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {

    const submitCommentType = 'submit-comment';
    const submitCommentErrorType = 'submit-comment-error';

    const commentsType = 'comments';

    const submitComments = document.querySelectorAll(`[data-type=${submitCommentType}]`);
    submitComments.forEach(submitComment => {
        const submitCommentError = submitComment.querySelector(`[data-type=${submitCommentErrorType}]`);

        submitComment.addEventListener('submit', async (e) => {
            e.preventDefault();
            if (submitComment.dataset.loading === 'true')
                return;

            submitComment.dataset.error = 'false';
            submitCommentError.innerText = '';

            const hasError = submitComment.querySelector(`[data-error=true]`);

            if (hasError) {
                submitComment.dataset.error = 'true';
                submitCommentError.innerText = hasError.dataset.message;
                return;
            }

            const formData = new URLSearchParams();
            formData.append('action', 'ajax_send_comment');
            formData.append('security', ajax_send_comment_object.nonce);

            const form = new FormData(submitComment);
            for (let [name, value] of form.entries()) {
                formData.append(name, value);
            }

            if (!formData.get('rate') && formData.get('post_type') === "Product") {
                submitComment.dataset.error = 'true';
                submitCommentError.innerText = 'امتیاز محصول را مشخص کنید.';
                return;
            }

            submitComment.dataset.loading = 'true';
            const response = await fetch(ajax_send_comment_object.url, {
                method: "POST",
                body: formData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            });

            submitComment.dataset.loading = 'false';
            const data = await response.json();

            if (data.success) {
                Toastify({
                    text: 'نظر شما ثبت شد.',
                    duration: 3000,
                    gravity: "top", // `top` or `bottom`
                    position: "center", // `left`, `center` or `right`
                    stopOnFocus: true, // Prevents dismissing of toast on hover
                    style: {
                        background: "var(--color-green-500)",
                        borderRadius: "8px",
                        fontSize: "var(--text-body-s)"
                    }
                }).showToast();

                submitComment.reset();
                submitComment.dataset.error = 'false';
            } else {
                Toastify({
                    text: data.data,
                    duration: 3000,
                    gravity: "top", // `top` or `bottom`
                    position: "center", // `left`, `center` or `right`
                    stopOnFocus: true, // Prevents dismissing of toast on hover
                    style: {
                        background: "var(--color-red-500)",
                        borderRadius: "8px",
                        fontSize: "var(--text-body-s)"
                    }
                }).showToast();
            }
        });
    });

    const comments = document.querySelectorAll(`[data-type=${commentsType}]`);
    comments.forEach(comment => {
        prepare_paginations(comment);
    });
});

document.addEventListener('DOMContentLoaded', () => {

    const inputBoxType = 'input-box';
    const inputBoxClearType = 'input-box-clear';
    const inputRequiredType = 'input-required';
    const inputEmailType = 'input-email';

    const inputBoxes = document.querySelectorAll(`[data-type=${inputBoxType}]`);
    inputBoxes.forEach(inputBox => {
        const clearButton = inputBox.querySelector(`[data-type=${inputBoxClearType}]`);
        const input = inputBox.querySelector('input') ?? inputBox.querySelector('textarea');
        if (clearButton)
            clearButton.addEventListener('click', () => {
                input.value = '';
            });
    });

    const inputRequiredList = document.querySelectorAll(`[data-type=${inputRequiredType}]`);
    inputRequiredList.forEach(inputRequired => {
        const check = () => {
            if (!inputRequired.value.trim()) {
                inputRequired.dataset.error = 'true';
                inputRequired.dataset.message = 'بخش‌های ستاره‌دار* الزامی است.';
            } else {
                inputRequired.dataset.error = 'false';
                inputRequired.dataset.message = '';
            }
        };
        inputRequired.addEventListener('input', check);
        check();
    });

    const inputEmails = document.querySelectorAll(`[data-type=${inputEmailType}]`);
    inputEmails.forEach(inputEmail => {
        inputEmail.addEventListener('input', () => {
            const regex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

            if (inputEmail.value && !regex.test(inputEmail.value)) {
                inputEmail.dataset.error = 'true';
                inputEmail.dataset.message = 'ایمیل وارد شده معتبر نیست.';
            } else {
                inputEmail.dataset.error = 'false';
                inputEmail.dataset.message = '';
            }
        });
    });
});


function setupHover() {
    const hoverType = 'hover';
    const overlayType = 'overlay';

    const overlay = document.querySelector(`[data-type=${overlayType}]`);

    const hovers = document.querySelectorAll(`[data-type^=${hoverType}]`);
    hovers.forEach(hover => {
        const zIndex = hover.dataset.overlayZ ?? '40';

        hover.addEventListener('mouseenter', (e) => {
            e.stopPropagation();
            if (hover.dataset.active === 'true') return;

            hover.dataset.active = 'true';
            overlay.dataset.active = 'true';
            overlay.style.zIndex = zIndex;

            document.addEventListener('mouseenter', () => {
                hover.dataset.active = 'false';
                overlay.dataset.active = 'false';
            }, {once: true});

            hover.addEventListener('mouseleave', () => {
                hover.dataset.active = 'false';
                overlay.dataset.active = 'false';
            }, {once: true});
        });

        hover.addEventListener("click", (e) => e.stopPropagation());
    });
}

function refreshCartQuantity() {
    const miniCartType = 'mini-cart';
    const quantityType = 'cart-quantity';
    const removeFromCartType = 'remove-from-cart';

    const miniCart = document.querySelector(`[data-type=${miniCartType}]`);
    if (!miniCart) return;

    const items = miniCart.querySelectorAll(`[data-type=${removeFromCartType}`);
    let count = 0;
    let productIds = [];
    items.forEach(item => {
        const productId = new FormData(item).get("product_id");
        productIds.push(productId);
        const quantity = new FormData(item).get("quantity");
        count += parseInt(quantity);
        const quantityItems = document.querySelectorAll(`[data-type='${quantityType}'][data-product-id='${productId}']`);
        quantityItems.forEach(quantityItem => {
            quantityItem.dataset.active = 'true';
            quantityItem.innerText = quantity;
        });
    });

    const quantityItems = document.querySelectorAll(`[data-type='${quantityType}']`);
    quantityItems.forEach(quantityItem => {
        if (productIds.includes(quantityItem.dataset.productId)) return;

        if (!quantityItem.dataset.productId && count) {
            quantityItem.dataset.active = 'true';
            quantityItem.innerText = count;
        } else {
            quantityItem.dataset.active = 'false';
            quantityItem.innerText = '0';
        }
    });
}

document.addEventListener('DOMContentLoaded', () => {
    setupHover();
    cartActions();
    refreshCartQuantity();
    setupQuantity();
});

document.addEventListener('DOMContentLoaded', () => {
    jQuery(document.body).on('wc_fragments_loaded', () => {
        setupHover();
        cartActions();
        refreshCartQuantity();
        setupQuantity();
    });

    jQuery(document.body).on('wc_fragments_refreshed', () => {
        setupHover();
        cartActions();
        refreshCartQuantity();
        setupQuantity();
    });
});

function selectorSetup() {
    const selectBoxType = 'select-box';
    const selectBoxContentType = 'select-box-content';
    const selectBoxItemType = 'select-box-item';
    const selectBoxSearchType = 'select-box-search';
    const clearType = 'select-box-clear';

    const event = new Event('input', {
        bubbles: true,
        cancelable: true,
    });

    const closeActiveContent = () => {
        const activeContent = document.querySelector(`[data-active=true][data-type=${selectBoxContentType}]`);
        if (activeContent) activeContent.dataset.active = 'false';
    }

    document.addEventListener('click', () => {
        closeActiveContent();
    });

    const selectBoxes = document.querySelectorAll(`[data-type=${selectBoxType}]`);
    selectBoxes.forEach(selectBox => {
        const content = selectBox.querySelector(`[data-type=${selectBoxContentType}]`);
        const input = selectBox.querySelector('input');
        const select = selectBox.querySelector('select');
        const search = selectBox.querySelector(`[data-type=${selectBoxSearchType}]`);
        const items = selectBox.querySelectorAll(`[data-type=${selectBoxItemType}]`);
        const clear = selectBox.querySelector(`[data-type=${clearType}]`);

        if(clear && clear.dataset.script !== 'loaded'){
            clear.dataset.script = 'loaded';
            clear.addEventListener('click', () => {
                select.selectedIndex = -1;
                clear.dataset.active = 'false';
                input.value = '';
                search.value = "";
                input.dispatchEvent(event);
                select.dispatchEvent(new Event("select"));
                closeActiveContent();
            });
        }

        if (input.dataset.script !== 'loaded') {
            input.dataset.script = 'loaded';
            console.log(14);
            input.addEventListener('focus', (e) => {
                e.stopPropagation();
                console.log(15);

                if (content?.dataset.active === 'false') {
                    closeActiveContent();
                    if (content) content.dataset.active = 'true';
                } else {
                    if (content) content.dataset.active = 'false';
                }
            });
        }

        content.addEventListener('click', (e) => {
            e.stopPropagation();
        });

        input.addEventListener('click', (e) => {
            e.stopPropagation();
        });

        items.forEach((item, i) => {
            const value = item.dataset.value;

            if (item.dataset.script !== 'loaded') {
                item.dataset.script = 'loaded';
                item.addEventListener("click", () => {
                    if(clear) clear.dataset.active = 'true';
                    input.value = value;
                    select.selectedIndex = i;
                    search.value = "";
                    items.forEach((item) => {
                        item.style.display = "unset";
                    });

                    input.dispatchEvent(event);
                    select.dispatchEvent(new Event("select"));
                    closeActiveContent();
                });
            }
        });

        search?.addEventListener("input", (e) => {
            const searchTerm = search.value;

            items.forEach((item) => {
                const value = item.dataset.value;
                if (value.includes(searchTerm.trim())) {
                    item.style.display = "unset";
                } else {
                    item.style.display = "none";
                }
            });
        });
    });
}

document.addEventListener('DOMContentLoaded', () => {
    selectorSetup();
});

document.addEventListener('DOMContentLoaded', () => {

    function setupBlogItems() {
        const blogItemsType = 'blog-items';
        const blogItemsBox = document.querySelector(`[data-type=${blogItemsType}]`);
        if (!blogItemsBox) return;

        const items = blogItemsBox.querySelectorAll('li');
        const columns = parseInt(isScreenLg() ? blogItemsBox.dataset.columnsLg : isScreenMd() ? blogItemsBox.dataset.columnsMd : blogItemsBox.dataset.columnsSm);
        const columnHeight = new Array(columns).fill(0);

        items.forEach(item => {
            const width = item.clientWidth;
            const height = item.clientHeight;
            const totalWidth = blogItemsBox.clientWidth;
            const columnOccupy = Math.round(width / totalWidth * columns);

            let itemTop = Number.MAX_VALUE;
            let column = 0;
            for (let i = 0; i < columnHeight.length - columnOccupy + 1; i++) {
                let max = 0;
                for (let j = i; j < i + columnOccupy; j++) {
                    max = Math.max(max, columnHeight[j]);
                }
                if (itemTop > max) {
                    itemTop = max;
                    column = i;
                }
            }
            for (let i = column; i < column + columnOccupy; i++) {
                columnHeight[i] = itemTop + height;
            }

            item.style.position = 'absolute';
            item.style.top = `${itemTop}px`;
            item.style.right = `${column * 100 / columns}%`;
        });

        let maxHeight = 0;
        for (let i = 0; i < columnHeight.length; i++)
            maxHeight = Math.max(maxHeight, columnHeight[i]);

        blogItemsBox.style.height = `${maxHeight}px`;
    }

    setupBlogItems();
    window.addEventListener('resize', () => setupBlogItems());
});

function isScreenLg() {
    const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    return (64 * rootFontSize) <= window.outerWidth;
}

function isScreenMd() {
    const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    return (48 * rootFontSize) <= window.outerWidth;
}

function isScreenSm() {
    const rootFontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);
    return (40 * rootFontSize) <= window.outerWidth;
}