<?php
/**
 * Campaign Info Block
 *
 * Displays the campaign information for the current fundraiser context.
 *
 * @package AmbassadorHub\Fundraisers\Blocks\CampaignInfo
 */

namespace AmbassadorHub\Fundraisers\Blocks\CampaignInfo;

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

/**
 * Block registration and server-side rendering.
 */
final class Block {
	/**
	 * Initialize the block.
	 *
	 * @return void
	 */
	public static function init(): void {
		add_action( 'init', array( self::class, 'register_block' ) );
	}

	/**
	 * Register block type, scripts, and styles.
	 *
	 * @return void
	 */
	public static function register_block(): void {
		$block_dir = AMBASSADOR_HUB_PATH . 'src/Fundraisers/Blocks/CampaignInfo/';
		$block_url = AMBASSADOR_HUB_URL . 'src/Fundraisers/Blocks/CampaignInfo/';

		// Editor script.
		$editor_handle = 'ambh-fundraiser-info-editor';
		$editor_file   = $block_dir . 'index.js';
		if ( file_exists( $editor_file ) ) {
			wp_register_script(
				$editor_handle,
				$block_url . 'index.js',
				array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-block-editor', 'wp-components' ),
				(string) filemtime( $editor_file ),
				true
			);
		}

		// Styles (shared between editor and frontend).
		$style_file = $block_dir . 'style.css';
		wp_register_style(
			'ambh-fundraiser-info',
			$block_url . 'style.css',
			array(),
			file_exists( $style_file ) ? (string) filemtime( $style_file ) : AMBASSADOR_HUB_VERSION
		);

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

		if ( file_exists( $editor_file ) ) {
			$block_args['editor_script'] = $editor_handle;
		}

		register_block_type( $block_dir, $block_args );
	}

	/**
	 * Server-side render callback.
	 *
	 * @param array $attributes Block attributes from block.json.
	 *
	 * @return string Rendered HTML.
	 */
	public static function render_block( array $attributes = array() ): string {
		// Editor placeholder — shown in the block editor canvas.
		if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
			return '<div style="padding: 20px; background: #f0f0f1; border: 1px solid #ddd; text-align: center;" class="ambh-block-preview">' . esc_html__( 'Fundraiser Info (renders on the frontend)', 'ambassadorhub' ) . '</div>';
		}

		$context = ContextResolver::resolve();
		if ( ! $context['fundraiser'] ) {
			return '';
		}

		// Pass block attributes to template
		$block_attrs = $attributes;
		ob_start();
		require __DIR__ . '/templates/campaign-info.php';
		return (string) ob_get_clean();
	}
}
