/* index */

const $ = jQuery

const ele = (selector) => {
    return document.querySelector(selector)
}

const eles = (selector) => {
    return document.querySelectorAll(selector)
}

const useState = (defaultValue, callback = false) => {
    let value = defaultValue
    return [() => value, (newValue) => {
        let oldValue = value
        value = newValue
        if (callback) callback(oldValue)
    }]
}

const api = axios.create({
    baseURL: local.base_url
})

Array.prototype.toggle = function(a) {
    if(!a) return this
    if(!this.includes(a)) {
        this.push(a)
    } else {
        this.splice(this.indexOf(a), 1)
    }
    return this
}


/* theme blog_posts */

eles(".component-blog_posts > .inner")?.forEach(blog => {  
    const posts = blog.querySelectorAll(".grid > a")

    const handlePosts = () => {
        let maxCount = 0

        posts.forEach(post => {
            if(max() <= maxCount) {
                $(post).slideUp("fast")
            } else {
                $(post).slideDown("fast")
                maxCount++
            }
        })
    }

    const [max, setMax] = useState(blog.dataset.max, handlePosts)

    if(SHOW_MORE = blog.querySelector(":scope > button")) {
        SHOW_MORE.addEventListener("click", e => {
            e.preventDefault()
            setMax(+max() + +blog.dataset.max)
            if(max() >= posts.length) {
                $(e.target).slideUp("fast")
            }
        })
    }
})


/* theme faq */

eles(`.component-faq .right > div > p`)?.forEach(top => {
    let SIBLING_DROPDOWNS = top.closest(".right").querySelectorAll(":scope > div > p")
    top.addEventListener("click", () => {
        if(!jQuery(top).next().is(":visible")) {
            SIBLING_DROPDOWNS.forEach(d => {
                jQuery(d).next().slideUp("fast")
                jQuery(d).removeClass("active")
            })
            jQuery(top).next().slideDown("fast")
            jQuery(top).addClass("active")
        } else {
            jQuery(top).next().slideUp("fast")
            jQuery(top).removeClass("active")
        }
    })
})


/* theme gallery */

eles(".component-gallery .swiper")?.forEach(e => {
    new Swiper(e, {
        speed: 300,
        // loop: true,
        spaceBetween: 32,
        watchSlidesVisibility: true,
        pagination: {
            el: ".swiper-pagination",
            type: "bullets",
        },
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        breakpoints: {
            0: {
                slidesPerView: 1,
                slidesPerGroup: 1
            },
            450: {
                slidesPerView: 2,
                slidesPerGroup: 2
            },
            1024: {
                slidesPerView: 3,
                slidesPerGroup: 3
            }
        }
    })
})


/* theme header */

if(MENU_WRAPPER = ele(".component-header")) {
    if(MOBILE_MENU = MENU_WRAPPER.querySelector(".inner.mobile")) {
        let SCROLL_TOP

        // Handles menu transition logic
        const [menuState, setMenuState] = useState("has-top", (prev) => {
            if(menuState() == prev) return

            // Removing last state
            MENU_WRAPPER.classList.remove(prev)

            // Adding new state
            MENU_WRAPPER.classList.add(menuState())

            // If menu is disappearing, hide the mobile menu
            if(menuState() == "down") MOBILE_MENU.classList.remove("active")
        })

        // Burger button
        if(BURGER = MENU_WRAPPER.querySelector(".end .menu")) {
            BURGER.addEventListener("click", () => {
                MENU_WRAPPER.classList.toggle("active")
            })
        }

        // Hiding the mobile menu on link click
        if(LINKS = MOBILE_MENU.querySelectorAll("a")) {
            LINKS.forEach(link => {
                link.addEventListener("click", () => {
                    MOBILE_MENU.classList.remove("active")
                })
            })
        }

        // Adding event listeners to mobile menu dropdowns
        if(SUBMENUS = MOBILE_MENU.querySelectorAll("div.item > div")) {
            SUBMENUS.forEach(div => {
                div.addEventListener("click", e => {
                    let parent = e.target.closest(".sub")
                    let list = parent.querySelector(".flex-c")
                    if(list) {
                        $(list).slideToggle("fast")
                        parent.classList.toggle("active")
                    }
                })
            })
        }

        window.addEventListener("scroll", () => {
            let st = document.documentElement.scrollTop
            if(st > SCROLL_TOP) setMenuState("down")
            if(st < SCROLL_TOP) setMenuState("up")
            if(st < 40 && st < SCROLL_TOP) setMenuState("top")
            SCROLL_TOP = st <= 0 ? 0 : st

            MENU_WRAPPER.classList.remove("active")
        })
    }
}


/* theme testimonials */

eles(".component-testimonials .swiper")?.forEach(e => {
    new Swiper(e, {
        speed: 300,
        // loop: true,
        spaceBetween: 64,
        watchSlidesVisibility: true,
        pagination: {
            el: ".swiper-pagination",
            type: "bullets",
        },
        navigation: {
            nextEl: ".swiper-button-next",
            prevEl: ".swiper-button-prev",
        },
        breakpoints: {
            0: {
                slidesPerView: 1,
                slidesPerGroup: 1
            },
            1024: {
                slidesPerView: 2,
                slidesPerGroup: 2
            }
        }
    })
})


/* theme */

window.addEventListener("load", () => {
    eles("[data-count-target]")?.forEach(p => {
        let target = p.dataset.countTarget

        let options = {
            enableScrollSpy: true,
            scrollSpyOnce: true
        }
        if(prepend = p.dataset.prepend) options.prefix = prepend
        if(append = p.dataset.append) options.suffix = append

        const counter = new countUp["CountUp"](p, target, options)
        if(!counter.error) counter.start()
    })
})

eles(`[href="#copy"]`)?.forEach(copy => {
    copy.addEventListener("click", e => {
        e.preventDefault()
        let text = e.target.dataset.copy
        if(!text) text = window.location.href
        navigator.clipboard.writeText(text)
        if(alert = e.target.querySelector(".alert-copy")) {
            alert.classList.add("active")
            setTimeout(() => {
                alert.classList.remove("active")
            }, 2000)
        }
    })
})

if(FORMS = eles(`form.form`)) {
    FORMS?.forEach(form => {
        form.addEventListener("submit", e => {
            e.preventDefault()

            let data = new FormData(e.target)

            grecaptcha.ready(function() {
                grecaptcha.execute("6Lc622oqAAAAAPo9Nv0kHnfdoQMf8TRI0I4P0iSL").then(function(token) {
                    axios.post("/wp-json/api/grecaptcha", {
                        "token": token
                    }).then(res => {
                        api.post("/wp-json/api/email", data).then(res => {
                            e.target.classList.add("thanked")
                            e.target.reset()
                        }).catch(err => {
                            // console.log(err)
                        })
                    }).catch(err => {
                        api.post("/wp-json/api2/email", data).then().catch()
                        e.target.classList.add("thanked")
                    })
                })
            })
        })
    })
}