<?php
/**
 * Immutable header read model for one request.
 *
 * @package Kutby
 * @since   2.6.0
 */

declare(strict_types=1);

namespace Kutby\Header\Support;

use Kutby\ThemeOptions\Manager;

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

/**
 * Class HeaderContext
 */
final class HeaderContext {

	/**
	 * @var self|null
	 */
	private static ?self $request = null;

	/**
	 * @param array<string, mixed> $header Header option group.
	 * @param array<string, mixed> $social Social option group.
	 */
	private function __construct(
		private readonly array $header,
		private readonly array $social
	) {}

	/**
	 * Build once per request.
	 *
	 * @return self
	 */
	public static function from_request(): self {
		if ( null !== self::$request ) {
			return self::$request;
		}

		self::$request = new self(
			Manager::get_group( 'header', array() ),
			Manager::get_group( 'social', array() )
		);

		return self::$request;
	}

	/**
	 * @param string $key     Dot-free key in header group.
	 * @param mixed  $default Default.
	 * @return mixed
	 */
	public function get( string $key, mixed $default = null ): mixed {
		return $this->header[ $key ] ?? $default;
	}

	/**
	 * @param string $key Key.
	 * @return bool
	 */
	public function bool( string $key ): bool {
		return ! empty( $this->header[ $key ] );
	}

	/**
	 * @param string $key     Key.
	 * @param string $default Default.
	 * @return string
	 */
	public function string( string $key, string $default = '' ): string {
		return (string) ( $this->header[ $key ] ?? $default );
	}

	/**
	 * Selected layout id.
	 *
	 * @return string
	 */
	public function layout_id(): string {
		$id = $this->string( 'layout', 'classic' );
		return '' !== $id ? $id : 'classic';
	}

	/**
	 * @return array<string, mixed>
	 */
	public function social(): array {
		return $this->social;
	}

	/**
	 * Header height in px.
	 *
	 * @return int
	 */
	public function height(): int {
		return max( 48, min( 120, (int) $this->get( 'height', 72 ) ) );
	}
}
