<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Features;

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

use Signocore\Multilanguage\Infrastructure\Traits\Singleton;

/**
 * Sets RTL document direction and body class on the frontend when the active
 * language is flagged as RTL in the language registry. WordPress's native
 * is_rtl() depends on the loaded translation file's text-direction context,
 * which is unreliable when we switch locales via filter — we override based
 * on our own DB flag instead.
 */
final class RtlSupport
{
	use Singleton;

	protected function init(): void
	{
		add_filter('language_attributes', [$this, 'filterLanguageAttributes'], 20, 2);
		add_filter('body_class', [$this, 'filterBodyClass']);
	}

	/**
	 * Override the dir attribute on the <html> element when the active
	 * language is RTL.
	 *
	 * @param string $output The existing language attributes string.
	 * @param string $doctype The doctype the attributes are being built for.
	 */
	public function filterLanguageAttributes(string $output, string $doctype): string
	{
		if (!$this->isCurrentLanguageRtl()) {
			return $output;
		}

		// Strip any existing dir="..." and append dir="rtl"
		$output = (string) preg_replace('/\s*dir="[^"]*"/', '', $output);

		return trim($output . ' dir="rtl"');
	}

	/**
	 * Add an `rtl` body class when the active language is RTL.
	 *
	 * @param string[] $classes
	 * @return string[]
	 */
	public function filterBodyClass(array $classes): array
	{
		if ($this->isCurrentLanguageRtl() && !in_array('rtl', $classes, true)) {
			$classes[] = 'rtl';
		}

		return $classes;
	}

	/**
	 * Whether the currently detected language is flagged RTL in the registry.
	 */
	private function isCurrentLanguageRtl(): bool
	{
		$current = LanguageDetection::load()->getCurrentLanguage();
		$languages = LanguageManager::load()->getActiveLanguages();

		if (!isset($languages[$current])) {
			return false;
		}

		return (int) $languages[$current]->is_rtl === 1;
	}
}
