/**
 * Font Awesome Kit connector (Theme Options > Icons).
 *
 * Enqueued via config/assets-admin.php (loaded on usof admin pages; bundled into usof.min.js for
 * production), like the other usof field/panel scripts. Wires the connect / choose-kit / disconnect
 * buttons of the "fa_kit_panel" field to the US_FA_Kit AJAX endpoints. Depends only on jQuery + the admin
 * `ajaxurl` global — it is a no-op on pages where the field isn't present.
 */
( function( $ ) {

	function initField( $root ) {
		var nonce = $root.data( 'nonce' ),
			$token = $root.find( '.usof-fa-kit-token' ),
			$connectBtn = $root.find( '.usof-fa-kit-connect-btn' ),
			$choose = $root.find( '.usof-fa-kit-choose' ),
			$select = $root.find( '.usof-fa-kit-select' ),
			$saveBtn = $root.find( '.usof-fa-kit-save' ),
			$disconnectBtn = $root.find( '.usof-fa-kit-disconnect' ),
			$refreshBtn = $root.find( '.usof-fa-kit-refresh' ),
			$msg = $root.find( '.usof-fa-kit-message' ),
			$connected = $root.find( '.usof-fa-kit-connected' ),
			$disconnected = $root.find( '.usof-fa-kit-disconnected' );

		function message( text, isError ) {
			$msg.text( text || '' ).toggleClass( 'is-error', !! isError );
		}
		function busy( $btn, on ) {
			$btn.toggleClass( 'loading', !! on );
		}
		function errText( res ) {
			return ( res && res.data && res.data.message ) ? res.data.message : 'Request failed.';
		}

		// Shared AJAX wrapper: clears the busy state via .always() and surfaces transport-level
		// failures via .fail() (expired nonce -> 403, PHP timeout -> 500/504), which a plain success
		// callback never sees — the buttons used to spin forever on those, with no message.
		function post( action, data, $btn, onSuccess ) {
			message( '' );
			busy( $btn, true );
			$.post( ajaxurl, $.extend( { action: action, _ajax_nonce: nonce }, data ) )
				.always( function() {
					busy( $btn, false );
				} )
				.done( function( res ) {
					if ( ! res || ! res.success ) {
						message( errText( res ), true );
						return;
					}
					onSuccess( res.data || {} );
				} )
				.fail( function( jqXHR ) {
					var status = ( jqXHR && jqXHR.status ) ? ' (HTTP ' + jqXHR.status + ')' : '';
					message( errText( jqXHR && jqXHR.responseJSON ) + status, true );
				} );
		}

		$connectBtn.on( 'click', function() {
			var token = $.trim( $token.val() );
			if ( ! token ) {
				message( 'Enter your Font Awesome API Token.', true );
				return;
			}
			post( 'us_fa_kit_connect', { api_token: token }, $connectBtn, function( data ) {
				$select.empty();
				$.each( data.kits || [], function( i, kit ) {
					$select.append( $( '<option/>' )
						.val( kit.token )
						.text( kit.name + ' — ' + kit.version + ' (' + kit.license + ')' ) );
				} );
				$choose.removeClass( 'hidden' );
			} );
		} );

		$saveBtn.on( 'click', function() {
			var kitToken = $select.val();
			if ( ! kitToken ) {
				return;
			}
			post( 'us_fa_kit_select', { api_token: $.trim( $token.val() ), kit_token: kitToken }, $saveBtn, function( data ) {
				$connected.find( '.usof-fa-kit-name' )
					.text( data.name )
					.attr( 'href', data.url || '#' );
				$connected.find( '.usof-fa-kit-meta' ).text( '(' + $.trim( data.version + ' ' + data.license ) + ')' );
				$disconnected.addClass( 'hidden' );
				$choose.addClass( 'hidden' );
				$connected.removeClass( 'hidden' );
			} );
		} );

		$disconnectBtn.on( 'click', function() {
			post( 'us_fa_kit_disconnect', {}, $disconnectBtn, function() {
				$connected.addClass( 'hidden' );
				$disconnected.removeClass( 'hidden' );
				$token.val( '' );
			} );
		} );

		// Re-sync the connected kit using the stored token (no re-entry needed)
		$refreshBtn.on( 'click', function() {
			post( 'us_fa_kit_refresh', {}, $refreshBtn, function( data ) {
				$connected.find( '.usof-fa-kit-name' ).attr( 'href', data.url || '#' );
				$connected.find( '.usof-fa-kit-meta' ).text( '(' + $.trim( data.version + ' ' + data.license ) + ')' );
				var styles = data.styles || [];
				message( ( data.message || 'Refreshed.' ) + ( styles.length ? ' (' + styles.join( ', ' ) + ')' : '' ) );
			} );
		} );
	}

	$( function() {
		$( '.usof-fa-kit' ).each( function() {
			initField( $( this ) );
		} );
	} );

}( jQuery ) );
