/**
 * Affiliate Plugin — Admin JavaScript
 *
 * Handles all admin-side interactivity for the Affiliate Management page:
 *   - Inline affiliate code editing
 *   - IBAN / account-name auto-save on blur
 *   - Payout modal open / close
 *   - CSV export trigger
 *
 * Nonces, AJAX URL, and translated strings are injected via wp_localize_script()
 * under the global `strp_sub_affiliate_admin` object, so they are always fresh and CSP-compliant.
 */
/* global strp_sub_affiliate_admin, jQuery */

(function($) {
    'use strict';

    $(document).ready(function() {

        // -------------------------------------------------------------------------
        // Inline affiliate-code editing
        // -------------------------------------------------------------------------

        $('.affp-edit-code-btn').on('click', function () {
            var $wrapper = $(this).closest('.affiliate-code-edit-wrapper');
            $wrapper.find('.affiliate-code-display, .affp-edit-code-btn').hide();
            $wrapper.find('.affiliate-code-edit-form').show().find('input').trigger('focus').trigger('select');
        });

        $('.affp-cancel-code-btn').on('click', function () {
            var $wrapper = $(this).closest('.affiliate-code-edit-wrapper');
            $wrapper.find('.affiliate-code-edit-form').hide();
            $wrapper.find('.affiliate-code-display, .affp-edit-code-btn').show();
        });

        $('.affp-save-code-btn').on('click', function () {
            var $wrapper = $(this).closest('.affiliate-code-edit-wrapper');
            var userId = $wrapper.data('user-id');
            var code = $wrapper.find('.affiliate-code-input').val().toUpperCase();

            $.post(
                strp_sub_affiliate_admin.ajax_url,
                {
                    action: 'strp_sub_save_custom_affiliate_code',
                    user_id: userId,
                    code: code,
                    nonce: strp_sub_affiliate_admin.save_code_nonce,
                },
                function (response) {
                    if (response.success) {
                        $wrapper.find('.affiliate-code-display').text(response.data.code).show();
                        $wrapper.find('.affp-edit-code-btn').show();
                        $wrapper.find('.affiliate-code-edit-form').hide();
                        _showNotice('success', strp_sub_affiliate_admin.i18n.code_updated);
                    } else {
                        _showNotice('error', response.data.message);
                    }
                }
            ).fail(function() {
                _showNotice('error', 'Network error. Please try again.');
            });
        });

        // -------------------------------------------------------------------------
        // IBAN & account-name auto-save on blur
        // -------------------------------------------------------------------------

        $(document).on('blur', '.affp-affiliate-iban-field', function () {
            var $field = $(this);
            $.post(strp_sub_affiliate_admin.ajax_url, {
                action: 'strp_sub_save_affiliate_iban',
                user_id: $field.data('user-id'),
                iban: $field.val(),
                nonce: strp_sub_affiliate_admin.save_code_nonce
            }).done(function(response) {
                if (!response.success) {
                    _showNotice('error', response.data && response.data.message ? response.data.message : (strp_sub_affiliate_admin.i18n && strp_sub_affiliate_admin.i18n.save_failed) || 'Save failed.');
                }
            }).fail(function() {
                _showNotice('error', (strp_sub_affiliate_admin.i18n && strp_sub_affiliate_admin.i18n.network_error) || 'Network error. Please try again.');
            });
        });

        $(document).on('blur', '.affp-affiliate-account-name-field', function () {
            var $field = $(this);
            $.post(strp_sub_affiliate_admin.ajax_url, {
                action: 'strp_sub_save_affiliate_account_name',
                user_id: $field.data('user-id'),
                account_name: $field.val(),
                nonce: strp_sub_affiliate_admin.save_code_nonce
            }).done(function(response) {
                if (!response.success) {
                    _showNotice('error', response.data && response.data.message ? response.data.message : (strp_sub_affiliate_admin.i18n && strp_sub_affiliate_admin.i18n.save_failed) || 'Save failed.');
                }
            }).fail(function() {
                _showNotice('error', (strp_sub_affiliate_admin.i18n && strp_sub_affiliate_admin.i18n.network_error) || 'Network error. Please try again.');
            });
        });

        // -------------------------------------------------------------------------
        // Payout modal
        // -------------------------------------------------------------------------

        $(document).on('click', '.affp-payout-btn', function () {
            var $trigger = $(this);
            $('#payout_user_id').val($trigger.data('user-id'));
            $('#payout_amount').val($trigger.data('amount'));
            $('#payout_affiliate_name').text($trigger.data('name'));
            var $modal = $('#affp-payout-modal');
            $modal.addClass('is-open').attr('aria-hidden', 'false');
            $modal.find('input, button, select').first().trigger('focus');
            $modal.data('trigger', $trigger);
        });

        function _closePayoutModal() {
            var $modal = $('#affp-payout-modal');
            $modal.removeClass('is-open').attr('aria-hidden', 'true');
            var $trigger = $modal.data('trigger');
            if ($trigger && $trigger.length) {
                $trigger.trigger('focus');
            }
        }

        $('#affp-cancel-payout').on('click', _closePayoutModal);

        $(document).on('keydown', function(e) {
            if (e.key === 'Escape' && $('#affp-payout-modal').hasClass('is-open')) {
                _closePayoutModal();
            }

            // Focus trap: keep Tab cycling within the payout modal while it is open.
            if (e.key === 'Tab' && $('#affp-payout-modal').hasClass('is-open')) {
                var $modal = $('#affp-payout-modal');
                var $focusable = $modal.find('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])').filter(':visible');
                if (!$focusable.length) {
                    return;
                }
                var firstEl = $focusable[0];
                var lastEl  = $focusable[$focusable.length - 1];

                if (e.shiftKey) {
                    if (document.activeElement === firstEl) {
                        e.preventDefault();
                        lastEl.focus();
                    }
                } else {
                    if (document.activeElement === lastEl) {
                        e.preventDefault();
                        firstEl.focus();
                    }
                }
            }
        });

        // -------------------------------------------------------------------------
        // CSV export
        // -------------------------------------------------------------------------

        $('#affp-export-affiliates').on('click', function () {
            var $form = $('<form>', { method: 'POST', action: strp_sub_affiliate_admin.ajax_url });
            $form.append($('<input>', { type: 'hidden', name: 'action', value: 'strp_sub_export_affiliates_csv' }));
            $form.append($('<input>', { type: 'hidden', name: 'nonce', value: strp_sub_affiliate_admin.export_nonce }));
            $form.appendTo('body').submit().remove();
        });

        // -------------------------------------------------------------------------
        // Internal: display a dismissible WP admin notice above the table
        // -------------------------------------------------------------------------

        function _showNotice(type, message) {
            var $notice = $('#affp-admin-notice');
            var dismiss = type === 'success' ? ' is-dismissible' : '';
            var $div = $('<div class="notice notice-' + type + dismiss + '" role="alert"><p></p></div>');
            $div.find('p').text(message);
            $notice.html($div).show();
            if (type === 'success') {
                setTimeout(function () {
                    $notice.fadeOut();
                }, 4000);
            }
            $('html,body').animate({ scrollTop: $notice.offset().top - 60 }, 300);
        }

    });
})(jQuery);
