function addEventToBtn(e, carousel_btn_con, btn_data, carousel_btn) {
    let container = "";
    let btn = "";

    if (carousel_btn_con) {
        container = carousel_btn_con;
        btn = carousel_btn;
    } else {
        btn = e.currentTarget;
        container = btn.closest(".carousel-btn-container").querySelector(".carousel-add-btn");
    }

    // Limit the number of buttons to 2
    if (container.children.length >= 1) {
        btn.style.display = "none";
        // alert("You can only add two buttons.");
        // return;
    }

    const id = `carousel-button-${Date.now()}`;
    const wrapper = document.createElement('div');
    wrapper.className = 'card p-3 mb-3 position-relative';
    wrapper.style.border = '1px solid #ccc';
    wrapper.id = id;

    const idAndDataTargetAttribute = `button-${Date.now()}`;

    wrapper.innerHTML = `
        <div class="mb-2 d-flex gap-2 align-items-center">
        <select class="form-select w-25 button-type">
            <option value="url" ${btn_data?.button_type === "url" ? "selected" : ""}>Visit Website</option>
            <option value="quickReply" ${btn_data?.button_type === "quickReply" ? "selected" : ""}>Quick Reply</option>
        </select>
            <input type="text" value=${btn_data ? btn_data.text : "Visit"} class="form-control w-50 button-text visit-url-title" placeholder="Button Text"/>
            <button type="button" class="btn btn-danger btn-sm delete-button delete-carousel-btn">Delete</button>
        </div>

        <div class="link-section">
            <div class="d-flex gap-2 align-items-center">
                <select class="form-select w-25 link-type">
                    <option value="static" ${btn_data?.link_type === "static" ? "selected" : ""}>Static</option>
                    <option value="dynamic" ${btn_data?.link_type === "dynamic" ? "selected" : ""}>Dynamic</option>
                </select>
                <input type="text" value=${btn_data ? btn_data.link : "www.xyz.com"} class="form-control w-75 button-link" placeholder="Enter Link"/>
            </div>
        </div>
    `;

    const buttonTypeSelect = wrapper.querySelector('.button-type');
    const linkSection = wrapper.querySelector('.link-section');
    const deleteButton = wrapper.querySelector('.delete-button');
    const visitUrlTitle = wrapper.querySelector('.visit-url-title');

    // Toggle visibility of the link section based on button type
    const toggleFields = () => {
        if (buttonTypeSelect.value === 'quickReply') {
            linkSection.style.display = 'none'; // Hide link section when Quick Reply is selected
        } else {
            linkSection.style.display = 'block'; // Show link section when Visit Website is selected
        }
    };
    // Handle button type change (Visit Website / Quick Reply)
    buttonTypeSelect.addEventListener('change', function () {
        carousel_select(idAndDataTargetAttribute, this.value); //This 'this.value' either contain a url or a quickReply.
        toggleFields();
        const previewContent = document.getElementById(idAndDataTargetAttribute);
        visitUrlTitle.value = this.value == "url" ? "Visit" : "Quick reply"

        visitUrlTitle.addEventListener('keyup', (e) => {
            const visitUrlSpan = previewContent.querySelector('span');
            visitUrlSpan.textContent = e.target.value;
        });
    });

    // Handle Delete
    deleteButton.addEventListener('click', () => {
        // Remove the preview content associated with this button
        const previewContent = document.getElementById(idAndDataTargetAttribute);

        if (previewContent) {
            previewContent.parentElement.remove();
        }
        // Now remove the button itself
        wrapper.remove();
    });
    // Set initial state
    toggleFields();

    container.appendChild(wrapper);

    if (!btn_data) {
        carousel_select(idAndDataTargetAttribute, 'url'); // Default to 'url' for new buttons
    }

    //Insert carousel button's data to caurosel slides butttons
    const previewContent = document.getElementById(idAndDataTargetAttribute);

    visitUrlTitle.addEventListener('keyup', (e) => {
        const visitUrlSpan = previewContent.querySelector('span');
        visitUrlSpan.textContent = e.target.value;
    });

    // By below code, add-website-btn is only visible when buttons are not more than 2
    const deleteBtn = container.querySelectorAll('.delete-carousel-btn');

    deleteBtn.forEach((elm) => {
        elm.addEventListener('click', () => {
            btn.style.display = "block";
        });
    });
}

function getEditContentComp(idx, editContentId) {

    return `<div class="rounded-3 border my-2 fade-animation-class edit-carousel-section-${idx} ${editContentId}" style="overflow: hidden;">
        <div class="d-flex py-2 px-3 justify-content-between align-items-center" style="background: #f6f8fb;">
            <p class="m-0">Edit card content</p>

            <div class="d-flex gap-3 align-items-center">
                <div style="cursor: pointer;">
                    <svg viewBox="0 0 24 24" width="20" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <g id="SVGRepo_bgCarrier" stroke-width="0"></g>
                        <g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g>
                        <g id="SVGRepo_iconCarrier">
                            <path fill-rule="evenodd" clip-rule="evenodd" d="M15 1.25H10.9436C9.10583 1.24998 7.65019 1.24997 6.51098 1.40314C5.33856 1.56076 4.38961 1.89288 3.64124 2.64124C2.89288 3.38961 2.56076 4.33856 2.40314 5.51098C2.24997 6.65019 2.24998 8.10582 2.25 9.94357V16C2.25 17.8722 3.62205 19.424 5.41551 19.7047C5.55348 20.4687 5.81753 21.1208 6.34835 21.6517C6.95027 22.2536 7.70814 22.5125 8.60825 22.6335C9.47522 22.75 10.5775 22.75 11.9451 22.75H15.0549C16.4225 22.75 17.5248 22.75 18.3918 22.6335C19.2919 22.5125 20.0497 22.2536 20.6517 21.6517C21.2536 21.0497 21.5125 20.2919 21.6335 19.3918C21.75 18.5248 21.75 17.4225 21.75 16.0549V10.9451C21.75 9.57754 21.75 8.47522 21.6335 7.60825C21.5125 6.70814 21.2536 5.95027 20.6517 5.34835C20.1208 4.81753 19.4687 4.55348 18.7047 4.41551C18.424 2.62205 16.8722 1.25 15 1.25ZM17.1293 4.27117C16.8265 3.38623 15.9876 2.75 15 2.75H11C9.09318 2.75 7.73851 2.75159 6.71085 2.88976C5.70476 3.02502 5.12511 3.27869 4.7019 3.7019C4.27869 4.12511 4.02502 4.70476 3.88976 5.71085C3.75159 6.73851 3.75 8.09318 3.75 10V16C3.75 16.9876 4.38624 17.8265 5.27117 18.1293C5.24998 17.5194 5.24999 16.8297 5.25 16.0549V10.9451C5.24998 9.57754 5.24996 8.47522 5.36652 7.60825C5.48754 6.70814 5.74643 5.95027 6.34835 5.34835C6.95027 4.74643 7.70814 4.48754 8.60825 4.36652C9.47522 4.24996 10.5775 4.24998 11.9451 4.25H15.0549C15.8297 4.24999 16.5194 4.24998 17.1293 4.27117ZM7.40901 6.40901C7.68577 6.13225 8.07435 5.9518 8.80812 5.85315C9.56347 5.75159 10.5646 5.75 12 5.75H15C16.4354 5.75 17.4365 5.75159 18.1919 5.85315C18.9257 5.9518 19.3142 6.13225 19.591 6.40901C19.8678 6.68577 20.0482 7.07435 20.1469 7.80812C20.2484 8.56347 20.25 9.56458 20.25 11V16C20.25 17.4354 20.2484 18.4365 20.1469 19.1919C20.0482 19.9257 19.8678 20.3142 19.591 20.591C19.3142 20.8678 18.9257 21.0482 18.1919 21.1469C17.4365 21.2484 16.4354 21.25 15 21.25H12C10.5646 21.25 9.56347 21.2484 8.80812 21.1469C8.07435 21.0482 7.68577 20.8678 7.40901 20.591C7.13225 20.3142 6.9518 19.9257 6.85315 19.1919C6.75159 18.4365 6.75 17.4354 6.75 16V11C6.75 9.56458 6.75159 8.56347 6.85315 7.80812C6.9518 7.07435 7.13225 6.68577 7.40901 6.40901Z" fill="#276afd"></path>
                        </g>
                    </svg>
                </div>

                <div data-carousel-id="${editContentId}" class="carousel-delete-button" style="cursor: pointer;" onclick="deleteCarouselCard(event,${idx})">
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="20" height="20" color="#000000" fill="none" style="height: 1.3rem; width: 1.3rem;">
                        <path d="M19.5 5.5L18.8803 15.5251C18.7219 18.0864 18.6428 19.3671 18.0008 20.2879C17.6833 20.7431 17.2747 21.1273 16.8007 21.416C15.8421 22 14.559 22 11.9927 22C9.42312 22 8.1383 22 7.17905 21.4149C6.7048 21.1257 6.296 20.7408 5.97868 20.2848C5.33688 19.3626 5.25945 18.0801 5.10461 15.5152L4.5 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                        <path d="M3 5.5H21M16.0557 5.5L15.3731 4.09173C14.9196 3.15626 14.6928 2.68852 14.3017 2.39681C14.215 2.3321 14.1231 2.27454 14.027 2.2247C13.5939 2 13.0741 2 12.0345 2C10.9688 2 10.436 2 9.99568 2.23412C9.8981 2.28601 9.80498 2.3459 9.71729 2.41317C9.32164 2.7167 9.10063 3.20155 8.65861 4.17126L8.05292 5.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                        <path d="M9.5 16.5L9.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                        <path d="M14.5 16.5L14.5 10.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" />
                    </svg>
                </div>
            </div>
        </div>

        <div class="py-2 px-3">
            <div class="mb-3">
                <label for="image" class="form-label fw-bold">Media</label>
                <p>Upload either an image or video</p>

                <div class="col-sm-10 d-flex gap-2">
                    <div class="form-checkm me-2">
                        <input class="form-check-input image-input-media" type="radio" name="media-upload-radio-${idx}" id="carousel-image-${idx}" value="image" checked onchange="onCarouselMediaTypeChange(event,${idx})">
                        <label class="form-check-label upload-media-image-label" for="carousel-image-${idx}">
                            Image
                        </label>
                    </div>

                    <div class="form-check me-4">
                        <input class="form-check-input video-input-media" type="radio" name="media-upload-radio-${idx}" id="carousel-video-${idx}" value="video" onchange="onCarouselMediaTypeChange(event, ${idx})">
                        <label class="form-check-label upload-media-video-label" for="carousel-video-${idx}">
                            Video
                        </label>
                    </div>
                </div>

                <div class="d-flex my-3 gap-2" id="upload-media-container">
                    <label id="upload-media-button" type="button" class="btn btn-outline-success carousel-media-label" for="carousel-upload-media-${idx}">Upload Media</label>

                    <input type="file" id="carousel-upload-media-${idx}" class="carousel-media-input" onchange="onCarouselMediaUpload(event,${idx})" hidden>
                </div>

                <h6 class="fw-bold">Uploaded from PC:</h6>

                <div id="carousel-card-media-${idx}" class="carousel-card-media" style="margin: 3rem 0rem;"></div>
                <div>
                    <h6 class="fw-bold">Card Content</h6>
                    <p>Input a minimum of 1 card content and button</p>
                </div>
                <div class="carousel-toolbar" id="carousel-toolbar-${idx}">
                    <select class="ql-header">
                        <option value="1">Heading</option>
                        <option value="2">Subheading</option>
                        <option selected>Normal</option>
                    </select>
                    <button class="ql-bold"></button>
                    <button class="ql-italic"></button>
                    <button class="ql-underline"></button>
                    <button class="ql-link"></button>
                    <button class="ql-list" value="ordered"></button>
                    <button class="ql-list" value="bullet"></button>
                    <button class="ql-strike"></button>
                </div>
                <div
                    id="quill-carousel-card-editor-${idx}"
                    class="inputbgcolor watify-quill-editor"
                    style="height: 200px;"
                    aria-placeholder="Template Message...">
                </div>
                <!-- button section -->
                <div id="carousel-buttons-section">
                    <div class="mb-3">
                        <label class="form-label fw-bold pt-3" style="color: black;">Carousel Buttons</label> <span class="fw-bold">(Recommended)</span>
                        <p>Insert buttons for carousel items!</p>
                        <div>
                            <div class="mb-2 gap-2 carousel-btn-container">
                                <div class="position-relative carousel-add-btn"></div>
                                <div id="carousel-addWebsiteCallButtonContainer" class="d-flex mb-2 gap-2">
                                    <button type="button" onclick="addEventToBtn(event)" class="btn btn-outline-success carousel-add-web-btn">
                                        Add Visit Website button
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>`
}
//add multiple cards in carousel 
function addCarousel(e) {
    const sliderLen = document.querySelectorAll(".slider-card").length;
    if (sliderLen === 5) {
        return;
    }

    // slider container
    hideShowSections("show", "carousel-container");

    const carouselConDiv = document.querySelector("#carousel-container > div");

    if (!carouselConDiv.classList.contains('swiper')) {
        carouselConDiv.classList.add('swiper');
    }

    const tempLength = document.querySelectorAll(".slider-card").length;

    // display crousel card
    const id = `carousel-${Date.now()}`;
    editContentId = id;
    const backgroundURL = "images/dummy-image.webp";
    $("#carousel-item-container").append(getCarouselItem(editContentId, backgroundURL, tempLength));


    swiper.appendSlide(getSliderItem(editContentId, backgroundURL, tempLength));

    carouselCardData[editContentId] = {
        mediaType: "image"
    };

    $("#carousel-card-length").html(document.querySelectorAll(".slider-card").length);

    $(`#${editContentId}`).click();


    if (document.querySelectorAll(".slider-card").length === 5) {
        $(".drag-and-drop-container").css({
            display: "none"
        })
    }

    // Add Carousel Edit content Component
    const editCarouselSectionCon = document.getElementById('edit-carousel-section-container');
    const div = document.createElement('div');
    div.innerHTML = getEditContentComp(sliderLen, editContentId);
    editCarouselSectionCon.appendChild(div.firstElementChild);
    initializeQuillEditor(sliderLen);
    // addEventToBtn(sliderLen);

    Array.from(editCarouselSectionCon.children).forEach((elm) => {
        if (!elm.classList.contains(editContentId)) {
            elm.style.display = "none";
        }
    });
}
// remove cards from carousel
const carouselCardData = {};

function initSwiper() {
    swiper = new Swiper('.swiper', {
        direction: 'horizontal',
        loop: false,
        pagination: {
            el: '.swiper-pagination',
        },
        navigation: {
            nextEl: '.swiper-button-next',
            prevEl: '.swiper-button-prev',
        },
        slidesPerView: 1,
        spaceBetween: 20,
        scrollbar: {
            el: '.swiper-scrollbar',
        },
    });
}

function deleteCarouselCard(e, idx) {
    const carouselId = e.currentTarget.getAttribute('data-carousel-id');
    const sliderCard = document.getElementById(carouselId);

    const editContentCon = document.getElementById('edit-carousel-section-container');

    const carouselItemCon = document.getElementById('carousel-item-container');
    const carouselItemConLen = carouselItemCon.children.length;

    const swiperButtonNext = document.querySelector('.swiper-button-next');
    const swiperButtonPrev = document.querySelector('.swiper-button-prev');

    // if (elm.id === carouselId) {
    const editContentComp = document.querySelector(`.${carouselId}`);

    const deleteBtnData = editContentComp.querySelector('.delete-carousel-btn');

    if (deleteBtnData) deleteBtnData.click();

    if (editContentComp) {
        editContentComp.classList.remove(carouselId);
        document.getElementById(`carousel-card-media-${idx}`).innerHTML = "";
        document.getElementById(`carousel-upload-media-${idx}`).value = "";
        editContentComp.remove();
    }
    sliderCard.remove();

    // Deleting a  matching swiper-slide
    const swiperSlides = document.querySelectorAll('.swiper-slide');

    swiperSlides.forEach((slide, slideIdx) => {
        if (slide.getAttribute('data-slider-id') === carouselId) {
            swiper.removeSlide(slideIdx);
        }
    });
    swiper.update();

    // Reset class and index
    Array.from(carouselItemCon.children).forEach((card, newIdx) => {
        card.setAttribute('data-index', newIdx);
        const oldClass = Array.from(card.classList).find(cls => cls.startsWith('slider-card-num-'));
        if (oldClass) {
            card.classList.replace(oldClass, `slider-card-num-${newIdx}`);
        }
    });

    Array.from(editContentCon.children).forEach((editContComp, newIdx) => {
        const oldClass = Array.from(editContComp.classList).find(cls => cls.startsWith('edit-carousel-section-'));
        if (oldClass) {
            editContComp.classList.replace(oldClass, `edit-carousel-section-${newIdx}`);
        }
    });

    document.querySelectorAll('.image-input-media').forEach((input, i) => {
        input.name = `media-upload-radio-${i}`;
        input.id = `carousel-image-${i}`;
    });
    document.querySelectorAll('.video-input-media').forEach((input, i) => {
        input.name = `media-upload-radio-${i}`;
        input.id = `carousel-video-${i}`;
    });
    document.querySelectorAll('.upload-media-image-label').forEach((label, i) => {
        label.setAttribute('for', `carousel-image-${i}`);
    });

    document.querySelectorAll('.upload-media-video-label').forEach((label, i) => {
        label.setAttribute('for', `carousel-video-${i}`);
    });

    document.querySelectorAll('.carousel-media-label').forEach((label, i) => {
        label.setAttribute('for', `carousel-upload-media-${i}`);
    });
    document.querySelectorAll('.carousel-media-input').forEach((input, i) => {
        input.id = `carousel-upload-media-${i}`;
        input.setAttribute('onchange', `onCarouselMediaUpload(event, ${i})`);
    });
    document.querySelectorAll('.carousel-delete-button').forEach((elm, i) => {
        elm.setAttribute('onclick', `deleteCarouselCard(event, ${i})`);
    });
    document.querySelectorAll('.carousel-card-media').forEach((elm, i) => {
        elm.id = `carousel-card-media-${i}`;
    });
    document.querySelectorAll('.carousel-toolbar').forEach((elm, i) => {
        elm.id = `carousel-toolbar-${i}`;
    });
    document.querySelectorAll('.watify-quill-editor').forEach((elm, i) => {
        elm.id = `quill-carousel-card-editor-${i}`;
    });
    // document.querySelectorAll('.carousel-add-btn').forEach((elm,i)=>{
    //     const oldClass = Array.from(elm.classList).find(cls => cls.startsWith('carousel-add-button-container-'));
    //     if (oldClass) {
    //         elm.classList.replace(oldClass, `carousel-add-button-container-${i}`);
    //     }
    // });
    // document.querySelectorAll('.carousel-add-web-btn').forEach((elm,i)=>{
    //     const oldClass = Array.from(elm.classList).find(cls => cls.startsWith('carousel-addWebsiteCallButton-'));
    //     if (oldClass) {
    //         elm.classList.replace(oldClass, `carousel-addWebsiteCallButton-${i}`);
    //     }
    // });

    // Reset swiper data indexes
    document.querySelectorAll('.swiper-slide').forEach((slider, newIdx) => {
        slider.setAttribute('data-index', newIdx);
        slider.setAttribute('data-swiper-slide-index', newIdx);
    });

    // Handle first and last conditions
    if (idx == 0) {
        swiperButtonPrev.style.display = "none";
        const updatedSliderLen = document.getElementById('carousel-item-container').children.length;
        if (updatedSliderLen > 0) {
            const nextCard = document.querySelector(`.slider-card-num-${idx}`);
            if (nextCard) nextCard.click();
        }
    } else {
        const prevCard = document.querySelector(`.slider-card-num-${idx - 1}`);
        if (prevCard) prevCard.click();
        swiper.slideTo(idx - 1);
        if (idx - 1 == 0) {
            swiperButtonPrev.style.display = "none";
        } else {
            swiperButtonPrev.style.display = "flex";
        }
    }

    if (idx == carouselItemConLen - 1) {
        swiperButtonNext.style.display = "none";
    } else {
        swiperButtonNext.style.display = "flex";
    }

    if (idx == 0 && swiperSlides.length > 1) {
        swiperSlides[idx + 1].click();
        // document.getElementById('carousel-container').style.display = "block";
        swiperButtonPrev.style.display = "none";
    }

    if (swiperSlides.length == 1) {
        const carouselPrevCon = document.getElementById('carousel-container'); //A container that show preview of slides
        carouselPrevCon.style.display = 'none';
    }

    editContentId = "";

    if (document.querySelectorAll(".slider-card").length < 5) {
        $(".drag-and-drop-container").css({
            display: "flex"
        });
    }

    $("#carousel-card-length").html(document.querySelectorAll(".slider-card").length);
}


// add dynamic button 

//****************************************************** */

function carousel_select(idAndDataTargetAttribute, value) {
    // ####################################################
    if (document.getElementById(`${idAndDataTargetAttribute}`)) {
        // remvove its parent
        document.getElementById(`${idAndDataTargetAttribute}`).parentElement.remove();
    }

    let slide_id = $('.slider-card.carousel-card-selected').attr('id')
    if (slide_id) {
        const slide_text_container = $(`[data-slider-id="${slide_id}"]`).children().last().children().last();
        slide_text_container.append(getPreviewContent(idAndDataTargetAttribute, "", value));
    }
    // ####################################################
}