/**
 * Admin related function handle from this file
 */

/** JS code for loading support link */
(function () {
    const targetHref = 'admin.php?page=minifly-help-center';
    const newHref = 'https://brainywp.com/support/';

    function modifyLink() {
        const link = document.querySelector(`a[href="${targetHref}"]`);
        if (link) {
            link.href = newHref;
            link.target = '_blank';
        }
    }

    // Run initially
    modifyLink();

    // Watch for changes in the DOM
    const observer = new MutationObserver(() => {
        modifyLink();
    });

    observer.observe(document.body, {
        childList: true,
        subtree: true
    });
})();

// Popup for pro features
function miniflyShowPopup() {
    document.getElementById('minifly-premium-popup').style.display = 'block';
    document.getElementById('minifly-premium-overlay').style.display = 'block';
}

function miniflyClosePopup() {
    document.getElementById('minifly-premium-popup').style.display = 'none';
    document.getElementById('minifly-premium-overlay').style.display = 'none';
}

// Popup for svg option
function sapmflySvgShowPopup() {
    document.getElementById("sapmfly-svg-popup").style.display = "block";
    document.getElementById("sapmfly-svg-overlay").style.display = "block";
}

function sapmflySvgClosePopup() {
    document.getElementById("sapmfly-svg-popup").style.display = "none";
    document.getElementById("sapmfly-svg-overlay").style.display = "none";
}

// Click to talk related code goes here
function miniflyClickTalkPopup() {
    document.getElementById('sapmfly-click-to-talk-block').style.display = 'block';
    document.getElementById('sapmfly-overlay').style.display = 'block';
}

document.addEventListener('DOMContentLoaded', function () {

    var closeBtn = document.querySelector(".click-chat-close-btn");
    var closeIcon = document.querySelector(".sapmfly-popup-close-btn");

    var popup = document.getElementById("sapmfly-click-to-talk-block");
    var overlay = document.getElementById("sapmfly-overlay");

    function closePopup(e) {
        popup.style.display = "none";
        overlay.style.display = "none";
    }

    // Close button
    if (closeBtn) {
        closeBtn.addEventListener('click', closePopup);
    }

    // Close icon
    if (closeIcon) {
        closeIcon.addEventListener('click', closePopup);
    }

    // Click outside popup
    if (overlay) {
        overlay.addEventListener('click', closePopup);
    }

});

// Click to call related code goes here
function miniflyClickCallPopup() {
    document.getElementById('sapmfly-click-to-call-block').style.display = 'block';
    document.getElementById('sapmfly-overlay').style.display = 'block';
}

document.addEventListener('DOMContentLoaded', function () {

    var closeBtn = document.querySelector(".click-call-close-btn");
    var closeIcon = document.querySelector(".sapmfly-popup-call-close-btn");

    var popup = document.getElementById("sapmfly-click-to-call-block");
    var overlay = document.getElementById("sapmfly-overlay");

    function closeCallPopup(e) {
        popup.style.display = "none";
        overlay.style.display = "none";
    }

    // Close button
    if (closeBtn) {
        closeBtn.addEventListener('click', closeCallPopup);
    }

    // Close icon
    if (closeIcon) {
        closeIcon.addEventListener('click', closeCallPopup);
    }

    // Click outside popup
    if (overlay) {
        overlay.addEventListener('click', closeCallPopup);
    }

});

// Floating button related code goes here
function miniflyFloatingBtnPopup() {
    document.getElementById('sapmfly-floating-btn-block').style.display = 'block';
    document.getElementById('sapmfly-overlay').style.display = 'block';
}

document.addEventListener('DOMContentLoaded', function () {

    var closeBtn = document.querySelector(".sapmfly-click-popup-close-icon");
    var closeIcon = document.querySelector(".sapmfly-floating-btn-close");

    var popup = document.getElementById("sapmfly-floating-btn-block");
    var overlay = document.getElementById("sapmfly-overlay");

    function closeCallPopup(e) {
        popup.style.display = "none";
        overlay.style.display = "none";
    }

    // Close button
    if (closeBtn) {
        closeBtn.addEventListener('click', closeCallPopup);
    }

    // Close icon
    if (closeIcon) {
        closeIcon.addEventListener('click', closeCallPopup);
    }

    // Click outside popup
    if (overlay) {
        overlay.addEventListener('click', closeCallPopup);
    }

});

document.addEventListener('click', function (e) {
    if (!e.target.closest('.sapmfly-floating-btn-clear')) return;

    const fields = [
        'sapmfly_floating_btn_text',
        'sapmfly_floating_btn_url',
        'sapmfly_floating_btn_color',
        'sapmfly_floating_btn_bg',
        'sapmfly_floating_btn_hover',
        'sapmfly_floating_btn_position'
    ];

    fields.forEach(id => {
        const field = document.getElementById(id);
        if (field) field.value = '';
    });

    // File input clear
    const fileInput = document.getElementById('sapmfly_floating_btn_icon');
    if (fileInput) fileInput.value = '';

    // Radio uncheck
    document
        .querySelectorAll('input[name="sapmfly_floating_btn_style"]')
        .forEach(r => r.checked = false);

    // mark image as deleted
    window.sapmflyFloatingBtnImageCleared = true;
});


// Call for global toggle all save
document.addEventListener('DOMContentLoaded', function () {
    const globalToggle = document.getElementById('sapmfly-global-toggle');
    const allToggles = document.querySelectorAll('.sapmfly-setting-toggle');
    const enableAllLabel = document.querySelector('.sapmfly-enable-all');
    const disableAllLabel = document.querySelector('.sapmfly-disable-all');

    function setAllToggles(state) {
        allToggles.forEach(toggle => {
            toggle.checked = state;
        });
        if (globalToggle) {
            globalToggle.checked = state;
        }
    }

    // Global toggle changes all
    if (globalToggle) {
        globalToggle.addEventListener('change', function () {
            setAllToggles(globalToggle.checked);
        });
    }

    // Manual Enable All click
    if (enableAllLabel) {
        enableAllLabel.style.cursor = 'pointer';
        enableAllLabel.addEventListener('click', function () {
            setAllToggles(true);
        });
    }

    // Manual Disable All click
    if (disableAllLabel) {
        disableAllLabel.style.cursor = 'pointer';
        disableAllLabel.addEventListener('click', function () {
            setAllToggles(false);
        });
    }

    // If any individual toggle is changed, update global toggle accordingly
    allToggles.forEach(toggle => {
        toggle.addEventListener('change', function () {
            const allChecked = Array.from(allToggles).every(t => t.checked);
            if (globalToggle) {
                globalToggle.checked = allChecked;
            }
        });
    });
});


// enable dark mood at admin panel
(function () {
    document.addEventListener('DOMContentLoaded', function () {
        const body = document.body;
        const toggle = document.getElementById('sapmfly-admin-dark-toggle');

        // Load from localStorage
        if (localStorage.getItem('sapmflyAdminDarkMode') === 'on') {
            body.classList.add('sapmfly-dark-mode');
        }

        // Only add event listener if toggle button exists
        if (toggle) {
            toggle.addEventListener('click', function () {
                body.classList.toggle('sapmfly-dark-mode');
                const mode = body.classList.contains('sapmfly-dark-mode') ? 'on' : 'off';
                localStorage.setItem('sapmflyAdminDarkMode', mode);
            });
        }
    });
})();


// Customization for back to top related popup goes here
document.addEventListener('DOMContentLoaded', function () {
    const body = document.body;

    // Open popup when any .sapmfly-open-popup is clicked
    body.addEventListener('click', function (e) {
        const openBtn = e.target.closest('.sapmfly-open-popup');
        if (openBtn) {
            const overlay = document.querySelector('.sapmfly-popup-overlay');
            if (overlay) {
                overlay.style.display = 'flex';
                overlay.style.alignItems = 'center';
                overlay.style.justifyContent = 'center';
            }
        }
    });

    // Close popup when any .sapmfly-close-popup is clicked
    body.addEventListener('click', function (e) {
        const closeBtn = e.target.closest('.sapmfly-close-popup');
        if (closeBtn) {
            const overlay = document.querySelector('.sapmfly-popup-overlay');
            const notice = document.querySelector('.sapmfly-popup-notice');
            if (overlay) overlay.style.display = 'none';
            if (notice) notice.style.display = 'none';
        }
    });

    // Close popup when clicking outside modal
    body.addEventListener('click', function (e) {
        const overlay = document.querySelector('.sapmfly-popup-overlay');
        const modal = document.querySelector('.sapmfly-popup-modal');
        if (
            overlay &&
            modal &&
            window.getComputedStyle(overlay).display !== 'none' &&
            e.target === overlay
        ) {
            overlay.style.display = 'none';
            const notice = document.querySelector('.sapmfly-popup-notice');
            if (notice) notice.style.display = 'none';
        }
    });

    // Save customization
    body.addEventListener('click', function (e) {
        const saveBtn = e.target.closest('.sapmfly-save-customization');
        if (saveBtn) {
            const overlay = document.querySelector('.sapmfly-popup-overlay');
            const notice = document.querySelector('.sapmfly-popup-notice');
            const colorInput = document.getElementById('sapmfly_bg_color');

            if (notice) notice.style.display = 'block';

            setTimeout(() => {
                if (notice) notice.style.display = 'none';
                if (overlay) overlay.style.display = 'none';
                // You can replace this with AJAX
            }, 1500);
        }
    });
});

// JS code to add back to top button color dynamically
document.addEventListener('click', function (e) {
    if (e.target.closest('.sapmfly-open-popup')) {
        const popupOverlay = document.querySelector('.sapmfly-popup-overlay');
        if (popupOverlay) {
            popupOverlay.style.display = 'block';
        }
    }
});

document.addEventListener('click', function (e) {
    if (e.target.closest('.sapmfly-close-popup')) {
        const popupOverlay = document.querySelector('.sapmfly-popup-overlay');
        if (popupOverlay) {
            popupOverlay.style.display = 'none';
        }
    }
});

document.addEventListener('click', function (e) {
    if (e.target.closest('.sapmfly-clear-customization')) {
        const bgColorInput = document.getElementById('sapmfly_bg_color');
        const hvColorInput = document.getElementById('sapmfly_hv_color');

        if (bgColorInput && hvColorInput) {
            bgColorInput.value = '';
            hvColorInput.value = '';
        }
    }
});

// Change back to top widget color
document.addEventListener('click', function (e) {
    if (e.target.closest('.sapmfly-save-customization')) {
        let bgHex = document.getElementById('sapmfly_bg_color')?.value.trim() || '';
        let hvHex = document.getElementById('sapmfly_hv_color')?.value.trim() || '';

        const defaultBg = '#4CAF50';
        const defaultHv = '#4CAF50';

        if (!bgHex) bgHex = defaultBg;
        if (!hvHex) hvHex = defaultHv;

        const isValidHex = hex => /^#([0-9A-F]{3}|[0-9A-F]{6})$/i.test(hex);

        if (!isValidHex(bgHex) || !isValidHex(hvHex)) {
            alert('Please enter valid 3- or 6-digit hex codes (e.g., #4CAF50 or #fff).');
            return;
        }

        fetch(ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams({
                action: 'sapmfly_save_back_top_color',
                hex_color: bgHex,
                hex_hover: hvHex,
                _wpnonce: sapmfly_ajax.nonce
            })
        })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const notice = document.querySelector('.sapmfly-popup-notice');
                    if (notice) {
                        notice.style.display = 'block';
                        setTimeout(() => {
                            notice.style.display = 'none';
                            const overlay = document.querySelector('.sapmfly-popup-overlay');
                            if (overlay) overlay.style.display = 'none';
                        }, 1200);
                    }
                } else {
                    alert('Error: ' + data.data);
                }
            });
    }
});


// Progress bar customization related code goes here
jQuery(document).ready(function ($) {

    /**
     * Open popup & load saved values
     */
    $('.sapmfly-open-pb-popup').on('click', function () {
        $('#sapmfly_pb_color').val(sapmfly_pb_data.color);
        $('#sapmfly_pb_height').val(sapmfly_pb_data.height);
        $('.sapmfly-pb-popup-overlay').fadeIn(100);
    });

    /**
     * Close popup on close button or outside click
     */
    $('.sapmfly-close-popup').on('click', function () {
        $('.sapmfly-pb-popup-overlay').fadeOut(200);
    });
    $(document).on('click', '.sapmfly-pb-popup-overlay', function (e) {
        if ($(e.target).hasClass('sapmfly-pb-popup-overlay')) {
            $('.sapmfly-pb-popup-overlay').fadeOut(200);
        }
    });

    /**
     * Save customization
     */
    $('.sapmfly-save-pb').on('click', function () {
        let color = $('#sapmfly_pb_color').val();
        let height = $('#sapmfly_pb_height').val();

        $.post(ajaxurl, {
            action: 'sapmfly_save_pb_customization',
            nonce: sapmfly_pb_data.nonce,
            color: color,
            height: height
        }, function (response) {
            $('.sapmfly-pb-popup-modal .sapmfly-success-msg, .sapmfly-pb-popup-modal .sapmfly-error-msg').remove();

            if (response.success) {
                sapmfly_pb_data.color = color;
                sapmfly_pb_data.height = height;
                $('<div class="sapmfly-success-msg" style="color:green;margin-top:10px;">' + response.data.message + '</div>')
                    .appendTo('.sapmfly-pb-popup-modal')
                    .delay(2000)
                    .fadeOut(400, function () { $(this).remove(); });
            } else {
                $('<div class="sapmfly-error-msg" style="color:red;margin-top:10px;">' + (response.data.message || 'Error saving settings.') + '</div>')
                    .appendTo('.sapmfly-pb-popup-modal')
                    .delay(3000)
                    .fadeOut(400, function () { $(this).remove(); });
            }
        });
    });

    /**
     * Clear values
     */
    $('.sapmfly-clear-pb').on('click', function () {
        $('#sapmfly_pb_color').val('');
        $('#sapmfly_pb_height').val('');
    });

});


// Admin footer credit edit related code goes here
jQuery(document).ready(function ($) {

    /**
     * Open popup & load saved value
     */
    $('.sapmfly-open-fc-popup').on('click', function () {
        $('#sapmfly_fc_input')
            .prop('disabled', false) // always enable when opening
            .removeClass('sapmfly-hidden-placeholder')
            .attr('placeholder', '')
            .val(sapmfly_fc_data.credit || '');
        $('.sapmfly-fc-popup-overlay').fadeIn(100);
    });

    /**
     * Close popup
     */
    $('.sapmfly-close-popup').on('click', function () {
        $('.sapmfly-fc-popup-overlay').fadeOut(200);
    });
    $(document).on('click', '.sapmfly-fc-popup-overlay', function (e) {
        if ($(e.target).hasClass('sapmfly-fc-popup-overlay')) {
            $('.sapmfly-fc-popup-overlay').fadeOut(200);
        }
    });

    /**
     * Save footer credit customization
     */
    function saveFooterCredit(credit) {
        $.post(ajaxurl, {
            action: 'sapmfly_save_fc_customization',
            nonce: sapmfly_fc_data.nonce,
            credit: credit
        }, function (response) {
            $('.sapmfly-fc-popup-modal .sapmfly-success-msg, .sapmfly-fc-popup-modal .sapmfly-error-msg').remove();

            if (response.success) {
                sapmfly_fc_data.credit = credit; // update local
                $('<div class="sapmfly-success-msg" style="color:green;margin-top:10px;">' + response.data.message + '</div>')
                    .appendTo('.sapmfly-fc-popup-modal')
                    .delay(1000)
                    .fadeOut(400, function () {
                        $(this).remove();
                        $('.sapmfly-fc-popup-overlay').fadeOut(200); // close popup
                    });
            } else {
                $('<div class="sapmfly-error-msg" style="color:red;margin-top:10px;">' + (response.data.message || 'Error saving settings.') + '</div>')
                    .appendTo('.sapmfly-fc-popup-modal')
                    .delay(3000)
                    .fadeOut(400, function () { $(this).remove(); });
            }
        });
    }

    /**
     * Save button click
     */
    $('.sapmfly-save-fc').on('click', function () {
        let credit = $('#sapmfly_fc_input').val();
        $('#sapmfly_fc_input')
            .prop('disabled', false)
            .removeClass('sapmfly-hidden-placeholder')
            .attr('placeholder', '');
        saveFooterCredit(credit);
    });

    /**
     * Clear button click
     */
    $('.sapmfly-clear-fc').on('click', function () {
        $('#sapmfly_fc_input')
            .val('')
            .prop('disabled', false)
            .removeClass('sapmfly-hidden-placeholder')
            .attr('placeholder', '');
        saveFooterCredit('');
    });

    /**
     * Empty button click
     */
    $('.sapmfly-empty-fc').on('click', function () {
        $('#sapmfly_fc_input')
            .val('')
            .prop('disabled', true)
            .addClass('sapmfly-hidden-placeholder')
            .attr('placeholder', 'Footer is hidden');
        saveFooterCredit('');
    });

});

/* Popup value saved success notice related js function code */
function sapmflyShowNotice(noticeId, message, type = 'success', callback = null) {
    const notice = document.getElementById(noticeId);
    if (!notice) return;

    notice.textContent = message;
    notice.style.backgroundColor = type === 'success' ? '#46b450' : '#dc3232';
    notice.style.color = '#fff';
    notice.style.padding = '10px 20px';
    notice.style.borderRadius = '4px';
    notice.style.position = 'fixed';
    notice.style.top = '20px';
    notice.style.right = '20px';
    notice.style.zIndex = 9999;
    notice.style.display = 'block';
    notice.style.opacity = '1';
    notice.style.transition = 'opacity 0.5s ease';

    // Hide after 4s
    setTimeout(() => {
        notice.style.opacity = '0';
        setTimeout(() => {
            notice.style.display = 'none';
            if (callback) callback();
        }, 500);
    }, 4000);
}

/* Handle click to talk data via AJAX */
document.addEventListener('click', function (e) {
    if (e.target.closest('.click-chat-save-btn')) {
        e.preventDefault();

        let heading = document
            .getElementById('sapmfly_click_talk_popup_heading')
            ?.value.trim() || '';

        let subheading = document
            .getElementById('sapmfly_click_talk_popup_subheading')
            ?.value.trim() || '';

        // QR Code image
        let fileInputQR = document.getElementById('sapmfly_click_talk_qr_image');
        let fileQR = fileInputQR && fileInputQR.files.length ? fileInputQR.files[0] : null;

        let highlighText = document
            .getElementById('sapmfly_click_talk_highlight_text')
            ?.value.trim() || '';

        let bgColor = document
            .getElementById('sapmfly_click_talk_color_bg')
            ?.value.trim() || '';

        // Agent 1 details 
        let agentOneName = document
            .getElementById('sapmfly_click_talk_agent_1_name')
            ?.value.trim() || '';

        let agentOneDesignation = document
            .getElementById('sapmfly_click_talk_agent_1_designation')
            ?.value.trim() || '';

        let agentOneNumber = document
            .getElementById('sapmfly_click_talk_agent_1_number')
            ?.value.trim() || '';

        let agentOneImage = document.getElementById('sapmfly_click_talk_agent_1_image');
        let fileAgentOneImage = agentOneImage && agentOneImage.files.length ? agentOneImage.files[0] : null;

        // Agent 2 details 
        let agentTwoName = document
            .getElementById('sapmfly_click_talk_agent_2_name')
            ?.value.trim() || '';

        let agentTwoDesignation = document
            .getElementById('sapmfly_click_talk_agent_2_designation')
            ?.value.trim() || '';

        let agentTwoNumber = document
            .getElementById('sapmfly_click_talk_agent_2_number')
            ?.value.trim() || '';

        let agentTwoImage = document.getElementById('sapmfly_click_talk_agent_2_image');
        let fileAgentTwoImage = agentTwoImage && agentTwoImage.files.length ? agentTwoImage.files[0] : null;

        // Agent 3 details 
        let agentThreeName = document
            .getElementById('sapmfly_click_talk_agent_3_name')
            ?.value.trim() || '';

        let agentThreeDesignation = document
            .getElementById('sapmfly_click_talk_agent_3_designation')
            ?.value.trim() || '';

        let agentThreeNumber = document
            .getElementById('sapmfly_click_talk_agent_3_number')
            ?.value.trim() || '';

        let agentThreeImage = document.getElementById('sapmfly_click_talk_agent_3_image');
        let fileAgentThreeImage = agentThreeImage && agentThreeImage.files.length ? agentThreeImage.files[0] : null;

        // FormData use handler
        let formData = new FormData();
        formData.append('action', 'sapmfly_save_click_talk_heading');
        formData.append('_wpnonce', sapmfly_click_talk_ajax.nonce);
        formData.append('sapmfly_click_talk_popup_heading', heading);
        formData.append('sapmfly_click_talk_popup_subheading', subheading);
        formData.append('sapmfly_click_talk_highlight_text', highlighText);
        formData.append('sapmfly_click_talk_color_bg', bgColor);

        // QR Code image
        if (fileQR) {
            formData.append('sapmfly_click_talk_qr_image', fileQR);
        }

        // Agent 1
        formData.append('sapmfly_click_talk_agent_1_name', agentOneName);
        formData.append('sapmfly_click_talk_agent_1_designation', agentOneDesignation);
        formData.append('sapmfly_click_talk_agent_1_number', agentOneNumber);
        if (fileAgentOneImage) {
            formData.append('sapmfly_click_talk_agent_1_image', fileAgentOneImage);
        }

        // Agent 2
        formData.append('sapmfly_click_talk_agent_2_name', agentTwoName);
        formData.append('sapmfly_click_talk_agent_2_designation', agentTwoDesignation);
        formData.append('sapmfly_click_talk_agent_2_number', agentTwoNumber);
        if (fileAgentTwoImage) {
            formData.append('sapmfly_click_talk_agent_2_image', fileAgentTwoImage);
        }

        // Agent 3
        formData.append('sapmfly_click_talk_agent_3_name', agentThreeName);
        formData.append('sapmfly_click_talk_agent_3_designation', agentThreeDesignation);
        formData.append('sapmfly_click_talk_agent_3_number', agentThreeNumber);
        if (fileAgentThreeImage) {
            formData.append('sapmfly_click_talk_agent_3_image', fileAgentThreeImage);
        }


        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(data => {
                const popup = document.getElementById('sapmfly-click-to-talk-block');
                const overlay = document.getElementById('sapmfly-overlay');

                if (data.success) {
                    sapmflyShowNotice(
                        'sapmfly-admin-notice-talk',
                        data.data,
                        'success',
                        function () {
                            if (popup) popup.style.display = 'none';
                            if (overlay) overlay.style.display = 'none';
                        }
                    );
                } else {
                    sapmflyShowNotice(
                        'sapmfly-admin-notice-talk',
                        'Error: ' + data.data,
                        'error'
                    );
                }
            });
    }
});

/* Handle Click Events via AJAX */
document.addEventListener('click', function (e) {

    /* ===============================
    CLICK TO CALL SAVE
    =============================== */
    const clickCallBtn = e.target.closest('.click-call-save-btn');
    if (clickCallBtn) {
        e.preventDefault();

        const formData = new FormData();
        formData.append('action', 'sapmfly_save_click_call_heading');
        formData.append('_wpnonce', sapmfly_click_call_ajax.nonce);

        formData.append(
            'sapmfly_click_call_popup_heading',
            document.getElementById('sapmfly_click_call_popup_heading')?.value.trim() || ''
        );

        formData.append(
            'sapmfly_click_call_popup_subheading',
            document.getElementById('sapmfly_click_call_popup_subheading')?.value.trim() || ''
        );

        formData.append(
            'sapmfly_click_call_highlight_text',
            document.getElementById('sapmfly_click_call_highlight_text')?.value.trim() || ''
        );

        formData.append(
            'sapmfly_click_call_color_bg',
            document.getElementById('sapmfly_click_call_color_bg')?.value.trim() || ''
        );

        // QR Image
        const qrInput = document.getElementById('sapmfly_click_call_qr_image');
        if (qrInput && qrInput.files.length) {
            formData.append('sapmfly_click_call_qr_image', qrInput.files[0]);
        }

        // Agent 4
        formData.append(
            'sapmfly_click_talk_agent_4_name',
            document.getElementById('sapmfly_click_talk_agent_4_name')?.value.trim() || ''
        );

        formData.append(
            'sapmfly_click_talk_agent_4_designation',
            document.getElementById('sapmfly_click_talk_agent_4_designation')?.value.trim() || ''
        );

        formData.append(
            'sapmfly_click_talk_agent_4_number',
            document.getElementById('sapmfly_click_talk_agent_4_number')?.value.trim() || ''
        );

        const agentImg = document.getElementById('sapmfly_click_talk_agent_4_image');
        if (agentImg && agentImg.files.length) {
            formData.append('sapmfly_click_talk_agent_4_image', agentImg.files[0]);
        }

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(data => handleResponse(
                data,
                'sapmfly-click-to-call-block'
            ))
            .catch(err => showAjaxError(err));

        return; // stop further checks
    }

    /* ===============================
    FLOATING BUTTON SAVE
    =============================== */
    const floatingBtn = e.target.closest('.sapmfly-floating-btn-save');
    if (floatingBtn) {
        e.preventDefault();

        const floatingBtnFormData = new FormData();
        floatingBtnFormData.append('action', 'sapmfly_floating_btn_handling');
        floatingBtnFormData.append('_wpnonce', sapmfly_floating_btn_ajax.nonce);

        floatingBtnFormData.append(
            'sapmfly_floating_btn_text',
            document.getElementById('sapmfly_floating_btn_text')?.value.trim() || ''
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_url',
            document.getElementById('sapmfly_floating_btn_url')?.value.trim() || ''
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_color',
            document.getElementById('sapmfly_floating_btn_color')?.value.trim() || ''
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_bg',
            document.getElementById('sapmfly_floating_btn_bg')?.value.trim() || ''
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_hover',
            document.getElementById('sapmfly_floating_btn_hover')?.value.trim() || ''
        );

        if (window.sapmflyFloatingBtnImageCleared) {
            floatingBtnFormData.append('sapmfly_floating_btn_icon_delete', '1');
        }

        const floatingBtnIcon = document.getElementById('sapmfly_floating_btn_icon');
        if (floatingBtnIcon && floatingBtnIcon.files.length) {
            floatingBtnFormData.append('sapmfly_floating_btn_icon', floatingBtnIcon.files[0]);
        }

        const style = document.querySelector(
            'input[name="sapmfly_floating_btn_style"]:checked'
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_style',
            style ? style.value : ''
        );

        const closeOption = document.querySelector(
            'input[name="sapmfly_floating_btn_close_option"]:checked'
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_close_option',
            closeOption ? closeOption.value : ''
        );

        const openLink = document.querySelector(
            'input[name="sapmfly_floating_btn_open_link"]:checked'
        );

        floatingBtnFormData.append(
            'sapmfly_floating_btn_open_link',
            openLink ? openLink.value : ''
        );


        floatingBtnFormData.append(
            'sapmfly_floating_btn_position',
            document.getElementById('sapmfly_floating_btn_position')?.value.trim() || ''
        );

        fetch(ajaxurl, {
            method: 'POST',
            body: floatingBtnFormData
        })
            .then(res => res.json())
            .then(data => handleResponse(
                data,
                'sapmfly-floating-btn-block',
                'sapmfly-admin-notice-floating'
            ))
            .catch(err => showAjaxError(err));
    }

    /* ===============================
ADD TO CART POPUP SAVE
=============================== */
    const cacSaveBtn = e.target.closest('.sapmfly-save-cac');
    if (cacSaveBtn) {
        e.preventDefault();

        const formData = new FormData();
        formData.append('action', 'sapmfly_save_cac_text');
        formData.append('_wpnonce', sapmfly_cac_ajax.nonce);

        formData.append(
            'sapmfly_cac_text',
            document.getElementById('sapmfly_cac_text')?.value.trim() || ''
        );

        fetch(ajaxurl, {
            method: 'POST',
            body: formData
        })
            .then(res => res.json())
            .then(data => handleResponse(
                data,
                'sapmfly-cac-popup-modal',
                'sapmfly-admin-notice-cac'
            ))
            .catch(err => console.error(err));

        return;
    }
});

/* Common Helpers */
function handleResponse(data, popupId, noticeId = 'sapmfly-admin-notice-call') {
    const popup = document.getElementById(popupId);
    const overlay = document.getElementById('sapmfly-overlay');

    if (data.success) {
        sapmflyShowNotice(
            noticeId,
            data.data || 'Saved successfully',
            'success',
            function () {
                if (popup) popup.style.display = 'none';
                if (overlay) overlay.style.display = 'none';
            }
        );
    } else {
        sapmflyShowNotice(
            noticeId,
            data.data || 'Something went wrong',
            'error'
        );
    }
}

function showAjaxError(error, noticeId = 'sapmfly-admin-notice-call') {
    sapmflyShowNotice(
        noticeId,
        'AJAX Error: ' + error.message,
        'error'
    );
}

// Configuration page related JS goes here
document.addEventListener('DOMContentLoaded', function () {

    /* Import Settings */
    const fileInput = document.getElementById('sapmfly_import_file');
    const actionBtn = document.getElementById('sapmfly-import-btn-trigger');
    const fileInfo = document.getElementById('sapmfly-file-info');
    const fileName = document.getElementById('sapmfly-file-name');
    const clearBtn = document.getElementById('sapmfly-clear-file');
    const realSubmit = document.getElementById('sapmfly-real-submit');

    // Only run if PRO elements exist
    if (fileInput && actionBtn && realSubmit) {

        actionBtn.addEventListener('click', function () {
            if (fileInput.files.length === 0) {
                fileInput.click();
            } else {
                realSubmit.click();
            }
        });

        fileInput.addEventListener('change', function () {
            if (this.files.length > 0) {

                if (fileName) {
                    fileName.textContent = this.files[0].name;
                }

                if (fileInfo) {
                    fileInfo.style.display = 'inline-flex';
                }

                actionBtn.textContent = 'Apply Settings';
                actionBtn.classList.replace('button-secondary', 'button-primary');
            }
        });

        if (clearBtn) {
            clearBtn.addEventListener('click', function () {
                fileInput.value = '';

                if (fileInfo) {
                    fileInfo.style.display = 'none';
                }

                actionBtn.textContent = 'Select JSON File';
                actionBtn.classList.replace('button-primary', 'button-secondary');
            });
        }
    }


    /* Reset Settings*/
    const resetInput = document.getElementById('sapmfly_reset_input');
    const resetSubmit = document.getElementById('sapmfly-submit-reset');

    if (resetInput && resetSubmit) {
        resetInput.addEventListener('input', function () {

            if (this.value.trim() === 'RESET') {
                resetSubmit.disabled = false;
                resetSubmit.style.opacity = '1';
            } else {
                resetSubmit.disabled = true;
                resetSubmit.style.opacity = '0.5';
            }

        });
    }

});


// Change Add to Cart popup related code
document.addEventListener('DOMContentLoaded', function () {

    const overlay = document.querySelector('.sapmfly-cac-popup-overlay');
    const modal = document.querySelector('.sapmfly-cac-popup-modal');
    const input = document.querySelector('#sapmfly_cac_text');

    document.addEventListener('click', function (e) {
        const overlay = document.querySelector('.sapmfly-cac-popup-overlay');
        const modal = document.querySelector('.sapmfly-cac-popup-modal');
        const input = document.querySelector('#sapmfly_cac_text');

        // OPEN popup
        if (e.target.closest('.sapmfly-open-cac-popup')) {
            if (overlay) {
                overlay.style.display = 'flex';
                overlay.style.alignItems = 'center';
                overlay.style.justifyContent = 'center';
            }
            return;
        }

        // CLOSE popup
        if (
            e.target.closest('.sapmfly-close-cac') ||
            e.target.closest('.sapmfly-popup-to-cart-close-btn')
        ) {
            if (overlay) overlay.style.display = 'none';
            return;
        }

        // CLICK outside modal
        if (
            overlay &&
            modal &&
            e.target === overlay
        ) {
            overlay.style.display = 'none';
            return;
        }

        // CLEAR input
        if (e.target.closest('.sapmfly-clear-cac')) {
            if (input) input.value = '';
            return;
        }
    });

    // Close popup when clicking outside modal
    document.addEventListener('click', function (e) {
        const overlay = document.querySelector('.sapmfly-cac-popup-overlay');
        const modal = document.querySelector('.sapmfly-cac-popup-modal');

        if (!overlay || !modal) return;

        const isOpen = overlay.style.display === 'flex';

        if (isOpen && e.target === overlay) {
            overlay.style.display = 'none';
        }
    });

});