<?php
/**
 * Render callback for the Team Create Form block.
 *
 * @package clanbite
 */

defined( 'ABSPATH' ) || exit;

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Block render: core-injected $attributes, $content, and $block in this scope.

if ( 'team_directories' !== clanbite_teams_get_team_mode() ) {
	$wrapper_attributes = get_block_wrapper_attributes(
		array(
			'class' => 'clanbite-team-create-form clanbite-team-create-form--unavailable',
		),
		$block
	);
	echo wp_kses(
		'<div ' . $wrapper_attributes . '><p>' . esc_html__( 'Team creation is only available when Teams is set to "team directories" mode.', 'clanbite' ) . '</p></div>',
		clanbite_block_fragment_allowed_html()
	);
	return;
}

if ( ! is_user_logged_in() ) {
	echo '<p>' . esc_html__( 'You must be logged in to create a team.', 'clanbite' ) . '</p>';
	return;
}

$wrapper_attributes = get_block_wrapper_attributes( array( 'class' => 'clanbite-team-create-form' ), $block );

$status       = '';
$status_code  = '';
if ( isset( $_GET['_clanbite_team_notice'] ) ) {
	// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Only other `$_GET` keys are read after this nonce succeeds (flash notice from `redirect_after_team_create()`).
	$notice_nonce = sanitize_text_field( wp_unslash( (string) $_GET['_clanbite_team_notice'] ) );
	if ( '' !== $notice_nonce && wp_verify_nonce( $notice_nonce, 'clanbite_team_create_notice' ) ) {
		if ( isset( $_GET['clanbite_team_status'] ) ) {
			$status = sanitize_key( (string) wp_unslash( $_GET['clanbite_team_status'] ) );
		}
		if ( isset( $_GET['clanbite_team_code'] ) ) {
			$status_code = sanitize_key( (string) wp_unslash( $_GET['clanbite_team_code'] ) );
		}
	}
}

$steps = array(
	'basic_details' => array(
		'label'       => __( 'Step 1: Team Details', 'clanbite' ),
		'title'       => __( 'Team details', 'clanbite' ),
		'description' => __( 'Name your team and add optional text.', 'clanbite' ),
	),
	'branding'      => array(
		'label'       => __( 'Step 2: Team Avatar', 'clanbite' ),
		'title'       => __( 'Branding', 'clanbite' ),
		'description' => __( 'Upload an avatar and cover image.', 'clanbite' ),
	),
);

if ( (bool) apply_filters( 'clanbite_enable_team_create_invites_step', true ) ) {
	$steps['invites'] = array(
		'label'       => __( 'Step 3: Player invites', 'clanbite' ),
		'title'       => __( 'Invites', 'clanbite' ),
		'description' => __( 'Optionally invite players by search.', 'clanbite' ),
	);
}

/**
 * Filter create-team form steps.
 *
 * Third parties can add custom steps by appending a new keyed array item.
 * Each step may include:
 * - label (string) — default in-step heading fallback.
 * - title (string) — short tab title; falls back to label.
 * - description (string) — short tab subtitle (optional).
 *
 * @param array $steps Step map.
 */
$steps = (array) apply_filters( 'clanbite_team_create_form_steps', $steps );

$context             = array(
	'stepCount'         => count( $steps ),
	'inviteSearchUrl'   => admin_url( 'admin-ajax.php' ),
	'inviteSearchNonce' => wp_create_nonce( 'clanbite_team_invite_search' ),
);

$team_create_form_root_open = '<div '
	. trim( (string) $wrapper_attributes )
	. ' data-wp-interactive="clanbite-team-create-form"'
	. ' data-wp-context="' . esc_attr( wp_json_encode( $context ) ) . '"'
	. ' data-wp-init="callbacks.init"'
	. '>';
?>
<?php ob_start(); ?>
<?php clanbite_echo_block_fragment_html( $team_create_form_root_open ); ?>
	<?php do_action( 'clanbite_before_team_create_form' ); ?>
	<?php if ( 'success' === $status ) : ?>
		<p id="clanbite-team-create-notice" class="clanbite-team-create-form__notice is-success" role="status" tabindex="-1"><?php esc_html_e( 'Team created successfully.', 'clanbite' ); ?></p>
	<?php elseif ( 'error' === $status ) : ?>
		<p id="clanbite-team-create-notice" class="clanbite-team-create-form__notice is-error" role="alert" tabindex="-1"><?php echo esc_html( 'missing_name' === $status_code ? __( 'Team name is required.', 'clanbite' ) : ( 'wordban' === $status_code ? __( 'That text is not allowed.', 'clanbite' ) : __( 'Could not create team. Please try again.', 'clanbite' ) ) ); ?></p>
	<?php endif; ?>
	<form
		method="post"
		class="clanbite-team-create-form__form"
		action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>"
		enctype="multipart/form-data"
		data-active-step="1"
		data-wp-on--submit="actions.onSubmit"
	>
		<div class="clanbite-team-create-form__tabs" role="tablist" aria-label="<?php esc_attr_e( 'Create team steps', 'clanbite' ); ?>" aria-orientation="horizontal">
			<?php
			$tab_index = 1;
			foreach ( $steps as $tab_step ) :
				$tab_title = isset( $tab_step['title'] ) && $tab_step['title'] !== ''
					? $tab_step['title']
					: ( $tab_step['label'] ?? sprintf(
						/* translators: %d: Step number (1-based) in the create-team flow. */
						__( 'Step %d', 'clanbite' ),
						$tab_index
					) );
				$tab_description = isset( $tab_step['description'] ) ? (string) $tab_step['description'] : '';
				$is_first_tab    = 1 === $tab_index;
				$tab_class       = 'clanbite-team-create-form__tab' . ( $is_first_tab ? ' is-active' : ' is-upcoming' );
				?>
				<button
					type="button"
					class="<?php echo esc_attr( $tab_class ); ?>"
					role="tab"
					id="clanbite-team-create-form-tab-<?php echo esc_attr( (string) $tab_index ); ?>"
					data-team-tab="<?php echo esc_attr( (string) $tab_index ); ?>"
					data-wp-on--click="actions.goToStepTab"
					aria-controls="clanbite-team-create-form-panel-<?php echo esc_attr( (string) $tab_index ); ?>"
					aria-selected="<?php echo $is_first_tab ? 'true' : 'false'; ?>"
					tabindex="<?php echo $is_first_tab ? '0' : '-1'; ?>"
					<?php echo $is_first_tab ? '' : ' disabled'; ?>
				>
					<span class="clanbite-team-create-form__tab-index" aria-hidden="true"><?php echo esc_html( (string) $tab_index ); ?></span>
					<span class="clanbite-team-create-form__tab-text">
						<span class="clanbite-team-create-form__tab-title"><?php echo esc_html( $tab_title ); ?></span>
						<?php if ( $tab_description !== '' ) : ?>
							<span class="clanbite-team-create-form__tab-description"><?php echo esc_html( $tab_description ); ?></span>
						<?php endif; ?>
					</span>
				</button>
				<?php
				++$tab_index;
			endforeach;
			?>
		</div>
		<?php
		$step_number = 1;
		foreach ( $steps as $step_key => $step ) :
			?>
			<div
				class="clanbite-team-create-form__step"
				role="tabpanel"
				id="clanbite-team-create-form-panel-<?php echo esc_attr( (string) $step_number ); ?>"
				aria-labelledby="clanbite-team-create-form-tab-<?php echo esc_attr( (string) $step_number ); ?>"
				data-team-step="<?php echo esc_attr( $step_number ); ?>"
				<?php echo $step_number > 1 ? ' hidden' : ''; ?>
			>
				<?php if ( 'basic_details' === $step_key ) : ?>
					<p>
						<label for="clanbite-team-name"><?php esc_html_e( 'Team Name', 'clanbite' ); ?></label>
						<input type="text" id="clanbite-team-name" name="team_name" required />
					</p>
					<p class="description"><?php esc_html_e( 'Team slug will be generated from your team name.', 'clanbite' ); ?></p>
					<p>
						<label for="clanbite-team-code"><?php esc_html_e( 'Team Code', 'clanbite' ); ?></label>
						<input type="text" id="clanbite-team-code" name="team_code" />
					</p>
					<p>
						<label for="clanbite-team-motto"><?php esc_html_e( 'Team Motto', 'clanbite' ); ?></label>
						<input type="text" id="clanbite-team-motto" name="team_motto" />
					</p>
					<p>
						<label for="clanbite-team-description"><?php esc_html_e( 'Description', 'clanbite' ); ?></label>
						<textarea id="clanbite-team-description" name="team_description" rows="4"></textarea>
					</p>
					<p>
						<label for="clanbite-team-country"><?php esc_html_e( 'Country', 'clanbite' ); ?></label>
						<select id="clanbite-team-country" name="team_country" class="widefat">
							<option value=""><?php esc_html_e( '— Select —', 'clanbite' ); ?></option>
							<?php
							if ( function_exists( 'clanbite_players_get_countries' ) ) :
								foreach ( clanbite_players_get_countries() as $cc => $cname ) :
									?>
									<option value="<?php echo esc_attr( $cc ); ?>"><?php echo esc_html( $cname ); ?></option>
									<?php
								endforeach;
							endif;
							?>
						</select>
					</p>
				<?php elseif ( 'branding' === $step_key ) : ?>
					<div class="clanbite-team-create-form__media-row" aria-label="<?php esc_attr_e( 'Team avatar and cover', 'clanbite' ); ?>">
						<div class="clanbite-team-create-form__avatar-cover-preview">
							<div class="clanbite-team-create-form__cover-preview"></div>
							<div class="clanbite-team-create-form__avatar-preview"></div>
						</div>
						<div class="clanbite-team-create-form__media-buttons">
							<button
								type="button"
								class="clanbite-team-create-form__change-media clanbite-team-create-form__change-media--avatar"
								data-wp-on--click="actions.selectTeamAvatar"
							><?php esc_html_e( 'Set team avatar', 'clanbite' ); ?></button>
							<input
								type="file"
								id="clanbite-team-avatar"
								name="team_avatar"
								accept="image/png,image/jpeg"
								hidden
								data-wp-on--change="actions.updateTeamAvatar"
							/>
							<button
								type="button"
								class="clanbite-team-create-form__change-media clanbite-team-create-form__change-media--cover"
								data-wp-on--click="actions.selectTeamCover"
							><?php esc_html_e( 'Set cover image', 'clanbite' ); ?></button>
							<input
								type="file"
								id="clanbite-team-cover"
								name="team_cover"
								accept="image/png,image/jpeg"
								hidden
								data-wp-on--change="actions.updateTeamCover"
							/>
						</div>
					</div>
					<p class="description"><?php esc_html_e( 'PNG or JPEG images only.', 'clanbite' ); ?></p>
				<?php elseif ( 'invites' === $step_key ) : ?>
					<p>
						<label for="clanbite-team-invite-search"><?php esc_html_e( 'Invite players', 'clanbite' ); ?></label>
						<input
							type="text"
							id="clanbite-team-invite-search"
							autocomplete="off"
							role="combobox"
							aria-autocomplete="list"
							aria-expanded="false"
							aria-controls="clanbite-team-invite-suggestions-list"
							placeholder="<?php esc_attr_e( 'Search by username, display name, or email', 'clanbite' ); ?>"
							data-wp-on--input="actions.onInviteInput"
							data-wp-on--keydown="actions.onInviteKeydown"
						/>
					</p>
					<ul
						id="clanbite-team-invite-suggestions-list"
						class="clanbite-team-create-form__invite-suggestions"
						role="listbox"
						data-team-invite-suggestions
						data-wp-on--click="actions.onSuggestionClick"
					></ul>
					<div class="clanbite-team-create-form__invite-list" data-team-invite-list data-wp-on--click="actions.onInviteListClick"></div>
					<input type="hidden" name="team_invites" value="" data-team-invite-hidden />
				<?php elseif ( 'matches' === $step_key ) : ?>
					<div class="clanbite-team-create-form__matches-field">
						<p>
							<input type="hidden" name="team_accept_challenges" value="0" />
							<label for="clanbite-team-accept-challenges">
								<input
									type="checkbox"
									id="clanbite-team-accept-challenges"
									name="team_accept_challenges"
									value="1"
									checked
								/>
								<?php esc_html_e( 'Allow other teams to challenge this team', 'clanbite' ); ?>
							</label>
						</p>
						<p class="description"><?php esc_html_e( 'You can change this later from your team settings.', 'clanbite' ); ?></p>
					</div>
				<?php else : ?>
					<?php
					/**
					 * Render a custom create-team step.
					 *
					 * @param string $step_key Step key.
					 * @param array  $step Step config.
					 * @param int    $step_number Step number.
					 */
					do_action( 'clanbite_team_create_form_step', $step_key, $step, $step_number );
					do_action( "clanbite_team_create_form_step_{$step_key}", $step, $step_number );
					?>
				<?php endif; ?>
			</div>
			<?php
			$step_number++;
		endforeach;
		?>

		<div class="clanbite-team-create-form__actions clanbite-team-create-form__actions--split" role="navigation" aria-label="<?php esc_attr_e( 'Step navigation', 'clanbite' ); ?>">
			<button type="button" class="clanbite-team-create-form__nav-btn" data-wp-on--click="actions.previousStep" data-wp-bind--hidden="!state.canGoBack()" hidden><?php esc_html_e( 'Back', 'clanbite' ); ?></button>
			<div class="clanbite-team-create-form__actions-end">
				<button type="button" class="clanbite-team-create-form__nav-btn" data-wp-on--click="actions.nextStep" data-wp-bind--hidden="!state.canGoNext()"><?php esc_html_e( 'Next', 'clanbite' ); ?></button>
				<button type="submit" class="clanbite-team-create-form__nav-btn clanbite-team-create-form__nav-btn--primary" data-wp-bind--hidden="state.canGoNext()" hidden><?php esc_html_e( 'Create team', 'clanbite' ); ?></button>
			</div>
		</div>

		<?php wp_nonce_field( 'clanbite_create_team_action', '_clanbite_create_team_nonce' ); ?>
		<input type="hidden" name="action" value="clanbite_create_team" />
	</form>
	<?php do_action( 'clanbite_after_team_create_form' ); ?>
</div>
<?php echo wp_kses( (string) ob_get_clean(), clanbite_block_fragment_allowed_html()); ?>
