/**
 * Cancellation Retention Flow — Frontend Modal Logic.
 *
 * @package StripeSubManager
 * @since   2.2.0
 */
(function($) {
    'use strict';

    var modal       = null;
    var currentStep = 'reason';
    var subId       = '';
    var reasonIndex = '';
    var offerType   = '';
    var offerData   = {};
    var params      = window.strp_sub_retention_params || {};
    var isProcessing = false;
    var triggerElement = null;

    function init() {
        modal = $('#strp-sub-retention-modal');
        if (!modal.length) return;

        // Open modal
        $(document).on('click', '.strp-sub-cancel-retention', function(e) {
            e.preventDefault();
            subId = $(this).data('subscription-id');
            triggerElement = this;
            openModal();
        });

        // Close modal
        modal.on('click', '.strp-retention-close, .strp-retention-close-btn', closeModal);
        modal.on('click', function(e) {
            if ($(e.target).hasClass('strp-retention-overlay')) closeModal();
        });
        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && modal.is(':visible')) closeModal();
        });

        // Step 1: Reason selection
        modal.on('change', 'input[name="cancel_reason"]', function() {
            $('#strp-retention-continue').prop('disabled', false);
            // Show/hide "Other" text field
            var isOther = $(this).closest('.strp-retention-reason-option').next('.strp-retention-other-text').length;
            modal.find('.strp-retention-other-text').slideUp(150);
            if (isOther) {
                $(this).closest('.strp-retention-reason-option').next('.strp-retention-other-text').slideDown(150);
            }
        });

        // Step 1 → Step 2: Submit reason
        modal.on('click', '#strp-retention-continue', submitReason);

        // Step 2: Accept offer
        modal.on('click', '#strp-retention-accept', acceptOffer);

        // Step 2: Decline offer → Step 3
        modal.on('click', '#strp-retention-decline', function() {
            showStep('confirm');
        });

        // Step 3: Confirm cancellation
        modal.on('click', '#strp-retention-confirm', confirmCancel);

        // Pause duration selector (dynamic)
        modal.on('click', '.strp-retention-pause-option', function() {
            modal.find('.strp-retention-pause-option').removeClass('selected');
            $(this).addClass('selected');
            offerData.pause_months = $(this).data('months');
        });

        // Downgrade plan selector
        modal.on('click', '.strp-retention-downgrade-option', function() {
            modal.find('.strp-retention-downgrade-option').removeClass('selected');
            $(this).addClass('selected');
            offerData.downgrade_price_id = $(this).data('price-id');
        });

        // Add class-based fallback for :has() CSS selector
        $('.strp-retention-reason-option input[type="radio"]').each(function() {
            $(this).on('change', function() {
                $('.strp-retention-reason-option').removeClass('strp-retention-reason-option--selected');
                if (this.checked) {
                    $(this).closest('.strp-retention-reason-option').addClass('strp-retention-reason-option--selected');
                }
            });
        });
    }

    function openModal() {
        currentStep = 'reason';
        modal.find('.strp-retention-step').hide();
        modal.find('[data-step="reason"]').show();
        modal.find('input[name="cancel_reason"]').prop('checked', false);
        modal.find('.strp-retention-other-text').val('').hide();
        modal.find('.strp-retention-reason-option').removeClass('strp-retention-reason-option--selected');
        $('#strp-retention-continue').prop('disabled', true);
        modal.attr('aria-hidden', 'false');
        modal.fadeIn(200, function() {
            trapFocus();
        });
    }

    function closeModal() {
        modal.attr('aria-hidden', 'true');
        modal.off('keydown.trapfocus');
        modal.fadeOut(200, function() {
            if (currentStep === 'success') {
                location.reload();
            } else if (triggerElement) {
                triggerElement.focus();
            }
        });
    }

    function showStep(step) {
        var validSteps = ['reason', 'offer', 'confirm', 'success'];
        if (validSteps.indexOf(step) === -1) return;
        currentStep = step;
        modal.find('.strp-retention-step').hide();
        modal.find('[data-step="' + step + '"]').fadeIn(200, function() {
            trapFocus();
        });
    }

    function showLoading(show) {
        modal.find('.strp-retention-loading').toggle(show);
        modal.find('.strp-retention-btn').prop('disabled', show);
    }

    function trapFocus() {
        var focusableSelector = 'button:visible, input:visible, textarea:visible, select:visible, a[href]:visible, [tabindex]:visible';
        var focusable = modal.find(focusableSelector);
        if (!focusable.length) return;

        focusable.first().focus();

        modal.off('keydown.trapfocus').on('keydown.trapfocus', function(e) {
            if (e.key !== 'Tab') return;
            var currentFocusable = modal.find(focusableSelector);
            var first = currentFocusable.first()[0];
            var last  = currentFocusable.last()[0];
            if (e.shiftKey) {
                if (document.activeElement === first) {
                    e.preventDefault();
                    last.focus();
                }
            } else {
                if (document.activeElement === last) {
                    e.preventDefault();
                    first.focus();
                }
            }
        });
    }

    function submitReason() {
        if (isProcessing) return;
        isProcessing = true;

        reasonIndex = modal.find('input[name="cancel_reason"]:checked').val();
        if (typeof reasonIndex === 'undefined') { isProcessing = false; return; }

        var otherText = modal.find('.strp-retention-other-text:visible').val() || '';

        showLoading(true);

        $.ajax({
            url:  params.ajax_url,
            type: 'POST',
            timeout: 30000,
            data: {
                action:          'strp_sub_retention_submit_reason',
                nonce:           params.nonce,
                subscription_id: subId,
                reason_index:    reasonIndex,
                reason_other:    otherText
            },
            success: function(response) {
                isProcessing = false;
                showLoading(false);
                if (response.success) {
                    offerType = response.data.offer_type;
                    offerData = response.data;

                    if (offerType === 'none' || response.data.cooldown_active) {
                        // Skip offer step — go straight to confirm
                        showStep('confirm');
                    } else {
                        // Server-rendered HTML from render_offer_card() with esc_html()/esc_attr() on all values.
                        // Trust chain: PHP render_offer_card() → esc_html/esc_attr/wp_kses_post → JSON response.
                        $('#strp-retention-offer-content').html(response.data.offer_html);
                        showStep('offer');
                    }
                } else {
                    showNotice(response.data.message || params.i18n_error, 'error');
                }
            },
            error: function() {
                isProcessing = false;
                showLoading(false);
                showNotice(params.i18n_error, 'error');
            }
        });
    }

    function acceptOffer() {
        if (isProcessing) return;
        isProcessing = true;
        showLoading(true);

        var data = {
            action:          'strp_sub_retention_accept_offer',
            nonce:           params.nonce,
            subscription_id: subId,
            offer_type:      offerType,
            reason_index:    reasonIndex
        };

        // Add offer-specific data
        if (offerType === 'pause' && offerData.pause_months) {
            data.pause_months = offerData.pause_months;
        }
        if (offerType === 'downgrade' && offerData.downgrade_price_id) {
            data.downgrade_price_id = offerData.downgrade_price_id;
        }

        $.ajax({
            url:  params.ajax_url,
            type: 'POST',
            timeout: 30000,
            data: data,
            success: function(response) {
                isProcessing = false;
                showLoading(false);
                if (response.success) {
                    showSuccess(
                        response.data.title || params.i18n_offer_accepted,
                        response.data.message || ''
                    );
                } else {
                    showNotice(response.data.message || params.i18n_error, 'error');
                }
            },
            error: function() {
                isProcessing = false;
                showLoading(false);
                showNotice(params.i18n_error, 'error');
            }
        });
    }

    function confirmCancel() {
        if (isProcessing) return;
        isProcessing = true;
        showLoading(true);

        $.ajax({
            url:  params.ajax_url,
            type: 'POST',
            timeout: 30000,
            data: {
                action:          'strp_sub_retention_confirm_cancel',
                nonce:           params.nonce,
                subscription_id: subId,
                reason_index:    reasonIndex,
                reason_other:    modal.find('.strp-retention-other-text:visible').val() || ''
            },
            success: function(response) {
                isProcessing = false;
                showLoading(false);
                if (response.success) {
                    showSuccess(
                        params.i18n_cancelled_title,
                        params.i18n_cancelled_message
                    );
                } else {
                    showNotice(response.data.message || params.i18n_error, 'error');
                }
            },
            error: function() {
                isProcessing = false;
                showLoading(false);
                showNotice(params.i18n_error, 'error');
            }
        });
    }

    function showSuccess(title, message) {
        $('#strp-retention-success-title').text(title);
        $('#strp-retention-success-message').text(message);
        showStep('success');
    }

    function showNotice(message, type) {
        var validTypes = ['error', 'success'];
        type = validTypes.indexOf(type) !== -1 ? type : 'error';
        // Remove any existing notices to prevent stacking.
        modal.find('.strp-retention-notice').remove();
        var $notice = $('<div class="strp-retention-notice strp-retention-notice--' + type + '" role="alert"></div>');
        $notice.text(message);
        modal.find('.strp-retention-modal').prepend($notice);
        setTimeout(function() { $notice.fadeOut(300, function() { $notice.remove(); }); }, 4000);
    }

    $(document).ready(init);

})(jQuery);
