<?php
/**
 * Widget registry — third parties register without touching Core.
 *
 * @package AuraBuilder
 */

declare(strict_types=1);

namespace AuraBuilder\Widgets;

final class WidgetRegistry {

	private static ?self $instance = null;

	/** @var array<string, WidgetInterface> */
	private array $widgets = array();

	public static function instance(): self {
		if ( null === self::$instance ) {
			self::$instance = new self();
		}
		return self::$instance;
	}

	public function register( WidgetInterface $widget ): void {
		$this->widgets[ $widget->get_type() ] = $widget;
	}

	public function get( string $type ): ?WidgetInterface {
		return $this->widgets[ $type ] ?? null;
	}

	/**
	 * @return list<string>
	 */
	public function types(): array {
		return array_keys( $this->widgets );
	}

	/**
	 * Catalog for the editor.
	 *
	 * @return list<array<string, mixed>>
	 */
	public function catalog(): array {
		$list = array();
		foreach ( $this->widgets as $w ) {
			if ( $w->get_type() === 'root' ) {
				continue;
			}
			$list[] = array(
				'type'     => $w->get_type(),
				'title'    => $w->get_title(),
				'category' => $w->get_category(),
				'icon'     => $w->get_icon(),
				'defaults' => $w->get_defaults(),
				'controls' => $w->get_controls(),
				'container'=> $w->is_container(),
			);
		}
		return $list;
	}
}
