!(function (e) {
    function t(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);
            });
    }
    document.addEventListener("click", function (a) {
        if (a.target.matches(".fetch_data")) {
            if (a.target.matches(".fetch_data")) {
                var n = a.target.getAttribute("data-id"),
                    o = a.target.getAttribute("data-parent-id"),
                    r = (e("#psdes_" + n).val(), "no"),
                    c = "no";
                e('input[name="meta_t_radio_' + n + '"]:checked').length > 0 && (r = "yes");
                e('input[name="meta_d_radio_' + n + '"]:checked').length > 0 && (c = "yes");
                var l = e("#regen_" + n).val();
            
                jQuery("#custom-loader").addClass("show");
                e.ajax({
                    url: ajax_object.ajax_url,
                    type: "POST",
                    data: {
                        action: "unleash_ai_fetchalt_rec",
                        nonce: ajax_object.update_nonce,
                        image_id: n,
                        pageID: o,
                        titlechk: r,
                        deschk: c,
                    },
                    success: function (response) {
                        try {
                            const data = JSON.parse(response);
            
                            if (data.message && data.message === "Internal Server Error") {
                                throw new Error("Internal Server Error");
                            }
            
                            const images = data.images[n];
                            if (images) {
                                Object.keys(images).forEach((key) => {
                                    const textarea = document.querySelector(`textarea[name="meta_des_${key}_${n}"]`);
                                    if (textarea) textarea.value = images[key];
                                });
                            }
            
                            jQuery("#custom-loader").removeClass("show");
            
                            if (data.msg === "disconnect") {
                                t("Your site is not connected with a license key, please connect it from the dashboard.");
                            } else if (data.msg === "request_limit") {
                                alert("Request limit reached");
                            } else if (data.msg === "invalid") {
                                alert("Invalid user");
                            } else {
                                if (r === "yes") {
                                    document.querySelector('textarea[name="meta_title_2_' + n + '"]').value = data.data.text.meta_title;
                                }
                                if (l !== "") {
                                    e(".pre_des_chk:checked").each(function () {
                                        var t = e(this).attr("desreqatt"),
                                            a = e(this).attr("name").split("_");
                                        if (data.data === "not_found") {
                                            e('textarea[name="meta_des_' + a[2] + "_" + n + '"]').val("not_found");
                                        } else {
                                            e('textarea[name="meta_des_' + a[2] + "_" + n + '"]').val(data.data.text.images[n][t]);
                                        }
                                    });
                                } else if (data.data === "not_found") {
                                    document.querySelector('textarea[name="meta_des_2_' + n + '"]').value = "not_found";
                                    document.querySelector('textarea[name="meta_des_3_' + n + '"]').value = "not_found";
                                    document.querySelector('textarea[name="meta_des_4_' + n + '"]').value = "not_found";
                                } else {
                                    document.querySelector('textarea[name="meta_des_2_' + n + '"]').value = data.data.text.images[n][0];
                                    document.querySelector('textarea[name="meta_des_3_' + n + '"]').value = data.data.text.images[n][1];
                                    document.querySelector('textarea[name="meta_des_4_' + n + '"]').value = data.data.text.images[n][2];
                                }
                            }
                        } catch (error) {
                            console.error(error);
                            alert("Something went wrong while processing the data. Please try again.");
                            jQuery("#custom-loader").removeClass("show");
                        }
                    },
                    error: function (e, t, a) {
                        console.error(e.responseText);
                        alert("An error occurred during the request. Please try again.");
                        jQuery("#custom-loader").removeClass("show");
                    },
                });
            }
            
        }
        if (a.target.matches(".update-btn")) {
            (o = a.target.getAttribute("data-id")), (n = a.target.getAttribute("data-parent-id")), (r = "no"), (c = "no");
            var d = e("#alt_" + o).find(".pre_des_chk:checked");
            if (d.length > 1) return alert("Please select a single meta title and description to update on your web page"), !1;
            1 == d.length && (c = "yes");
            var s = "";
            if ("yes" == c) {
                var i = d.attr("name").split("_");
                console.log(i), (s = e('textarea[name="meta_des_' + i[2] + "_" + o + '"]').val());
            }
            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: n, image_id: o, altTag: s },
                    success: function (a) {
                        jQuery("#custom-loader").removeClass("show"), t("Updated Successfully"), (document.getElementById("meta_des_" + o).value = s), e("#mpg_" + o + " .meta-description").text(s);
                    },
                    error: function (e, t, a) {
                        console.error(e.responseText);
                    },
                });
        }
        if (a.target.matches(".fetch_dataall")) {
            console.log("You pressed the generate button");

            const t = document.querySelectorAll(".pre_title_checkbox.pageitem:checked");
            if (t.length === 0) {
                alert("Please select at least one post to generate metadata.");
                return;
            }
            
            jQuery("#custom-loader").addClass("show");
            
            const a = Array.from(t).flatMap((e) => {
                const t = e.closest(".accordionBtn")?.nextElementSibling,
                    a = t.querySelectorAll(".fetch_data");
            
                return Array.from(a)
                    .map((e) => {
                        const parentId = e.getAttribute("data-parent-id"),
                            pageId = e.getAttribute("data-page-id"),
                            content = e.getAttribute("data-content");
            
                        return fetch(ajax_object.ajax_url, {
                            method: "POST",
                            headers: { "Content-Type": "application/x-www-form-urlencoded" },
                            body: new URLSearchParams({
                                action: "unleash_ai_fetchalt_rec",
                                nonce: ajax_object.update_nonce,
                                pageID: parentId,
                                image_id: pageId,
                                content: content,
                            }),
                        })
                            .then((response) => response.json())
                            .then((data) => {
                            
                                if (data.message && data.message === "Internal Server Error") {
                                  //  alert(`Something went wrong while processing pageId=${pageId}. Please try again.`);
                                   // jQuery("#custom-loader").removeClass("show");
                                    throw new Error("Internal Server Error");
                                }
            
                                const images = data.images?.[pageId];
                                if (images) {
                                    Object.keys(images).forEach((key) => {
                                        const textarea = document.querySelector(`textarea[name="meta_des_${key}_${pageId}"]`);
                                        if (textarea) textarea.value = images[key];
                                    });
                                }
                            })
                            .catch((error) => {
                                console.error(`Error processing pageId=${pageId}:`, error);
                                alert(`Something went wrong while processing pageId=${pageId}. Please try again.`);
                                jQuery("#custom-loader").removeClass("show");
                            });
                    })
                    .filter((e) => e !== null);
            });
            
            Promise.all(a)
                .then(() => {
                    modalTitle.textContent = "Metadata generation completed";
                    modalBody.textContent = "Metadata generation completed. You can now update the data.";
                    e("#exampleModal").modal("show");
                })
                .finally(() => {
                    jQuery("#custom-loader").removeClass("show");
                });
                        
        }
        if (a.target.matches(".update_btnall")) {
            console.log("You pressed the update button");
            const e = document.querySelectorAll(".alt_checkbox.pre_des_chk:checked");
            document.getElementById("page_filter").value;
            if (0 === e.length) return void alert("Please select at least one post to update metadata.");
            const a = Array.from(e)
                .map((e) => {
                    const t = e.getAttribute("data-id"),
                        a = e.getAttribute("data-parent-id"),
                        n = document.querySelector(`#page_${t} input[name^="meta_d_"]:checked`);
                    if (!n) return alert("Please select at least one Alt Tag to update."), null;
                    const o = n.getAttribute("desreqatt"),
                        r = document.querySelector(`textarea[name="meta_des_${o}_${t}"]`).value;
                    return (
                        jQuery("#custom-loader").addClass("show"),
                        fetch(ajax_object.ajax_url, {
                            method: "POST",
                            headers: { "Content-Type": "application/x-www-form-urlencoded" },
                            body: new URLSearchParams({ action: "update_meta_action", nonce: ajax_object.update_nonce, image_id: t, pageID: a, altTag: r }),
                        })
                            .then((e) => e.json())
                            .then((e) => {})
                    );
                })
                .filter((e) => null !== e);
            Promise.all(a)
                .then(() => {
                    a.some((e) => null !== e) && (jQuery("#custom-loader").removeClass("show"), t("Updated Successfully"));
                })
                .finally(() => {});
        }
    });
    const a = document.getElementById("selectAllCheckbox");
    a.addEventListener("change", () => {
        document.querySelectorAll(".pageitem").forEach((e) => {
            e.checked = a.checked;
        });
    });
    const n = document.querySelectorAll(".pageitem");
    n.forEach((e) => {
        e.addEventListener("change", () => {
            a.checked = Array.from(n).every((e) => e.checked);
        });
    });
    for (var o = document.getElementsByClassName("accordionBtn"), r = 0; r < o.length; r++)
        o[r].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);
