<?php

defined( 'ABSPATH' ) || exit;


// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals -- Block render: core-injected $attributes, $content, and $block in this scope.
/**
 * Server render: Event list block (Interactivity: time filter, pagination).
 *
 * @package clanbite
 */

use Kernowdev\Clanbite\Events\Event_Post_Type;

$scope    = sanitize_key( (string) ( $attributes['scopeType'] ?? 'team' ) );
$team_id  = (int) ( $attributes['teamId'] ?? 0 );
$group_id = (int) ( $attributes['groupId'] ?? 0 );
$max_list   = function_exists( 'clanbite_events_rest_max_per_page_paginated' )
	? clanbite_events_rest_max_per_page_paginated()
	: 50;
$default_pp = function_exists( 'clanbite_events_rest_default_per_page_paginated' )
	? clanbite_events_rest_default_per_page_paginated()
	: 20;
$limit      = max( 1, min( (int) $max_list, (int) ( $attributes['limit'] ?? $default_pp ) ) );

if ( $team_id < 1 ) {
	$team_id = (int) get_query_var( 'clanbite_events_team_id' );
}
if ( $group_id < 1 ) {
	$group_id = (int) get_query_var( 'clanbite_events_group_id' );
}
if ( $group_id < 1 && 'group' === $scope && function_exists( 'clanbite_group_profile_context_group_id' ) ) {
	$group_id = (int) clanbite_group_profile_context_group_id();
}

if ( 'team' === $scope && $team_id < 1 ) {
	$wrapper = get_block_wrapper_attributes( array( 'class' => 'clanbite-event-list clanbite-event-list--placeholder' ), $block );
	echo wp_kses( '<div ' . $wrapper . '><p>' . esc_html__( 'No team context for events.', 'clanbite' ) . '</p></div>', clanbite_block_fragment_allowed_html());
	return;
}

if ( 'group' === $scope && $group_id < 1 ) {
	$wrapper = get_block_wrapper_attributes( array( 'class' => 'clanbite-event-list clanbite-event-list--placeholder' ), $block );
	echo wp_kses( '<div ' . $wrapper . '><p>' . esc_html__( 'No group context for events.', 'clanbite' ) . '</p></div>', clanbite_block_fragment_allowed_html());
	return;
}

if ( 'team' === $scope && function_exists( 'clanbite_events_are_enabled_for_team' ) && ! clanbite_events_are_enabled_for_team( $team_id ) ) {
	return '';
}

if ( 'group' === $scope && function_exists( 'clanbite_events_are_enabled_for_group' ) && ! clanbite_events_are_enabled_for_group( $group_id ) ) {
	return '';
}

$config = array(
	'scope'      => 'team' === $scope ? Event_Post_Type::SCOPE_TEAM : Event_Post_Type::SCOPE_GROUP,
	'teamId'     => $team_id,
	'groupId'    => $group_id,
	'restUrl'    => esc_url_raw( rest_url( 'clanbite/v1/event-posts' ) ),
	'nonce'      => wp_create_nonce( 'wp_rest' ),
	'perPage'    => $limit,
	'maxPerPage' => (int) $max_list,
	'i18n'     => array(
		'timeAll'       => __( 'All', 'clanbite' ),
		'timeUpcoming'  => __( 'Upcoming', 'clanbite' ),
		'timePast'      => __( 'Past', 'clanbite' ),
		'loading'       => __( 'Loading…', 'clanbite' ),
		'noEvents'      => __( 'No events yet.', 'clanbite' ),
		'prev'          => __( 'Previous', 'clanbite' ),
		'next'          => __( 'Next', 'clanbite' ),
		'pageLabel'     => __( 'Page', 'clanbite' ),
		'error'         => __( 'Could not load events.', 'clanbite' ),
		'untitled'      => __( '(Untitled)', 'clanbite' ),
	),
);

$list_ssr_hydrated = false;
$list_ssr_total    = 0;
$list_ssr_rows     = '';

if ( function_exists( 'clanbite_events_block_query_collection' ) ) {
	$query_args = array(
		'page'       => 1,
		'per_page'   => $limit,
		'time_scope' => 'all',
		'order'      => 'asc',
	);
	if ( 'team' === $scope ) {
		$query_args['team_id'] = $team_id;
	} else {
		$query_args['group_id'] = $group_id;
	}
	$coll = clanbite_events_block_query_collection( $query_args );
	if ( ! is_wp_error( $coll ) ) {
		$list_ssr_total    = (int) ( $coll['total'] ?? 0 );
		$items             = isset( $coll['items'] ) && is_array( $coll['items'] ) ? $coll['items'] : array();
		$list_ssr_rows     = clanbite_events_render_event_list_rows_html( $items, $config['i18n'] );
		$list_ssr_hydrated = true;
	}
}

$config['ssrHydrated'] = $list_ssr_hydrated;
$config['ssrTotal']  = $list_ssr_total;

$cp_event_list_hide_pagination = ! $list_ssr_hydrated
	|| (int) ceil( max( 1, $list_ssr_total ) / max( 1, $limit ) ) <= 1;

$wrapper = get_block_wrapper_attributes(
	array(
		'class' => 'clanbite-event-list-wrap clanbite-event-list-wrap--interactive',
	),
	$block
);

$event_list_root_open = '<div '
	. trim( (string) $wrapper )
	. ' data-wp-interactive="clanbite-event-list"'
	. ' data-wp-context="' . esc_attr( wp_json_encode( $config ) ) . '"'
	. ' data-wp-init="callbacks.init"'
	. '>';
?>
<?php ob_start(); ?>
<?php clanbite_echo_block_fragment_html( $event_list_root_open ); ?>
	<div class="clanbite-event-list__toolbar">
		<label class="screen-reader-text" for="clanbite-event-list-time"><?php esc_html_e( 'Filter by time', 'clanbite' ); ?></label>
		<select id="clanbite-event-list-time" class="clanbite-event-list__time" data-wp-on--change="actions.onTimeScopeChange">
			<option value="all"><?php echo esc_html( $config['i18n']['timeAll'] ); ?></option>
			<option value="upcoming"><?php echo esc_html( $config['i18n']['timeUpcoming'] ); ?></option>
			<option value="past"><?php echo esc_html( $config['i18n']['timePast'] ); ?></option>
		</select>
	</div>
	<p class="clanbite-event-list__loading" hidden data-wp-bind--hidden="!state.isLoading()" aria-live="polite"><?php echo esc_html( $config['i18n']['loading'] ); ?></p>
	<p class="clanbite-event-list__error" hidden data-wp-bind--hidden="!state.errorMessage" data-wp-text="state.errorMessage" role="alert"></p>
	<ul class="clanbite-event-list"><?php clanbite_echo_block_fragment_html( $list_ssr_hydrated ? (string) $list_ssr_rows : '' ); ?></ul>
	<nav class="clanbite-event-list__pagination" data-wp-bind--hidden="!state.showPagination()" aria-label="<?php esc_attr_e( 'Events pagination', 'clanbite' ); ?>"<?php echo $cp_event_list_hide_pagination ? ' hidden' : ''; ?>>
		<button type="button" class="clanbite-event-list__page-btn" data-wp-on--click="actions.prevPage" data-wp-bind--disabled="state.isFirstPage()">
			<?php echo esc_html( $config['i18n']['prev'] ); ?>
		</button>
		<span class="clanbite-event-list__page-status">
			<span data-wp-text="state.pageLabel"></span>
		</span>
		<button type="button" class="clanbite-event-list__page-btn" data-wp-on--click="actions.nextPage" data-wp-bind--disabled="state.isLastPage()">
			<?php echo esc_html( $config['i18n']['next'] ); ?>
		</button>
	</nav>
</div>
<?php echo wp_kses( (string) ob_get_clean(), clanbite_block_fragment_allowed_html()); ?>
