function call_filter() {
    var e = document.getElementById("page_filter").value;
    if ("" != e) {
        addParameterToURL("aifilterpage", e);
    }
}
function addParameterToURL(e, t) {
    var a = window.location.href;
    -1 !== a.indexOf("?") ? (a += "&" + e + "=" + t) : (a += "?" + e + "=" + t), (window.location.href = a);
}
!(function (e) {
    document.addEventListener("click", function (t) {
        if (t.target.matches(".fetch_data")) {
            console.log("You pressed generate button");

            const e = t.target.getAttribute("data-id"),
                a = t.target.getAttribute("data-content"),
                o = document.querySelector(`textarea[name="meta_focus_${e}"]`),
                n = o ? o.value : "";
            
            jQuery("#custom-loader").addClass("show");
            
            const r = new FormData();
            r.append("action", "unleash_ai_fetchmeta_rec");
            r.append("nonce", ajax_object.update_nonce);
            r.append("pageID", e);
            r.append("content", a);
            r.append("foukeyword", n);
            
            fetch(ajax_object.ajax_url, { method: "POST", body: r })
                .then((response) => response.json())
                .then((data) => {
                    jQuery("#custom-loader").removeClass("show");
            
                    // Check for internal server error in the response
                    if (data.message && data.message === "Internal Server Error") {
                        throw new Error("Internal Server Error");
                    }
            
                    const metaTitle = data.meta_title,
                        metaDescription = data.meta_description;
            
                    Object.keys(metaTitle).forEach((key) => {
                        const titleTextarea = document.querySelector(`textarea[name="meta_title_${key}_${e}"]`);
                        if (titleTextarea) titleTextarea.value = metaTitle[key];
            
                        const descriptionTextarea = document.querySelector(`textarea[name="meta_des_${key}_${e}"]`);
                        if (descriptionTextarea) descriptionTextarea.value = metaDescription[key];
                    });
                })
                .catch((error) => {
                    console.error("Error:", error);
                    alert("Something went wrong while processing the data. Please try again.");
                    jQuery("#custom-loader").removeClass("show");
                });
            
        }
        if (t.target.matches(".update-btn")) {
            var a = t.target.getAttribute("data-page-id"),
                o = (e('input[name="meta_t_radio_' + a + '"]:checked'), e('input[name="meta_d_radio_' + a + '"]:checked'), "no"),
                n = "no",
                r = e(".pre_title_checkbox:checked");
            if (r.length > 1) return alert("Please select single meta title and description to update on your web page"), !1;
            1 == r.length && (o = "yes");
            var c = e(".pre_des_chk:checked");
            if (c.length > 1) return alert("Please select single meta title and description to update on your web page"), !1;
            var l = "";
            if ("yes" == o) {
                var d = r.attr("name").split("_");
                l = e('textarea[name="meta_title_' + d[3] + "_" + a + '"]').val();
            }
            1 == c.length && (n = "yes");
            var s = "";
            if ("yes" == n) {
                var u = c.attr("name").split("_");
                console.log(u), (s = e('textarea[name="meta_des_' + u[2] + "_" + a + '"]').val());
            }
            if (!l || !s) return alert("Please select at least one meta title and one meta description to update."), !1;
            jQuery("#custom-loader").addClass("show"),
                e.ajax({
                    url: ajax_object.ajax_url,
                    type: "POST",
                    data: { action: "update_meta_action", nonce: ajax_object.update_nonce, pageID: a, metaTitle: l, metaDescription: s },
                    success: function (t) {
                        (jQuery("#custom-loader").removeClass("show"),
                        (function (e) {
                            const t = document.createElement("div");
                            (t.innerHTML = `\n            <div class="updatedDataNow">\n                <p>${e}</p>\n                <button id="closeButton">Close</button>\n            </div>`),
                                Object.assign(t.style, {
                                    position: "fixed",
                                    top: "50%",
                                    left: "50%",
                                    transform: "translate(-50%, -50%)",
                                    backgroundColor: "rgba(0, 0, 0, 0.27)",
                                    border: "1px solid #cccccc",
                                    padding: "20px",
                                    zIndex: "10000",
                                    width: "100%",
                                    height: "100%",
                                }),
                                document.body.appendChild(t),
                                document.getElementById("closeButton").addEventListener("click", () => {
                                    document.body.removeChild(t);
                                });
                        })("Updated Successfully"),
                        "yes" == o) && (document.querySelector('textarea[name="meta_title_' + a + '"]').value = l);
                        "yes" == n && (document.querySelector('textarea[name="meta_des_' + a + '"]').value = s);
                        e("#mpg_" + a + " .meta-title").text(l), e("#mpg_" + a + " .meta-description").text(s);
                    },
                    error: function (e, t, a) {
                        console.error(e.responseText);
                    },
                });
        }
        if (t.target.matches(".fetch_dataall")) {
            console.log("You pressed generate button");

            const e = document.querySelectorAll(".pre_title_checkbox.pageitem:checked");
            if (e.length === 0) {
                alert("Please select at least one post to generate metadata.");
                return;
            }
            
            jQuery("#custom-loader").addClass("show");
            
            const t = Array.from(e).map((e) => {
                const t = e.getAttribute("data-id"),
                    a = e.getAttribute("data-content"),
                    o = document.querySelector(`textarea[name="meta_focus_${t}"]`),
                    n = o ? o.value : "",
                    r = new FormData();
                
                r.append("action", "unleash_ai_fetchmeta_rec");
                r.append("nonce", ajax_object.update_nonce);
                r.append("pageID", t);
                r.append("content", a);
                r.append("foukeyword", n);
            
                return fetch(ajax_object.ajax_url, { method: "POST", body: r })
                    .then((response) => response.json())
                    .then((data) => {
                        // Check for internal server error in the response
                        if (data.message && data.message === "Internal Server Error") {
                            throw new Error("Internal Server Error");
                        }
            
                        const metaTitle = data.meta_title,
                            metaDescription = data.meta_description;
            
                        Object.keys(metaTitle).forEach((key) => {
                            const titleTextarea = document.querySelector(`textarea[name="meta_title_${key}_${t}"]`);
                            const descriptionTextarea = document.querySelector(`textarea[name="meta_des_${key}_${t}"]`);
                            if (titleTextarea) titleTextarea.value = metaTitle[key];
                            if (descriptionTextarea) descriptionTextarea.value = metaDescription[key];
                        });
                    })
                    .catch((error) => {
                        console.error("Error processing pageID:", t, error);
                        alert(`Something went wrong while processing pageID ${t}. Please try again.`);
                    });
            });
            
            Promise.all(t)
                .then(() => {
                    alert("Metadata generation completed. You can now update the data.");
                })
                .finally(() => {
                    jQuery("#custom-loader").removeClass("show");
                });
            
        }
        if (t.target.matches(".update_btnall")) {
            console.log("You pressed the update button");
            const e = document.querySelectorAll(".pre_title_checkbox.pageitem:checked");
            if (0 === e.length) return void alert("Please select at least one post to update metadata.");
            jQuery("#custom-loader").addClass("show");
            const t = Array.from(e).map((e) => {
                const t = e.getAttribute("data-id"),
                    a = document.querySelector(`#page_${t} input[name^="meta_t_chk_"]:checked`),
                    o = document.querySelector(`#page_${t} input[name^="meta_d_"]:checked`);
                if (!a || !o) return alert(`Please select a meta title and description for page ID ${t}.`), Promise.resolve();
                const n = a.getAttribute("reqatt"),
                    r = o.getAttribute("desreqatt"),
                    c = document.querySelector(`textarea[name="meta_title_${n}_${t}"]`).value,
                    l = document.querySelector(`textarea[name="meta_des_${r}_${t}"]`).value;
                return jQuery
                    .ajax({ url: ajax_object.ajax_url, type: "POST", dataType: "json", data: { action: "update_meta_action", nonce: ajax_object.update_nonce, pageID: t, metaTitle: c, metaDescription: l } })
                    .done((e) => {
                        if (e.success) {
                            const e = document.querySelector(`textarea[name="meta_title_${t}"]`),
                                a = document.querySelector(`textarea[name="meta_des_${t}"]`);
                            e && (e.value = c), a && (a.value = l);
                        } else alert(`Failed to update metadata for page ID ${t}.`);
                    })
                    .fail(() => {
                        alert(`Error processing metadata update for page ID ${t}.`);
                    });
            });
            Promise.all(t)
                .then(() => {
                    alert("Metadata update completed for all selected posts.");
                })
                .finally(() => {
                    jQuery("#custom-loader").removeClass("show");
                });
        }
    });
    const t = document.getElementById("selectAllCheckbox");
    t.addEventListener("change", () => {
        document.querySelectorAll(".pageitem").forEach((e) => {
            e.checked = t.checked;
        });
    });
    const a = document.querySelectorAll(".pageitem");
    a.forEach((e) => {
        e.addEventListener("change", () => {
            t.checked = Array.from(a).every((e) => e.checked);
        });
    });
    for (var o = document.getElementsByClassName("accordionBtn"), n = 0; n < o.length; n++)
        o[n].addEventListener("click", function () {
            for (var e = document.getElementsByClassName("panel"), t = 0; t < e.length; t++) e[t].style.display = "none";
            this.classList.toggle("active");
            var a = this.nextElementSibling;
            "block" === a.style.display ? (a.style.display = "none") : (a.style.display = "block");
        });
})(jQuery);
