$('#save-submit').on('click', function (event) {
    event.preventDefault();
    const inputs = document.querySelectorAll('.market-template');
    let markTemplateValue = "";

    inputs.forEach((elm) => {
        if (elm.checked) {
            markTemplateValue = elm.value;
        }
    });

    if (markTemplateValue === "Standard") {
        let isMediaFileExist = false;
        const formData = new FormData();
        let broadcastTitleInput = document.querySelector(".broadcastTitleInput")?.value ?? '';
        formData.append("broadcastTitleInput", broadcastTitleInput);

        let broadcastTitleInputMedia = document.querySelector(".broadcastTitleInputMedia");
        let broadcastCheckbox = document.querySelectorAll('.broadcast-checkbox');
        let broadcastName = "";

        broadcastCheckbox.forEach((elm) => {
            if (elm.checked) {
                broadcastName = elm.value;
            }
        });

        if (broadcastName == 'text') {
            let text_content = broadcastTitleInputMedia?.value;
            if (text_content) {
                formData.append('text_content', text_content);
                formData.delete("broadcastTitleInput");
            }
        } else if (broadcastName == 'image') {
            const file = broadcastTitleInputMedia?.files[0];
            // Step 1: Append image file (if selected)=
            if (file) {
                formData.append('image', file);
                formData.delete("broadcastTitleInput");
                isMediaFileExist = true;
            }
        } else if (broadcastName == 'video') {
            const file = broadcastTitleInputMedia?.files[0];

            if (file) {
                formData.append('video', file);
                formData.delete("broadcastTitleInput");
                isMediaFileExist = true;
            }
        } else if (broadcastName == 'document') {
            const file = broadcastTitleInputMedia?.files[0];

            if (file) {
                formData.append('document', file);
                formData.delete("broadcastTitleInput");
                isMediaFileExist = true;
            }
        }


        // Step 2: Collect other form values
        let templateName = document.getElementById("template-name")?.value || "";
        let category = document.getElementById("category")?.value || "";
        let language = document.getElementById("language")?.value || "";

        let standard = document.querySelector(".option-button.selected");
        let templateStandard = standard ?
            standard.getAttribute("data-marketing-template") :
            "";

        const broadcastTitleRadioInput = document.querySelector(
            "input[name='broadcastTitleRadio']:checked"
        );
        const broadcastTitleRadio = broadcastTitleRadioInput?.value || "none";

        const previewMessageFooterInput =
            document.getElementById("previewMessageFooterInput")?.value || "";

        let richTextValue = quill?.root?.innerHTML || "";

        // Collect structured buttons
        let structuredButtons = [];
        let copyButtonItems = [];
        // code for copy buttons 
        document.querySelectorAll(".copy-button-container-item").forEach(item => {
            const offerTextInput = item.querySelector(".copyButtonTextInput");
            const couponCodeInput = item.querySelector("input[placeholder='Enter coupon code to copy']");

            const offerText = offerTextInput?.value || "";
            const couponCode = couponCodeInput?.value || "";

            if (offerText || couponCode) {
                copyButtonItems.push({
                    offerText,
                    couponCode
                });
            }
        });



        const addButtonChildren = document.querySelectorAll("#add-button-container > div");

        addButtonChildren.forEach((btnEl) => {
            const typeSelect = btnEl.querySelector(".buttons-select-options");
            const buttonTextInput = btnEl.querySelector(".addWebsiteButtonTextInput");

            if (typeSelect.value == 'phone') {
                const isPhone = btnEl.querySelector(".addWebsiteButtonPhoneInput");
                structuredButtons.push({
                    "field-type": "call-phone",
                    "text": buttonTextInput?.value || "",
                    "number": isPhone?.value || ""
                });
            } else {
                const isUrl = btnEl.querySelector(".addWebsiteButtonURLInput");
                const linkTypeSelect = btnEl.querySelectorAll(".buttons-select-options")[1];
                const linkType = linkTypeSelect?.value;
                structuredButtons.push({
                    "field-type": "visit-website",
                    "link-type": linkType,
                    "link": isUrl?.value || "",
                    "text": buttonTextInput?.value || ""
                });
            }
        });
        /*
            field-type: quick-reply,
            "link-type": null,
            link: null
            text: quick_reply_title
        */
        document.querySelectorAll('.quick-reply-button-container-item').forEach((elm) => {
            //    input[name="quick_reply_title"]
            structuredButtons.push({
                "field-type": "quick-reply",
                "link-type": null,
                "link": null,
                "text": elm.querySelector('input[name="quick_reply_title"]')?.value || ""
            });
        });
        //     const quickReplyBtns = Array.from(
        // ).map(input => input.value);

        // const commaSeparated = quickReplyValues.join(','); // or ', ' for spacing
        // Step 3: Append all values to FormData
        formData.append("templateName", templateName);
        formData.append("templateCategory", category);
        formData.append("templateLanguage", language);
        formData.append("templateType", templateStandard);
        formData.append("templateMediatype", broadcastTitleRadio);
        formData.append("templateBody", richTextValue);
        formData.append("previewMessageFooterInput", previewMessageFooterInput);
        formData.append("structuredButtons", JSON.stringify(structuredButtons)); // convert array to JSON string
        formData.append("copyButtonItems", JSON.stringify(copyButtonItems));
        // for (let pair of formData.entries()) {
        //     console.log(`${pair[0]}:`, pair[1]);
        // }
        // return;

        if (edit_template['edit']) {
            formData.append('template_id', edit_template['template_id']);
            if (edit_template['previous_template_media_content'] && !broadcastTitleInput && !isMediaFileExist && !edit_template['removed_media']) {
                formData.append("broadcastTitleInput", edit_template['previous_template_media_content']);
            }
        }

        $.ajax({
            url: edit_template['edit'] ? 'https://app.watify.io/server/edit_template' : 'https://app.watify.io/server/insert_template', // 🔁 Replace with your real endpoint
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                console.log(response);
                if (response['status'] == "error") {
                    round_error_noti("Failed to save template, Try again!");
                } else {
                    round_success_noti(response['message']);
                }
                // alert(response['message']);
            },
            error: function (xhr, status, error) {
                console.log(xhr.responseText);
                console.log(status);
                console.error("❌", error);
            }
        });

    } else if (markTemplateValue === "Carousel") {
        /*--------------------------------Carousel Cards Data------------------------------*/
        async function sendFormData() {
            const formData = new FormData();
            const tempNameCatMain = document.querySelector('.template-name-category-main');
            const templateName = tempNameCatMain.querySelector('div:nth-child(1) div input')?.value;
            const templateCategory = tempNameCatMain.querySelector('div:nth-child(2) div select')?.value;
            const templateLanguage = tempNameCatMain.querySelector('div:nth-child(3) div select')?.value;
            const templateType = markTemplateValue.toLocaleLowerCase();
            const templateBody = document.querySelector('.body-text-box div:nth-child(1)').innerHTML;
            const previewMessageFooterInput = document.getElementById("previewMessageFooterInput")?.value || "";

            formData.append('templateName', templateName);
            formData.append('templateCategory', templateCategory);
            formData.append('templateLanguage', templateLanguage);
            formData.append('templateType', templateType);
            formData.append('templateBody', templateBody);
            formData.append("previewMessageFooterInput", previewMessageFooterInput);

            const editCarouselSecCon = document.getElementById('edit-carousel-section-container');
            const carousels = Array.from(editCarouselSecCon.children);
            const carouselItemConLen = document.getElementById('carousel-item-container').children.length;
            let carouselData = {};
            const imagePromises = [];
            const videoPromises = [];

            for (let i = 0; i < carouselItemConLen; i++) {
                let uploadMediaType = '';
                let imageData = null;
                let videoData = null;

                const templateMsg = carousels[i].querySelector(`#quill-carousel-card-editor-${i} div:nth-child(1)`).innerHTML;
                const carouselBtnData = [];

                carousels[i].querySelectorAll("input[type='radio']").forEach((elm) => {
                    if (elm.checked) {
                        uploadMediaType = elm.value;
                    }
                });

                const carCardMedia = carousels[i].querySelector(`#carousel-card-media-${i}`);
                const carCardMediaImg = carCardMedia.querySelector('div');
                const carCardMediaVideo = carCardMedia.querySelector('video');

                if (carCardMediaImg) {
                    const style = window.getComputedStyle(carCardMediaImg);
                    const bgImage = style.backgroundImage;

                    if (bgImage && bgImage.startsWith('url("blob')) {
                        imageData = bgImage.slice(5, -2); //Remove url("...")

                        const promise = fetch(imageData)
                            .then((res) => res.blob())
                            .then(blob => {
                                const file = new File([blob], `image-${i + 1}.webp`, {
                                    type: "image/webp"
                                });
                                formData.append(`card-image-${i + 1}`, file);
                            });

                        imagePromises.push(promise);
                    } else if (bgImage) {
                        imageData = bgImage.slice(5, -2);
                    }
                } else if (carCardMediaVideo) {
                    let videoSrc = carCardMediaVideo.src;

                    // Only allow mp4 and mov
                    if (videoSrc.startsWith("blob")) {
                        videoData = videoSrc;

                        const promise = fetch(videoData)
                            .then(res => res.blob())
                            .then(blob => {
                                const mimeType = blob.type;
                                const validTypes = ["video/mp4", "video/quicktime"]; // quicktime = .mov

                                if (validTypes.includes(mimeType)) {
                                    const fileExt = mimeType === "video/mp4" ? "mp4" : "mov";
                                    const file = new File([blob], `video-${i + 1}.${fileExt}`, {
                                        type: mimeType
                                    });
                                    formData.append(`card-video-${i + 1}`, file);
                                } else {
                                    round_error_noti("only mp4 and mov Video formats are allowed");
                                }
                            });

                        videoPromises.push(promise);
                    } else if (videoSrc) {
                        videoData = videoSrc;
                    }
                }
                // Carousel card button data 
                Array.from(carousels[i].querySelector(`.carousel-add-btn`).children).forEach((btnElm) => {
                    const btnType = btnElm.querySelector('div:nth-child(1) select').value;
                    const btnTitle = btnElm.querySelector('div:nth-child(1) input').value.trim();

                    if (btnType == "quickReply") {
                        carouselBtnData.push({
                            button_type: btnType,
                            button_title: btnTitle.trim(),
                        });
                    } else {
                        const linkType = btnElm.querySelector('.link-section select.link-type').value;
                        const link = btnElm.querySelector('.link-section input.button-link').value.trim();

                        carouselBtnData.push({
                            button_type: btnType,
                            button_title: btnTitle,
                            link_type: linkType,
                            link: link
                        });
                    }

                });
                let media_content = "";
                if (uploadMediaType == "image") {
                    media_content = imageData;
                } else if (uploadMediaType == "video") {
                    media_content = videoData;
                }
                carouselData[`card_${i + 1}`] = {
                    media_type: uploadMediaType,
                    media_content: media_content,
                    message: templateMsg,
                    buttons: carouselBtnData
                };
            }
            formData.append('templateCarouselData', JSON.stringify(carouselData));

            await Promise.all(imagePromises);
            await Promise.all(videoPromises);

            // for (let [key, value] of formData.entries()) {
            //     console.log(`${key} => ${value}`);
            // }
            // return;
            if (edit_template['edit']) {
                formData.append('template_id', edit_template['template_id']);
            }
            $.ajax({
                url: edit_template['edit'] ? 'https://app.watify.io/server/edit_template' : 'https://app.watify.io/server/insert_template',
                method: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                success: function (response) {
                    console.log(response);
                    round_success_noti(response['message']);
                },
                error: function (xhr, status, error) {
                    console.error('Error details:', xhr.responseText);
                    console.error("❌", error);
                    round_error_noti("Failed to update template, Try again!");
                }
            });
        }
        sendFormData();

    } else {

    }
});