<?php
/**
 * Hero module — registry, schema labels, body class.
 *
 * @package Kutby
 * @since   2.8.0
 */

declare(strict_types=1);

namespace Kutby\Modules;

use Kutby\Contracts\ModuleInterface;
use Kutby\Hero\Layouts\ClassicHero;
use Kutby\Hero\Layouts\GridHero;
use Kutby\Hero\Layouts\MagazineHero;
use Kutby\Hero\Layouts\MinimalHero;
use Kutby\Hero\Services\HeroRegistry;
use Kutby\Hero\Support\HeroContext;

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

/**
 * Class HeroModule
 */
final class HeroModule implements ModuleInterface {

	/**
	 * {@inheritdoc}
	 */
	public function register(): void {
		$registry = HeroRegistry::instance();
		$registry->add( 'classic', ClassicHero::class );
		$registry->add( 'magazine', MagazineHero::class );
		$registry->add( 'grid', GridHero::class );
		$registry->add( 'minimal', MinimalHero::class );

		/**
		 * Register additional hero layouts.
		 *
		 * @since 2.8.0
		 *
		 * @param HeroRegistry $registry Registry.
		 */
		do_action( 'kutby_hero_register_layouts', $registry );

		add_filter( 'kutby_options_schema', array( $this, 'filter_layout_options' ) );
		add_filter( 'body_class', array( $this, 'body_classes' ) );

		/**
		 * Hero module ready.
		 *
		 * @since 2.8.0
		 */
		do_action( 'kutby_hero_module_ready' );
	}

	/**
	 * {@inheritdoc}
	 */
	public function boot(): void {}

	/**
	 * @param array<int, string> $classes Classes.
	 * @return array<int, string>
	 */
	public function body_classes( array $classes ): array {
		if ( ! is_front_page() ) {
			return $classes;
		}

		$layout = HeroContext::from_request()->layout_id();
		if ( HeroRegistry::instance()->has( $layout ) ) {
			$classes[] = 'kutby-hero-layout-' . sanitize_html_class( $layout );
		}

		return $classes;
	}

	/**
	 * @param array<string, array<string, array<string, mixed>>> $schema Schema.
	 * @return array<string, array<string, array<string, mixed>>>
	 */
	public function filter_layout_options( array $schema ): array {
		$labels = HeroRegistry::instance()->labels();
		if ( empty( $labels ) || empty( $schema['hero']['layout'] ) ) {
			return $schema;
		}

		$schema['hero']['layout']['options'] = $labels;
		return $schema;
	}
}
