<?php
/**
 * Team Count Block
 *
 * @package AmbassadorHub\Fundraisers\Blocks\TeamCount
 */

namespace AmbassadorHub\Fundraisers\Blocks\TeamCount;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use AmbassadorHub\Fundraisers\Blocks\Stats\Block as StatsBlock;

final class Block {
	public static function init(): void {
		add_action( 'init', array( self::class, 'register_block' ) );
	}

	public static function register_block(): void {
		$handle    = 'ambh-team-count-block';
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Fundraisers/Blocks/TeamCount/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Fundraisers/Blocks/TeamCount/';

		$script_file = $block_dir . 'index.js';
		if ( file_exists( $script_file ) ) {
			wp_register_script(
				$handle,
				$block_url . 'index.js',
				array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-server-side-render', 'wp-block-editor' ),
				filemtime( $script_file ),
				true
			);
		}

		wp_register_style(
			'ambh-team-count',
			$block_url . 'style.css',
			array(),
			file_exists( $block_dir . 'style.css' ) ? (string) filemtime( $block_dir . 'style.css' ) : AMBASSADOR_HUB_VERSION
		);

		$block_args = array(
			'style'           => 'ambh-team-count',
			'render_callback' => array( self::class, 'render_block' ),
		);

		if ( file_exists( $script_file ) ) {
			$block_args['editor_script'] = $handle;
		}

		register_block_type( $block_dir, $block_args );
	}

	public static function render_block( array $attributes = array() ): string {
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;">'
				. esc_html__( 'Team count.', 'ambassadorhub' )
				. '</div>';
		}

		$stats = StatsBlock::resolve_stats( $attributes );
		if ( array() === $stats || empty( $stats['team_count'] ) ) {
			return '';
		}

		$label         = 1 === (int) $stats['team_count'] ? esc_html__( 'Team', 'ambassadorhub' ) : esc_html__( 'Teams', 'ambassadorhub' );
		$wrapper_attrs = get_block_wrapper_attributes( array( 'class' => 'ambh-team-count-block' ) );

		ob_start();
		?>
		<div <?php echo $wrapper_attrs; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- sanitized by get_block_wrapper_attributes(). ?>>
			<div class="ambh-team-count-block__value"><?php echo esc_html( (string) $stats['team_count'] ); ?></div>
			<div class="ambh-team-count-block__label"><?php echo esc_html( $label ); ?></div>
			<div class="ambh-team-count-block__caption"><?php esc_html_e( 'Active in this fundraising context', 'ambassadorhub' ); ?></div>
		</div>
		<?php
		return (string) ob_get_clean();
	}
}