/**
 * Forumax – Avatar Upload Handler
 *
 * Handles the client-side logic for uploading and removing
 * custom profile avatars via AJAX on the bbPress user edit page.
 *
 * @package Forumax
 * @since   2.2.0
 */
( function( $ ) {
	'use strict';

	var $preview   = $( '#frmx-avatar-preview' ),
		$img       = $( '#frmx-avatar-img' ),
		$removeBtn = $( '#frmx-avatar-remove' ),
		$fileInput = $( '#frmx-avatar-input' ),
		$hiddenId  = $( '#frmx-avatar-id' ),
		$status    = $( '#frmx-avatar-status' );

	/**
	 * Display a temporary status message.
	 *
	 * @param {string} message The message text.
	 * @param {string} type    Status type: 'success', 'error', or 'info'.
	 */
	function showStatus( message, type ) {
		type = type || 'info';
		$status
			.removeClass( 'frmx-status-success frmx-status-error frmx-status-info' )
			.addClass( 'frmx-status-' + type )
			.text( message )
			.fadeIn( 200 );

		if ( 'info' !== type ) {
			setTimeout( function() {
				$status.fadeOut( 300 );
			}, 4000 );
		}
	}

	/**
	 * Handle avatar file selection and upload.
	 */
	$fileInput.on( 'change', function( e ) {
		var file = e.target.files[ 0 ];

		if ( ! file ) {
			return;
		}

		// Validate file type.
		var allowedTypes = [ 'image/jpeg', 'image/png', 'image/gif', 'image/webp' ];
		if ( allowedTypes.indexOf( file.type ) === -1 ) {
			showStatus( frmx_avatar.error, 'error' );
			$fileInput.val( '' );
			return;
		}

		// Validate file size.
		if ( file.size > frmx_avatar.max_size ) {
			showStatus( frmx_avatar.max_size_text, 'error' );
			$fileInput.val( '' );
			return;
		}

		// Show uploading status.
		showStatus( frmx_avatar.uploading, 'info' );
		$preview.addClass( 'frmx-avatar-uploading' );

		// Prepare form data.
		var formData = new FormData();
		formData.append( 'action', 'frmx_upload_avatar' );
		formData.append( 'nonce', frmx_avatar.nonce );
		formData.append( 'avatar_file', file );
		formData.append( 'user_id', $( 'input[name="bbp_user_id"]' ).val() || $( 'input[name="user_id"]' ).val() || '' );

		// Upload via AJAX.
		$.ajax( {
			url: frmx_avatar.ajax_url,
			type: 'POST',
			data: formData,
			processData: false,
			contentType: false,
			success: function( response ) {
				$preview.removeClass( 'frmx-avatar-uploading' );

				if ( response.success ) {
					$img.attr( 'src', response.data.avatar_url );
					$hiddenId.val( response.data.attachment_id );
					showStatus( response.data.message, 'success' );

					// Show remove button if not visible.
					if ( $removeBtn.length === 0 ) {
						$preview.append(
							'<button type="button" class="frmx-avatar-remove" id="frmx-avatar-remove" title="Remove Photo">' +
							'<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>' +
							'</button>'
						);
						$removeBtn = $( '#frmx-avatar-remove' );
					}
				} else {
					showStatus( response.data.message || frmx_avatar.error, 'error' );
				}
			},
			error: function() {
				$preview.removeClass( 'frmx-avatar-uploading' );
				showStatus( frmx_avatar.error, 'error' );
			}
		} );

		// Reset file input so the same file can be re-selected.
		$fileInput.val( '' );
	} );

	/**
	 * Handle avatar removal.
	 */
	$( document ).on( 'click', '#frmx-avatar-remove', function( e ) {
		e.preventDefault();

		if ( ! confirm( frmx_avatar.confirm ) ) {
			return;
		}

		showStatus( frmx_avatar.removing, 'info' );
		$preview.addClass( 'frmx-avatar-uploading' );

		$.ajax( {
			url: frmx_avatar.ajax_url,
			type: 'POST',
			data: {
				action: 'frmx_remove_avatar',
				nonce: frmx_avatar.nonce,
				user_id: $( 'input[name="bbp_user_id"]' ).val() || $( 'input[name="user_id"]' ).val() || ''
			},
			success: function( response ) {
				$preview.removeClass( 'frmx-avatar-uploading' );

				if ( response.success ) {
					$img.attr( 'src', response.data.avatar_url );
					$hiddenId.val( '' );
					$removeBtn.remove();
					$removeBtn = $( '#frmx-avatar-remove' );
					showStatus( response.data.message, 'success' );
				} else {
					showStatus( response.data.message || frmx_avatar.error, 'error' );
				}
			},
			error: function() {
				$preview.removeClass( 'frmx-avatar-uploading' );
				showStatus( frmx_avatar.error, 'error' );
			}
		} );
	} );
} )( jQuery );
