let mainContent = document.querySelector('.xyz-main-content')
let xyzsortValue
let xyzsortBool = false
let thexyzSelect = document.querySelector('.xyz_select_dropDown')
let xyzlengthSelect = document.querySelector(".xyz-length-select");

let wordSections = {}
function Filtering(id) {
    id = xyzlengthSelect.value
    mainContent.innerHTML += ``
    var section = document.querySelectorAll('.allGroupWords')
    var sort_val = "alpha";
    Array.prototype.forEach.call(section, function (e) {
        if (document.body.clientWidth > 991) {
            wordSections[e.id] = e.offsetTop - 10
        } else {
            wordSections[e.id] = e.offsetTop - 10
        }
    })
    console.log(sort_val + '_' + id);
    document.documentElement.scrollTop = wordSections[sort_val + '_' + id] + 5
}
// sorting for words
thexyzSelect.addEventListener("change", () => {
    xyzsortValue = thexyzSelect[thexyzSelect.selectedIndex].text;
    let list_word = document.getElementsByClassName("list_word")
    let data = []
    Array.from(list_word).forEach(item => {
        item.removeChild(item.lastElementChild);
        data.push(item.innerHTML.replace(/\s/g, ''))
    })
    if (xyzsortValue == "Z-A") {
        xyzsortBool = "Z-A";
        sortby(xyzsortBool, data);
    } else if (xyzsortValue == "Points") {
        xyzsortBool = "Points";
        sortPointsby(xyzsortBool, data);
    } else {
        xyzsortBool = "A-Z";
        sortby(xyzsortBool, data);
    }
});
// sort by aplhabets
function sortby(xyzsortValue, data) {
    if (xyzsortValue === "Z-A") {
        appendData(xyzsortValue, data.reverse())
    }
    else if (xyzsortValue === "A-Z") {
        appendData(xyzsortValue, data.sort())
    }
}
// sorting by points
function sortPointsby(xyzsortValue, data) {
    if (xyzsortValue === "Points") {
        let newArray = [];
        data.map((item) => {
            if (item.length === 1) {
                ok = false;
            } else {
                let ScrabbleLetterScore = xyzScrabbleScore();
                let points = 0;
                let word = item.replace(/<\/?[^>]+>/gi, '')
                for (let i = 0; i < word.length; i++) {
                    points += ScrabbleLetterScore[word[i]] || 0;
                }
                const value = {
                    words: item,
                    points: points,
                };
                newArray.push(value);
            }
        });
        newArray.sort(function (a, b) {
            return b.points - a.points;
        });
        appendData(xyzsortValue, newArray)
    }
}

function appendData(xyzsortValue, data) {
    mainContent.innerHTML = "";
    let newWordsLength = 0;
    for (let i = 15; i > 0; i--) {
        let newdata
        if (xyzsortValue === "Points") {
            newdata = data.filter((item) => item.words.replace(/<\/?[^>]+>/gi, '').length === i)
        } else {
            newdata = data.filter((item) => item.replace(/<\/?[^>]+>/gi, '').length === i)
        }
        if (newdata.length === 0) {
            mainContent.innerHTML += "";
        } else {
            newWordsLength += newdata.length;
            const result = newdata.map((item) => {
                let ScrabbleLetterScore = xyzScrabbleScore();
                let points = 0;
                let word
                if (xyzsortValue === "Points") {
                    word = item.words.replace(/<\/?[^>]+>/gi, '')
                    item = item.words
                } else {
                    word = item.replace(/<\/?[^>]+>/gi, '')
                }
                for (let i = 0; i < word.length; i++) {
                    points += ScrabbleLetterScore[word[i]] || 0; // for unknown characters
                }
                return `
        <a class="anchor__style" title="Lookup ${item.replace(/<\/?[^>]+>/gi, '')} in Dictionary" target="_blank"
        href="/word-meaning?search=${item.replace(/<\/?[^>]+>/gi, '')}">
        <li class="list_word">
        ${item}
        <span class="points" value="${points}" style="position:relative; top:4px; font-size:12px">${points}</span>
        </li>
    </a>
`});

            mainContent.innerHTML += `
      <div class="allGroupWords wordlistContainer" id="alpha_${i}">
      <div class="wordListHeading">
      <h3 class="lead">${i} Letter Words</h3>
      </div>
      <div class="wordList">
      <ul class="ul list-unstyled">
        ${result.join('')}
        </ul>
      </div>
      </div>
      `
        }
    }
}
// Scrabble Point Array
const xyzScrabbleScore = () => {
    let twl06_sowpods = {
        a: 1,
        e: 1,
        i: 1,
        o: 1,
        u: 1,
        l: 1,
        n: 1,
        r: 1,
        s: 1,
        t: 1,
        d: 2,
        g: 2,
        b: 3,
        c: 3,
        m: 3,
        p: 3,
        f: 4,
        h: 4,
        v: 4,
        w: 4,
        y: 4,
        k: 5,
        j: 8,
        x: 8,
        q: 10,
        z: 10,
    };

    let wwfScore = {
        a: 1,
        b: 4,
        c: 4,
        d: 2,
        e: 1,
        f: 4,
        g: 3,
        h: 3,
        i: 1,
        j: 10,
        k: 5,
        l: 2,
        m: 4,
        n: 2,
        o: 1,
        p: 4,
        q: 10,
        r: 1,
        s: 1,
        t: 1,
        u: 2,
        v: 5,
        w: 4,
        x: 8,
        y: 3,
        z: 10,
    };

    // if (dictonary === "wwf") {
    //   return wwfScore;
    // } else {
    return twl06_sowpods;
    // }
};





let txtBox = document.querySelector('.txtBox')
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", () => {
            e.target.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();
    document.querySelector(".xyzPad").style.display = "none"
    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);
                });
        }
    }
});
// 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)) {
        document.querySelector(".xyzPad").style.display = "none"
        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();