<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\UI\Blocks;

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

use Signocore\Multilanguage\Application\Constants;
use Signocore\Multilanguage\Features\LanguageSwitcher as LanguageSwitcherFeature;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;

/**
 * Registers the Language Switcher Gutenberg block.
 */
final class LanguageSwitcher
{
	use Singleton;

	protected function init(): void
	{
		add_action('init', [$this, 'registerBlock']);
	}

	/**
	 * Register the block type.
	 */
	public function registerBlock(): void
	{
		wp_register_script(
			'sml-block-language-switcher-editor',
			plugins_url('assets/js/blocks/language-switcher.js', SIGNOCORE_ML_FILE),
			['wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-server-side-render'],
			Constants::$pluginVersion,
			true
		);

		wp_register_style(
			'sml-switcher',
			plugins_url('assets/css/switcher.css', SIGNOCORE_ML_FILE),
			[],
			Constants::$pluginVersion
		);

		wp_register_style(
			'sml-block-language-switcher-editor',
			plugins_url('assets/css/blocks/language-switcher-editor.css', SIGNOCORE_ML_FILE),
			['sml-switcher'],
			Constants::$pluginVersion
		);

		register_block_type('signocore-multilanguage/language-switcher', [
			'api_version' => '3',
			'title' => __('Language Switcher', 'signocore-multilanguage'),
			'description' => __('Display a language switcher for visitors to change languages.', 'signocore-multilanguage'),
			'category' => 'widgets',
			'icon' => 'translation',
			'keywords' => [
				__('language', 'signocore-multilanguage'),
				__('translation', 'signocore-multilanguage'),
				__('multilingual', 'signocore-multilanguage'),
			],
			'supports' => [
				'html' => false,
				'align' => true,
				'className' => true,
			],
			'attributes' => [
				'style' => [
					'type' => 'string',
					'default' => 'dropdown',
					'enum' => ['dropdown', 'list', 'flags', 'inline'],
				],
				'showFlags' => [
					'type' => 'boolean',
					'default' => true,
				],
				'showNames' => [
					'type' => 'boolean',
					'default' => true,
				],
			],
			'editor_script_handles' => ['sml-block-language-switcher-editor'],
			'editor_style_handles' => ['sml-block-language-switcher-editor'],
			'render_callback' => [$this, 'render'],
		]);
	}

	/**
	 * Server-side render callback for the block.
	 *
	 * @param array{style?: string, showFlags?: bool, showNames?: bool, className?: string} $attributes
	 */
	public function render(array $attributes): string
	{
		$style = $attributes['style'] ?? 'dropdown';
		$showFlags = $attributes['showFlags'] ?? true;
		$showNames = $attributes['showNames'] ?? true;
		$extraClass = $attributes['className'] ?? '';

		$switcher = LanguageSwitcherFeature::load();

		return $switcher->render([
			'style' => $style,
			'show_flags' => $showFlags,
			'show_names' => $showNames,
			'class' => $extraClass,
		]);
	}
}
