let txtBox = document.querySelector('.txtBox')
txtBox.focus()
let letterCloseButton = document.querySelector('.letter-close-button')
let startsWith = document.getElementById("startsWith");
let mustInclude = document.getElementById("mustInclude");
let endsWith = document.getElementById("endsWith");
let exculdeWith = document.getElementById("exculdeWith");
let inculdeWith = document.getElementById("inculdeWith");
let wordLength = document.getElementById("wordLength");

const serachSection = document.querySelector(".serachSection");
let rangeOfBlankTile = serachSection.dataset.range;

// // when typing on input
txtBox.addEventListener('input', (e) => {
    if (e.target.value === "") {
        letterCloseButton.style.display = "none"
    }
    else {
        letterCloseButton.style.display = "block"
    }
    e.target.value = e.target.value.replace(/[^a-zA-Z? ]/g, "")
    let rangeOfBlankTile = 3
    if (rangeOfBlankTile === "") {
        rangeOfBlankTile = 3
    }
    e.target.value = e.target.value.replace(/ /g, '?')
    let data = []
    data = e.target.value.split('').filter((i) => i === '?')
    if (data.length > rangeOfBlankTile) {
        e.target.value = e.target.value.replace(/\?$/, '')
    }
})
letterCloseButton.addEventListener("click", () => {
    txtBox.value = ""
    letterCloseButton.style.display = "none"
})
//tooltips for advanced filter
const filterInputs = document.querySelectorAll('.filter_val');
Array.from(filterInputs).forEach((item) => {
    item.addEventListener("input", (e) => {
        const inputValue = e.target.value;
        const parentElement = e.target.parentElement;
        const imgElement = parentElement.querySelector('img');
        const tooltipElement = parentElement.querySelector('.filter-tooltip');

        if (inputValue == "") {
            imgElement.src = "/assets/images/questionmark.svg"
            setTimeout(() => {
                item.nextElementSibling.setAttribute("data-tip", item.nextElementSibling.id)
            }, 100);
            tooltipElement.style.setProperty('--tooltip-padding', '0.5rem');
            tooltipElement.style.setProperty('--tooltip-border-style', 'soild');

        } else {
            item.nextElementSibling.removeAttribute("data-tip")
            imgElement.src = "/assets/images/close-btn.svg"
            tooltipElement.style.setProperty('--tooltip-padding', '0');
            tooltipElement.style.setProperty('--tooltip-border-style', 'none');
        }      
    })

    item.nextElementSibling.addEventListener("click", () => {
        const parentElement = item.parentElement;
        const imgElement = parentElement.querySelector('img');
        const tooltipElement = parentElement.querySelector('.filter-tooltip');
        item.value = ""
        imgElement.src = "/assets/images/questionmark.svg"
        setTimeout(() => {
            item.nextElementSibling.setAttribute("data-tip", item.nextElementSibling.id)
        }, 100);
        tooltipElement.style.setProperty('--tooltip-padding', '0.5rem');
        tooltipElement.style.setProperty('--tooltip-border-style', 'soild');
    })
})


const loadResource = (FILE_URL, data = {}, async = true, type = "text/javascript") => {
    return new Promise((resolve, reject) => {
        let resourceEle;

        if (type === "text/javascript") {
            resourceEle = document.createElement("script");
            resourceEle.src = FILE_URL;
            resourceEle.classList.add("loaded-js");
        } else if (type === "text/css") {
            resourceEle = document.createElement("link");
            resourceEle.rel = "stylesheet";
            resourceEle.href = FILE_URL;
        } else {
            reject({
                status: false,
                message: `Unsupported resource type: ${type}`,
            });
            return;
        }

        resourceEle.type = type;
        resourceEle.async = async;

        Object.keys(data).forEach((key) => {
            resourceEle.setAttribute(`data-${key}`, data[key]);
        });

        resourceEle.addEventListener("load", () => {
            resolve({ status: true });
        });

        resourceEle.addEventListener("error", () => {
            reject({
                status: false,
                message: `Failed to load the resource ${FILE_URL}`,
            });
        });

        if (type === "text/javascript") {
            // console.log(resourceEle);
            // console.log(FILE_URL);
            document.body.appendChild(resourceEle);
        } else if (type === "text/css") {
            document.head.appendChild(resourceEle);
        }
    });
};
const formElement = document.querySelector("#form");
formElement.addEventListener("submit", function (e) {
    e.preventDefault();
    if (txtBox.value != "" || startsWith.value != "" || endsWith.value != "" || mustInclude.value != "" || exculdeWith.value != "" || inculdeWith.value != "" || wordLength.value != "") {
        let quesMark = "?";
        if (rangeOfBlankTile) {
            if (!txtBox.value.includes("?")) {
                txtBox.value = txtBox.value + quesMark.repeat(rangeOfBlankTile); //
                txtBox.value = txtBox.value;
            }
        }
        document.querySelector(".fillterWrapper").classList.add("hide")
        let selectedDictionary = document.querySelector(".select_dropDown2").value;
        if (history.pushState) {
            var newurl =
                window.location.protocol +
                "//" +
                window.location.host +
                window.location.pathname +
                "?" +
                "search" +
                "=" +
                txtBox.value.toLowerCase() +
                "&" +
                "dictionary" +
                "=" +
                selectedDictionary +
                "&" +
                "prefix" +
                "=" +
                startsWith.value +
                "&" +
                "contains" +
                "=" +
                mustInclude.value +
                "&" +
                "suffix" +
                "=" +
                endsWith.value +
                "&" +
                "exclude" +
                "=" +
                exculdeWith.value +
                "&" +
                "include" +
                "=" +
                inculdeWith.value +
                "&" +
                "length" +
                "=" +
                wordLength.value;
            window.history.pushState({ path: newurl }, "", newurl);

            const params = new URLSearchParams(window.location.search);
            serachValue = params.get("search");
            prefixValue = params.get("prefix");
            containsValue = params.get("contains");
            suffixValue = params.get("suffix");
            exculdeValue = params.get("exclude");
            includeValue = params.get("include");
            lengthValue = params.get("length");
            dictonary = params.get("dictionary");

            gtag("event", "page_view", {
                page_location: window.location.pathname + location.search,
            });
        }
        const paramName = 'search';
        if (new URLSearchParams(window.location.search).has(paramName)) {
            const additionalData = {
                url: "{{site.url}}",
                range: "{{page.blanktilerange}}"
            }
            var loadJs = document.querySelector(".loaded-js");
            if (loadJs == null) {
                loadResource("/assets/css/wordfinder-result.css", additionalData, true, "text/css")
                    .then((data) => {
                        console.log("CSS loaded:", data);
                    })
                    .then(() => {
                        // Load the JavaScript file after the CSS file has loaded
                        loadResource("/assets/js/wordfinder.js", additionalData, true, "text/javascript")
                            .then((data) => {
                                console.log("JavaScript loaded:", data);
                                getData(txtBox.value.toLowerCase());
                            })
                            .catch((error) => {
                                console.error("Error loading JavaScript:", error);
                            });
                    })
                    .catch((error) => {
                        console.error("Error loading CSS:", error);
                    });
            }
        }
    } else {
       console.log("Please Enter Valid Letters.");
    }
});
// Now you can use the loadScript function with additional data
function checkQueryParam() {
    const urlParams = new URLSearchParams(window.location.search);
    const paramName = 'search';
    if (urlParams.has(paramName)) {
        const additionalData = {
            url: "{{site.url}}",
            range: "{{page.blanktilerange}}"
        };
        loadResource("/assets/css/wordfinder-result.css", additionalData, true, "text/css")
            .then((data) => {
                console.log("CSS loaded:", data);
            })
            .then(() => {
                // Load the JavaScript file after the CSS file has loaded
                loadResource("/assets/js/wordfinder.js", additionalData, true, "text/javascript")
                    .then((data) => {
                        console.log("JavaScript loaded:", data);
                        getData(txtBox.value.toLowerCase());
                    })
                    .catch((error) => {
                        console.error("Error loading JavaScript:", error);
                    });
            })
            .catch((error) => {
                console.error("Error loading CSS:", error);
            });
    }
}
checkQueryParam();