/**
 * Affiliate Stats Modal - Frontend behaviour.
 *
 * Expects `strpSubAffiliateModal` to be provided via wp_localize_script().
 */
jQuery( document ).ready( function ( $ ) {
	var cfg = window.strpSubAffiliateModal || {};

	$( '#open-affiliate-modal-btn' ).on( 'click', function () {
		$( '#affiliate-modal-overlay' ).addClass( 'is-visible' );
		$.post( cfg.ajaxUrl, {
			action:  'strp_sub_get_affiliate_referrals',
			user_id: cfg.userId,
			nonce:   cfg.referralsNonce
		}, function ( r ) {
			if ( r.success ) {
				var bd = $( r.data.summary ).filter( '.strp-sub-referral-breakdown' );
				if ( bd.length ) {
					$( '#affiliate-breakdown-section' ).html( bd );
				} else {
					$( '#affiliate-breakdown-section' ).html(
						'<p class="strp-sub-referral-stat-label" style="text-align:center;">' + cfg.i18n.noReferrals + '</p>'
					);
				}
			}
		} );
	} );

	$( '#affiliate-modal-close-btn, #affiliate-modal-overlay' ).on( 'click', function ( e ) {
		if ( e.target === this ) {
			$( '#affiliate-modal-overlay' ).removeClass( 'is-visible' );
		}
	} );

	$( '#affiliate-copy-code-btn' ).on( 'click', function () {
		navigator.clipboard.writeText( $( this ).data( 'code' ) );
	} );

	$( '#affiliate-payout-form' ).on( 'submit', function ( e ) {
		e.preventDefault();
		var btn = $( this ).find( 'button[type="submit"]' );
		btn.text( cfg.i18n.saving ).prop( 'disabled', true );
		$.post( cfg.ajaxUrl, {
			action:       'strp_sub_save_user_iban',
			iban:         $( '#affiliate_iban' ).val(),
			account_name: $( '#affiliate_account_name' ).val(),
			nonce:        cfg.ibanNonce
		}, function () {
			btn.text( cfg.i18n.saved ).css( 'background', '#00d4aa' );
			setTimeout( function () {
				btn.text( cfg.i18n.save ).prop( 'disabled', false ).css( 'background', '' );
			}, 2000 );
		} );
	} );
} );
