<?php
/**
 * Hero manager — resolve selected layout.
 *
 * @package Kutby
 * @since   2.8.0
 */

declare(strict_types=1);

namespace Kutby\Hero\Services;

use Kutby\Hero\Contracts\HeroLayoutInterface;
use Kutby\Hero\Support\HeroContext;

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

/**
 * Class HeroManager
 */
final class HeroManager {

	public const DEFAULT_LAYOUT = 'classic';

	/**
	 * @return HeroLayoutInterface
	 */
	public function layout(): HeroLayoutInterface {
		$ctx      = HeroContext::from_request();
		$id       = $ctx->layout_id();
		$registry = HeroRegistry::instance();

		$layout = $registry->make( $id );
		if ( null !== $layout ) {
			return $layout;
		}

		$fallback = $registry->make( self::DEFAULT_LAYOUT );
		if ( null !== $fallback ) {
			return $fallback;
		}

		foreach ( $registry->all() as $class ) {
			if ( is_subclass_of( $class, HeroLayoutInterface::class ) ) {
				return new $class();
			}
		}

		throw new \RuntimeException( 'No Kutby hero layouts registered.' );
	}
}
