/**
 * Deactivation Survey
 * WP Mailinglist Plugin
 * Security: HTML escaping and input validation
 */

(function ($) {
    'use strict';

    // Security: HTML escape function
    function escapeHtml(text) {
        var map = {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#039;'
        };
        return String(text).replace(/[&<>"']/g, function (m) { return map[m]; });
    }

    $(document).ready(function () {
        // Hook into deactivation link for wp-mailinglist plugin
        var deactivateLink = $('tr[data-plugin*="wp-mailinglist"] .deactivate a, tr[data-plugin*="newsletters"] .deactivate a');

        if (deactivateLink.length > 0) {
            deactivateLink.on('click', function (e) {
                e.preventDefault();
                var deactivateUrl = $(this).attr('href');

                // Security: Validate URL
                if (deactivateUrl && deactivateUrl.indexOf('action=deactivate') !== -1) {
                    showDeactivationSurvey(deactivateUrl);
                }
            });
        }
    });

    function showDeactivationSurvey(deactivateUrl) {
        var modalHtml = '<div id="newsletters-deactivation-survey" style="position: relative; padding: 25px; max-width: 600px; font-family: -apple-system, BlinkMacSystemFont, \'Segoe UI\', Roboto, Oxygen-Sans, Ubuntu, Cantarell, \'Helvetica Neue\', sans-serif; border-radius: 8px; overflow: hidden;">' +
            '<button type="button" id="newsletters-close-modal" style="position: absolute; top: 12px; right: 12px; background: none; border: none; font-size: 24px; color: #666; cursor: pointer; padding: 0; width: 30px; height: 30px; line-height: 1; transition: color 0.2s;" title="Close">&times;</button>' +
            '<div style="display: flex; align-items: center; margin-bottom: 15px;">' +
            '<span class="dashicons dashicons-testimonial" style="font-size: 24px; color: #666; margin-right: 8px;"></span>' +
            '<h2 style="margin: 0; font-size: 18px; font-weight: 600; color: #23282d;">' + newsletters_survey_strings.quick_feedback + '</h2>' +
            '</div>' +
            '<p style="margin: 0 0 15px 0; color: #555; font-size: 14px; line-height: 1.5;">' + newsletters_survey_strings.intro + '</p>' +
            '<form id="newsletters-deactivation-form" style="border-top: 1px solid #e5e5e5; padding-top: 15px; margin-top: 15px;">' +
            '<div>' +
            '<label style="display: flex; align-items: center; padding: 8px; cursor: pointer; border-radius: 4px; transition: background-color 0.2s;" class="newsletters-reason-label">' +
            '<input type="radio" name="reason" value="found_better" style="margin: 0 8px 0 0; flex-shrink: 0;">' +
            '<span style="color: #23282d; font-size: 13px;">' + newsletters_survey_strings.reason_found_better + '</span>' +
            '</label>' +
            '</div>' +
            '<div>' +
            '<label style="display: flex; align-items: center; padding: 8px; cursor: pointer; border-radius: 4px; transition: background-color 0.2s;" class="newsletters-reason-label">' +
            '<input type="radio" name="reason" value="temporary" style="margin: 0 8px 0 0; flex-shrink: 0;">' +
            '<span style="color: #23282d; font-size: 13px;">' + newsletters_survey_strings.reason_temporary + '</span>' +
            '</label>' +
            '</div>' +
            '<div>' +
            '<label style="display: flex; align-items: center; padding: 8px; cursor: pointer; border-radius: 4px; transition: background-color 0.2s;" class="newsletters-reason-label">' +
            '<input type="radio" name="reason" value="missing_features" style="margin: 0 8px 0 0; flex-shrink: 0;">' +
            '<span style="color: #23282d; font-size: 13px;">' + newsletters_survey_strings.reason_missing_features + '</span>' +
            '</label>' +
            '</div>' +
            '<div>' +
            '<label style="display: flex; align-items: center; padding: 8px; cursor: pointer; border-radius: 4px; transition: background-color 0.2s;" class="newsletters-reason-label">' +
            '<input type="radio" name="reason" value="not_working" style="margin: 0 8px 0 0; flex-shrink: 0;">' +
            '<span style="color: #23282d; font-size: 13px;">' + newsletters_survey_strings.reason_not_working + '</span>' +
            '</label>' +
            '</div>' +
            '<div>' +
            '<label style="display: flex; align-items: flex-start; padding: 8px; cursor: pointer; border-radius: 4px; transition: background-color 0.2s;" class="newsletters-reason-label">' +
            '<input type="radio" name="reason" value="other" style="margin: 3px 8px 0 0; flex-shrink: 0;">' +
            '<span style="color: #23282d; font-size: 13px;">' + newsletters_survey_strings.reason_other + '</span>' +
            '</label>' +
            '</div>' +
            '<div id="newsletters-deactivation-details" style="display:none; margin: 12px 0 15px 0;">' +
            '<textarea name="details" rows="4" style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; font-size: 13px; font-family: inherit; resize: vertical; box-sizing: border-box;" placeholder="' + newsletters_survey_strings.placeholder_default + '"></textarea>' +
            '</div>' +
            '<div style="border-top: 1px solid #e5e5e5; padding-top: 15px; margin-top: 15px;">' +
            '<div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 10px;">' +
            '<div>' +
            '<button type="submit" class="button button-primary" style="margin-right: 8px; padding: 5px 14px; font-size: 13px;">' + newsletters_survey_strings.submit_btn + '</button>' +
            '<a href="' + deactivateUrl + '" class="button" style="padding: 5px 14px; text-decoration: none; font-size: 13px;">' + newsletters_survey_strings.skip_btn + '</a>' +
            '</div>' +
            '<a href="https://tribulant.com/support/" target="_blank" style="color: #0073aa; text-decoration: none; font-size: 12px; white-space: nowrap;">' + newsletters_survey_strings.support_link + '</a>' +
            '</div>' +
            '</div>' +
            '</form>' +
            '</div>';

        $.colorbox({
            html: modalHtml,
            width: '620px',
            closeButton: false,
            className: 'newsletters-deactivation-colorbox',
            onComplete: function () {
                // Add rounded corners to ColorBox
                $('#cboxLoadedContent').css('border-radius', '8px');

                // Close button handler
                $('#newsletters-close-modal').on('click', function () {
                    $.colorbox.close();
                });

                // Hover effect for reason labels
                $('.newsletters-reason-label').hover(
                    function () {
                        $(this).css('background-color', '#f5f5f5');
                    },
                    function () {
                        $(this).css('background-color', 'transparent');
                    }
                );

                // Show details textarea when any reason is selected
                $('input[name="reason"]').on('change', function () {
                    var reason = $(this).val();
                    var $details = $('#newsletters-deactivation-details');
                    var $textarea = $details.find('textarea');

                    // Update placeholder based on reason
                    if (reason === 'found_better') {
                        $textarea.attr('placeholder', newsletters_survey_strings.placeholder_found_better);
                    } else if (reason === 'not_working') {
                        $textarea.attr('placeholder', newsletters_survey_strings.placeholder_not_working);
                    } else if (reason === 'missing_features') {
                        $textarea.attr('placeholder', newsletters_survey_strings.placeholder_missing_features);
                    } else {
                        $textarea.attr('placeholder', newsletters_survey_strings.placeholder_default);
                    }

                    if (reason === 'other' || reason === 'found_better' || reason === 'not_working' || reason === 'missing_features') {
                        $details.slideDown(200, function () {
                            // Resize ColorBox after textarea is shown to prevent scrolling
                            $.colorbox.resize();
                        });
                    } else {
                        $details.slideUp(200, function () {
                            $.colorbox.resize();
                        });
                    }
                });

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

                    var reason = $('input[name="reason"]:checked').val();
                    var details = $('textarea[name="details"]').val();

                    if (!reason) {
                        alert(newsletters_survey_strings.alert_select_reason);
                        return;
                    }

                    var $submitBtn = $('#newsletters-deactivation-form button[type="submit"]');
                    var originalText = $submitBtn.text();
                    $submitBtn.prop('disabled', true).text(newsletters_survey_strings.submit_btn_loading);

                    // Step 1: Get signed payload from WordPress
                    $.ajax({
                        url: newslettersDeactivation.ajaxUrl,
                        type: 'POST',
                        data: {
                            action: 'newsletters_sign_deactivation',
                            nonce: newslettersDeactivation.nonce,
                            plugin_slug: 'wp-mailinglist',
                            plugin_name: 'Newsletters',
                            site_url: (window.location.host + window.location.pathname).replace(/\/wp-admin\/.*$/, ''),
                            reason: reason,
                            details: details
                        },
                        success: function (response) {
                            if (response.success && response.data.payload) {
                                // Step 2: Send signed payload to external endpoint
                                $.ajax({
                                    url: 'https://tribulant.com/deactivation_feedback',
                                    type: 'POST',
                                    contentType: 'application/json',
                                    data: JSON.stringify(response.data.payload),
                                    complete: function () {
                                        // Deactivate plugin regardless of response
                                        $.colorbox.close();
                                        window.location.href = deactivateUrl;
                                    }
                                });
                            } else {
                                // If signing fails, still allow deactivation
                                $.colorbox.close();
                                window.location.href = deactivateUrl;
                            }
                        },
                        error: function () {
                            // If signing fails, still allow deactivation
                            $.colorbox.close();
                            window.location.href = deactivateUrl;
                        }
                    });
                });
            }
        });
    }

})(jQuery);
