jQuery(document).ready(function($) {
    var radioLabels = $(".zl-image-select-label");
    var imageContainer = $("#zl_selected_design_image");
    radioLabels.on("click", function() {
        radioLabels.removeClass("selected");
        $(this).addClass("selected");
        var selectedValue = $(this).find("input").val();
        imageContainer.html("<img src='" + scriptData.designOptions[selectedValue].image + "' alt='Selected Design' height='auto' width='700px'/>");
    });

    // Save the active tab as post meta
    var tabLinks = $('#zl-tabs ul li a');
    tabLinks.on("click", function() {
        var activeTab = $(this).attr("href");

        // Save the active tab as post meta using AJAX
        $.ajax({
            type: "POST",
            url: ajaxurl,
            data: {
                action: "save_active_tab",
                post_id: scriptData.postId,
                active_tab: activeTab,
                security:scriptData.security,
            },
        });
    });

    // Tabs (Hide all tab contents initially backend tab)
    jQuery("#zl-tabs").tabs();

    // Colorpicker
    $('.zl-my-color-field').wpColorPicker();

    // Top Rated
    $('#zl_testimo_top_rated').select2({
        placeholder: 'Select options',
        allowClear: false 
    });

    // Update the text field value when the range input changes
    $('#zl-range-field').on('input', function() {
        $('#zl-range-value').val($(this).val()+ 'ms');
    });

    // Hide and show Grid option(grid col,gap,padding,margin)
    $('#zl_testimoo_layout').on('change', function() {
        var $columnsSelect = $('#zl_grid_columns_select');
        if ($(this).val() === 'grid') {
            $columnsSelect.show();
        } else {
            $columnsSelect.hide();
        }
    });

    // Copy shortcode for inline and column shortcode
    $('.zl_shortcode_input,.column-shortcode').on('click', function() {
        var $input = $(this);
        $input.select();  // Select the text in the input
        // Copy the selected text to the clipboard
        document.execCommand('copy');
        // Display the toast notification
        toastr.options = {
            "positionClass": "toast-bottom-right"
        };
        toastr.success('Shortcode Copied!');
    });

    // Get stored tab link
    $(document).ready(function() {
        var storedTab = scriptData.activeTab;
        $('#zl-tabs ul li a').each(function() {
            if ($(this).attr('href') === storedTab) {
                $(this).click();
            }
        });
    });  
    
    // Custom Css code editor
    // var editor = CodeMirror.fromTextArea(jQuery('#zl-custom-css-editor')[0], {
    //     lineNumbers: true,
    //     mode: 'css',
    //     theme: 'default',
    //     matchBrackets: true,
    //     autoCloseBrackets: true,
    //     indentWithTabs: true,
    //     tabSize: 2
    // });

    // Function to create and display the modal
    function showModal(deactivateUrl) {
        // Create the modal form HTML
        var modalHtml = `
            <div id="zletc-deactivation-modal" class="zletc-plugin-deactivate-pop-up">
                <div class="zletc-plugin-deactivate-pop-up-content">
                    <h2>Easy Testimonials Carousel Feedback</h2>
                    <h3>If you have a moment, please let us know why you are deactivating:</h3>
                    <form id="zletc-deactivation-form">
                        <div class="form-body">
                            <ul class="zletc-reasons">
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="I found a better plugin.">
                                        <span>I found a better plugin</span>
                                    </label>
                                </li>
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="This plugin does not work on my site">
                                        <span>This plugin does not work on my site</span>
                                    </label>
                                </li>
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="Design is outdated, difficult to navigate">
                                        <span>Design is outdated, difficult to navigate</span>
                                    </label>
                                </li>
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="It's just temporary. I will be back soon.">
                                        <span>It's just temporary. I will be back soon</span>
                                    </label>
                                </li>
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="It is not what I am looking for.">
                                        <span>It is not what I am looking for</span>
                                    </label>
                                </li>
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="I am finding it difficult to configure it as per my needs">
                                        <span>I am finding it difficult to configure it as per my needs</span>
                                    </label>
                                </li>
                                <li class="reason">
                                    <label>
                                        <input type="radio" name="selected_reason" value="other">
                                        <span>Other</span>
                                    </label>
                                    <div>
                                        <textarea id="other_reason" name="other_reason" placeholder="Enter your reason (please specify)" class="zletc-other-reason"></textarea>
                                    </div>
                                </li>
                            </ul>
                        </div>
                        <div class="zletc-form-footer">
                            <input type="submit" class="button button-secondary" value="Submit and Deactivate">
                            <input type="button" id="zletc-skip-feedback-btn" class="button button-secondary" value="Skip and Deactivate">
                        </div>
                    </form>
                    <button id="zletc-modal-close" class="zletc-cancel-btn">
                        <svg height="18px" width="18px" id="Layer_1" style="enable-background:new 0 0 512 512;" version="1.1" viewBox="0 0 512 512" xmlns="http://www.w3.org/2000/svg"><path d="M443.6,387.1L312.4,255.4l131.5-130c5.4-5.4,5.4-14.2,0-19.6l-37.4-37.6c-2.6-2.6-6.1-4-9.8-4c-3.7,0-7.2,1.5-9.8,4  L256,197.8L124.9,68.3c-2.6-2.6-6.1-4-9.8-4c-3.7,0-7.2,1.5-9.8,4L68,105.9c-5.4,5.4-5.4,14.2,0,19.6l131.5,130L68.4,387.1  c-2.6,2.6-4.1,6.1-4.1,9.8c0,3.7,1.4,7.2,4.1,9.8l37.4,37.6c2.7,2.7,6.2,4.1,9.8,4.1c3.5,0,7.1-1.3,9.8-4.1L256,313.1l130.7,131.1  c2.7,2.7,6.2,4.1,9.8,4.1c3.5,0,7.1-1.3,9.8-4.1l37.4-37.6c2.6-2.6,4.1-6.1,4.1-9.8C447.7,393.2,446.2,389.7,443.6,387.1z"/></svg>
                    </button>
                </div>
            </div>
        `;

        // Append modal HTML to body
        $("body").append(modalHtml);
        $("#zletc-deactivation-modal").fadeIn();

        // Handle radio button change to show/hide textarea
        $("input[name='selected_reason']").on("change", function () {
        var $textarea = $("textarea[name='other_reason']");
        if ($(this).val() === "other") {
            $textarea.show().prop("required", true);
        } else {
            $textarea.hide().prop("required", false);
        }
        });

        // Handle form submission
        $("#zletc-deactivation-form").on("submit", function (e) {
        e.preventDefault();

        var $submitButton = $(this).find('input[type="submit"]');
        $submitButton.prop("disabled", true);

        var selectedReason = $("input[name='selected_reason']:checked").val();
        var otherReason = $("#other_reason").val().trim();

        var reason = selectedReason === "other" ? otherReason : selectedReason;

        if (!selectedReason) {
            alert("Please select a reason for deactivating.");
            $submitButton.prop("disabled", false);
            return;
        }

        $.ajax({
            url: ajaxurl,
            type: "POST",
            data: {
            action: "zletc_handle_deactivation_form",
            reason: reason,
            redirect: deactivateUrl,
            nonce: scriptData.deactivationNonce,
            },
            success: function (response) {
            $("#zletc-deactivation-modal").fadeOut(function () {
                $(this).remove();
                window.location.href = deactivateUrl;
            });
            },
            error: function (jqXHR, textStatus, errorThrown) {
            alert("AJAX request failed: " + textStatus + " - " + errorThrown);
            },
            complete: function () {
            setTimeout(function () {
                $submitButton.prop("disabled", false);
            }, 5000);
            },
        });
        });

        // Handle modal close button
        $(document).on("click", "#zletc-modal-close", function () {
        $("#zletc-deactivation-modal").fadeOut(function () {
            $(this).remove();
        });
        });

        // Handle skip feedback button
        $(document).on("click", "#zletc-skip-feedback-btn", function () {
        $("#zletc-deactivation-modal").fadeOut(function () {
            $(this).remove();
            window.location.href = deactivateUrl;
        });
        });
    }

    // Attach event handler to deactivate link
    $(document).on(
        "click",
        "#deactivate-easy-testimonials-carousel",
        function (e) {
        e.preventDefault();
        showModal($(this).attr("href"));
        }
    );
});




