<?php
/**
 * Header manager — resolve selected layout.
 *
 * @package Kutby
 * @since   2.6.0
 */

declare(strict_types=1);

namespace Kutby\Header\Services;

use Kutby\Header\Contracts\HeaderLayoutInterface;
use Kutby\Header\Support\HeaderContext;

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

/**
 * Class HeaderManager
 */
final class HeaderManager {

	public const DEFAULT_LAYOUT = 'classic';

	/**
	 * Resolve layout instance for the current request.
	 *
	 * @return HeaderLayoutInterface
	 */
	public function layout(): HeaderLayoutInterface {
		$ctx      = HeaderContext::from_request();
		$id       = $ctx->layout_id();
		$registry = HeaderRegistry::instance();

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

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

		// Absolute last resort: first registered layout.
		foreach ( $registry->all() as $class ) {
			if ( is_subclass_of( $class, HeaderLayoutInterface::class ) ) {
				return new $class();
			}
		}

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