let filter_active = false;

window.addEventListener("load", (event) => {
    let filter = document.querySelector(".sh-query-posts .filter");
    if (filter != null) {
        if (filter.getAttribute("data-show") == 'latest') {
            filter_active = true;
        }
    }

    if (filter_active) {
        updateFilters();
    }
});

document.addEventListener("keypress", function (e) {
    if (e.target.matches(".sh-query-posts #search.search") && filter_active) {
        if (e.key == "Enter") {
            updateFilters();
            getResults();
        }
    }
});

document.addEventListener("click", function (e) {
    if (e.target.matches(".sh-query-posts .results .filter-clear") && filter_active) {
        let type = e.target.getAttribute("data-clear");
        let filters = ["search", "author", "taxonomy", "category"];

        if (type == "all") {
            filters.forEach(function (item) {
                let filter = document.querySelector(".sh-query-posts #" + item);
                if (filter != null) {
                    filter.value = "";
                }
            });
        } else {
            let filter = document.querySelector(".sh-query-posts #" + type);
            if (filter != null) {
                filter.value = "";
            }
        }

        updateFilters();
        getResults();
    } else if (e.target.matches(".sh-query-posts .pagination-result a") && filter_active) {
        updateFilters();
        getResults();
    }
});

document.addEventListener("change", function (e) {
    if (e.target.matches(".sh-query-posts .options select") && filter_active) {
        updateFilters();
        getResults();
    }
});

function createPost(post, labelTitle) {
    let queryPost = document.createElement("div");
    queryPost.classList.add("query-post");

    let postImage = document.createElement("div");
    postImage.classList.add("post-image");

    let img = document.createElement("img");
    img.setAttribute("src", post.image);
    img.setAttribute("decoding", "async");
    img.setAttribute("alt", "Image");

    postImage.appendChild(img);

    let postContent = document.createElement("div");
    postContent.classList.add("post-content");

    let postTitle = document.createElement(labelTitle);
    postTitle.classList.add("post-title");
    postTitle.textContent = post.title;

    let postAuthor = document.createElement("div");
    postAuthor.classList.add("post-author");

    let authorIcon = document.createElement("span");
    authorIcon.classList.add("author-icon");
    authorIcon.innerHTML = `
    <svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
        <path d="M13.9618 4.15202L11.3488 1.53752C10.8622 1.04862 10.2836 0.661015 9.64642 0.397112C9.00919 0.133208 8.32596 -0.00175791 7.63625 1.72865e-05H4.25C3.2558 0.00120818 2.30267 0.396679 1.59966 1.09968C0.896661 1.80269 0.501191 2.75582 0.5 3.75002V14.25C0.501191 15.2442 0.896661 16.1973 1.59966 16.9004C2.30267 17.6034 3.2558 17.9988 4.25 18H11.75C12.7442 17.9988 13.6973 17.6034 14.4003 16.9004C15.1033 16.1973 15.4988 15.2442 15.5 14.25V7.86377C15.5019 7.17408 15.3669 6.49089 15.1028 5.85375C14.8388 5.21661 14.4509 4.6382 13.9618 4.15202ZM12.9012 5.21252C13.1303 5.44813 13.3272 5.71291 13.487 6.00002H10.25C10.0511 6.00002 9.86032 5.921 9.71967 5.78035C9.57902 5.63969 9.5 5.44893 9.5 5.25002V2.01302C9.7872 2.17271 10.0522 2.36939 10.2882 2.59802L12.9012 5.21252ZM14 14.25C14 14.8468 13.7629 15.4191 13.341 15.841C12.919 16.263 12.3467 16.5 11.75 16.5H4.25C3.65326 16.5 3.08097 16.263 2.65901 15.841C2.23705 15.4191 2 14.8468 2 14.25V3.75002C2 3.15328 2.23705 2.58098 2.65901 2.15903C3.08097 1.73707 3.65326 1.50002 4.25 1.50002H7.63625C7.75925 1.50002 7.8785 1.52402 8 1.53527V5.25002C8 5.84675 8.23705 6.41905 8.65901 6.84101C9.08097 7.26296 9.65326 7.50002 10.25 7.50002H13.9647C13.976 7.62152 14 7.74002 14 7.86377V14.25Z" fill="#0160AC"></path>
    </svg>`;

    let authorDate = document.createElement("span");
    authorDate.classList.add("author-date");
    authorDate.textContent = post.date;

    let authorBy = document.createElement("span");
    authorBy.classList.add("author-by");
    authorBy.textContent = "By";

    let authorName = document.createElement("span");
    authorName.classList.add("author-name");

    let authorLink = document.createElement("a");
    authorLink.setAttribute("href", post.author_url);
    authorLink.textContent = post.author_name;
    authorName.appendChild(authorLink);

    postAuthor.appendChild(authorIcon);
    postAuthor.appendChild(authorDate);
    postAuthor.appendChild(authorBy);
    postAuthor.appendChild(authorName);
    
    if (post.author_term_name != "") {
        let authorSeparator = document.createElement("span");
        authorSeparator.classList.add("author-separator");
        authorSeparator.textContent = "|";

        let authorCategories = document.createElement("span");
        authorCategories.className = "post-categories";

        let authorCategory = document.createElement("span");
        authorCategory.className = "post-category";

        let categoryLink = document.createElement("a");
        categoryLink.href = "/" + post.author_term_taxonomy + "/" + post.author_term_slug;
        categoryLink.innerHTML = post.author_term_name;
        authorCategory.appendChild(categoryLink);
        authorCategories.appendChild(authorCategory);

        postAuthor.appendChild(authorSeparator);
        postAuthor.appendChild(authorCategories);
    }

    let postDescription = document.createElement("div");
    postDescription.classList.add("post-description");
    postDescription.textContent = post.post_excerpt;

    postContent.appendChild(postTitle);
    postContent.appendChild(postAuthor);
    postContent.appendChild(postDescription);

    let LinkPost = document.createElement("a");
    LinkPost.setAttribute("href", post.url);
    LinkPost.setAttribute("target", "_self");
    LinkPost.classList.add("post-link");

    queryPost.appendChild(LinkPost);
    queryPost.appendChild(postImage);
    queryPost.appendChild(postContent);

    return queryPost;
}

function getResults() {
    let search_selected = '';
    let search = document.querySelector(".sh-query-posts #search");
    if (search != null) {
        search_selected = search.value;
    }

    let author_selected = '';
    let author = document.querySelector(".sh-query-posts #author option:checked");
    if (author != null) {
        author_selected = author.value;
    }

    let term_selected = '';
    let term = document.querySelector(".sh-query-posts #taxonomy option:checked");
    if (term != null) {
        term_selected = term.value;
    }

    let category_selected = '';
    let category = document.querySelector(".sh-query-posts #category option:checked");
    if (category != null) {
        category_selected = category.value;
    }

    let post_type = document.querySelector(".sh-query-posts .filter").getAttribute("data-post-type");
    let taxonomy = document.querySelector(".sh-query-posts .filter").getAttribute("data-taxonomy");
    let show = document.querySelector(".sh-query-posts .filter").getAttribute("data-show");
    let category_type = document.querySelector(".sh-query-posts .filter").getAttribute("data-category-type");
    let category_include = document.querySelector(".sh-query-posts .filter").getAttribute("data-category-include");
    let category_exclude = document.querySelector(".sh-query-posts .filter").getAttribute("data-category-exclude");
    let quantity = document.querySelector(".sh-query-posts .filter").getAttribute("data-quantity");

    const ajax_url = sh_query_posts_var.ajaxurl;

    fetch(ajax_url, {
        method: "POST",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        body: `action=load_query_posts&taxonomy=${taxonomy}&post_type=${post_type}&show=${show}&category_type=${category_type}&category_include=${category_include}&category_exclude=${category_exclude}&quantity=${quantity}&search=${search_selected}&author=${author_selected}&term=${term_selected}&category=${category_selected}`,
    })
    .then((response) => response.json())
    .then((posts) => {
        let primary_selector = document.querySelector(".sh-query-posts .query-primary");
        let list_selector = document.querySelector(".sh-query-posts .query-lists");

        if (posts.length > 0) {
            let post_primary = posts[0];
            posts.shift();
            
            if (primary_selector != null) {
                primary_selector.innerHTML = "";
                let query_post = createPost(post_primary, "div");
                primary_selector.appendChild(query_post);
            }

            if (posts.length > 0) {
                if (list_selector != null) {
                    list_selector.innerHTML = "";
                } else {
                    let block = document.querySelector(".sh-query-posts .container-query-posts");
                    let list_selector_tem = document.createElement("div");
                    list_selector_tem.classList.add("query-lists");
                    list_selector_tem.classList.add("size-posts-list");
                    block.appendChild(list_selector_tem);

                    primary_selector.classList.remove("size-primary-full");
                    primary_selector.classList.add("size-primary");

                    list_selector = document.querySelector(".sh-query-posts .query-lists");
                }

                posts.forEach(function (post) {
                    let query_post = createPost(post, "div");
                    list_selector.appendChild(query_post);
                });
            } else {
                if (list_selector != null) {
                    list_selector.remove();
                }

                primary_selector.classList.remove("size-primary");
                primary_selector.classList.add("size-primary-full");
            }
        } else {
            if (primary_selector != null) {
                primary_selector.innerHTML = "";
            }

            if (list_selector != null) {
                list_selector.innerHTML = "";
            }
        }
    })
    .catch((err) => console.error(err));
}


function updateFilters() {
    let results = "";
    let count = 0;
    let filters = ["search", "author", "taxonomy", "category"];
    let label;

    filters.forEach(function (item) {
        let filter = document.querySelector(".sh-query-posts #" + item);
        if (filter != null && filter.value != "") {
            label = "";

            if (filter.tagName === "SELECT") {
                label = filter.options[filter.selectedIndex].innerHTML;
            } else {
                label = filter.value;
            }

            count++;
            results += `<a id="filter-${item}" class="filter-clear" data-clear="${item}"><b class="filter-clear" data-clear="${item}">${ucFirst(item)}:</b> ${ucFirst(label)}</a>`;
        }
    });

    if (count != 0) {
        results += `<a id="filter-all" class="filter-clear" data-clear="all">Clear</a>`;
    }

    document.querySelector(".sh-query-posts section.results").innerHTML = results;
}

function ucFirst(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
