jQuery(document).ready(function ($) {
    'use strict';

    // Find the deactivate link for our plugin
    const pluginSlug = 'codeandcore-user-registration-cf7/codeandcore-user-registration-cf7.php';
    const $deactivateLink = $(`tr[data-plugin="${pluginSlug}"] .deactivate a`);

    if (!$deactivateLink.length) {
        return;
    }

    let deactivateUrl = '';

    // Intercept deactivate click
    $deactivateLink.on('click', function (e) {
        e.preventDefault();
        deactivateUrl = $(this).attr('href');
        showDeactivationModal();
    });

    function showDeactivationModal() {
        // Create modal HTML
        const modalHTML = `
            <div id="cnc-cf7-deactivation-modal" class="cnc-cf7-modal-overlay">
                <div class="cnc-cf7-modal-container">
                    <div class="cnc-cf7-modal-header">
                        <h2>Deactivation Reason</h2>
                        <button class="cnc-cf7-modal-close">&times;</button>
                    </div>
                    <div class="cnc-cf7-modal-body">
                        <div class="cnc-cf7-reasons-grid">
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Just Debugging">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-admin-tools"></span>
                                <span class="cnc-cf7-reason-text">Just Debugging</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Plugin Issues">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-warning"></span>
                                <span class="cnc-cf7-reason-text">Plugin Issues</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Slow Performance">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-update"></span>
                                <span class="cnc-cf7-reason-text">Slow Performance</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Switched to Alternative">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-randomize"></span>
                                <span class="cnc-cf7-reason-text">Switched to Alternative</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="No Longer Needed">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-archive"></span>
                                <span class="cnc-cf7-reason-text">No Longer Needed</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Compatibility Issues">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-dismiss"></span>
                                <span class="cnc-cf7-reason-text">Compatibility Issues</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Missing Feature">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-star-empty"></span>
                                <span class="cnc-cf7-reason-text">Missing Feature</span>
                            </label>
                            <label class="cnc-cf7-reason-option">
                                <input type="radio" name="deactivation_reason" value="Other Reason">
                                <span class="cnc-cf7-reason-icon dashicons dashicons-editor-help"></span>
                                <span class="cnc-cf7-reason-text">Other Reason</span>
                            </label>
                        </div>

                        <div class="cnc-cf7-details-section" style="display: none;">
                            <textarea 
                                id="cnc-cf7-details" 
                                placeholder="Please share the reason"
                                rows="4"
                            ></textarea>
                        </div>

                        <div class="cnc-cf7-contact-section">
                            <p class="cnc-cf7-contact-text">
                                After submitting, we'll get in touch with you via email to provide the support you need. 
                                If you require any help, please <a href="https://wordpress.org/support/plugin/codeandcore-user-registration-cf7/" target="_blank">Create A Ticket</a>, 
                                we reply within 24 working hours.
                            </p>
                            
                            <label class="cnc-cf7-checkbox-label">
                                <input type="checkbox" id="cnc-cf7-agree-contact">
                                <span>I agree to be contacted via email for support with this plugin.</span>
                            </label>
                        </div>
                    </div>
                    <div class="cnc-cf7-modal-footer">
                        <a href="#" class="cnc-cf7-link-skip">Skip & Deactivate</a>
                        <button class="cnc-cf7-btn-submit" disabled>Submit & Deactivate</button>
                    </div>
                </div>
            </div>
        `;

        // Append modal to body
        $('body').append(modalHTML);

        const $modal = $('#cnc-cf7-deactivation-modal');
        const $detailsSection = $('.cnc-cf7-details-section');
        const $agreeCheckbox = $('#cnc-cf7-agree-contact');
        const $submitBtn = $('.cnc-cf7-btn-submit');

        // Function to check if submit should be enabled
        function updateSubmitButton() {
            const hasReason = $('input[name="deactivation_reason"]:checked').length > 0;
            const hasConsent = $agreeCheckbox.is(':checked');

            if (hasReason || hasConsent) {
                $submitBtn.prop('disabled', false);
            } else {
                $submitBtn.prop('disabled', true);
            }
        }

        // Show details textarea when a reason is selected
        $('input[name="deactivation_reason"]').on('change', function () {
            $detailsSection.slideDown();
            updateSubmitButton();
        });

        // Update submit button when checkbox changes
        $agreeCheckbox.on('change', function () {
            updateSubmitButton();
        });

        // Close modal
        $('.cnc-cf7-modal-close, .cnc-cf7-modal-overlay').on('click', function (e) {
            if (e.target === this) {
                $modal.remove();
            }
        });

        // Skip & Deactivate
        $('.cnc-cf7-link-skip').on('click', function (e) {
            e.preventDefault();
            window.location.href = deactivateUrl;
        });

        // Submit & Deactivate
        $('.cnc-cf7-btn-submit').on('click', function () {
            const reason = $('input[name="deactivation_reason"]:checked').val() || '';
            const details = $('#cnc-cf7-details').val();
            const agreeContact = $agreeCheckbox.is(':checked') ? 'yes' : 'no';

            // Disable button to prevent double submission
            $(this).prop('disabled', true).text('Submitting...');

            // Send AJAX request
            $.ajax({
                url: cnc_cf7_deactivation.ajax_url,
                type: 'POST',
                data: {
                    action: 'cnc_cf7_submit_deactivation_reason',
                    nonce: cnc_cf7_deactivation.nonce,
                    reason: reason,
                    details: details,
                    agree_contact: agreeContact
                },
                success: function () {
                    // Redirect to deactivation URL
                    window.location.href = deactivateUrl;
                },
                error: function () {
                    // Even on error, proceed with deactivation
                    window.location.href = deactivateUrl;
                }
            });
        });
    }
});
