<?php

declare(strict_types=1);

namespace Signocore\Multilanguage\Features;

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

use Signocore\Multilanguage\Application\Entitlements;
use Signocore\Multilanguage\Application\LicenseManager;
use Signocore\Multilanguage\Infrastructure\Traits\Singleton;

/**
 * Applies string translations on the frontend via WordPress/WooCommerce filters.
 */
final class StringTranslationHooks
{
	use Singleton;

	/** @var string Current widget ID being rendered (set by dynamic_sidebar_params filter). */
	private string $currentWidgetId = '';

	protected function init(): void
	{
		if (is_admin()) {
			return;
		}

		// Widget hooks
		add_filter('dynamic_sidebar_params', [$this, 'captureWidgetId']);
		add_filter('widget_title', [$this, 'translateWidgetTitle'], 20, 1);
		add_filter('widget_text_content', [$this, 'translateWidgetText'], 20, 2);
		add_filter('widget_custom_html_content', [$this, 'translateCustomHtmlContent'], 20, 3);
		add_filter('widget_display_callback', [$this, 'translateWidgetInstance'], 20, 3);

		// WooCommerce hooks (if active and licensed)
		if ($this->shouldLoadWooCommerceHooks()) {
			$this->registerWooCommerceHooks();
		}
	}

	// -------------------------------------------------------------------------
	// Widget hooks
	// -------------------------------------------------------------------------

	/**
	 * Capture the current widget ID before title/content filters fire.
	 *
	 * @param array<int, array<string, mixed>> $params
	 * @return array<int, array<string, mixed>>
	 */
	public function captureWidgetId(array $params): array
	{
		$this->currentWidgetId = $params[0]['widget_id'] ?? '';

		return $params;
	}

	/**
	 * Translate widget title using the captured widget ID.
	 */
	public function translateWidgetTitle(string $title): string
	{
		if ($title === '' || $this->currentWidgetId === '') {
			return $title;
		}

		return signocore_ml_translate_string('Widgets', $this->currentWidgetId . '_title', $title);
	}

	/**
	 * Translate text widget content.
	 *
	 * @param string $text
	 * @param array<string, mixed> $instance
	 */
	public function translateWidgetText(string $text, array $instance): string
	{
		if ($text === '' || $this->currentWidgetId === '') {
			return $text;
		}

		return signocore_ml_translate_string('Widgets', $this->currentWidgetId . '_text', $text);
	}

	/**
	 * Translate custom HTML widget content.
	 *
	 * @param string $content
	 * @param array<string, mixed> $instance
	 * @param \WP_Widget_Custom_HTML $widget
	 */
	public function translateCustomHtmlContent(string $content, array $instance, $widget): string
	{
		if ($content === '' || $this->currentWidgetId === '') {
			return $content;
		}

		return signocore_ml_translate_string('Widgets', $this->currentWidgetId . '_content', $content);
	}

	/**
	 * Translate widget instance data before rendering.
	 *
	 * Handles block widget content and image widget caption/alt.
	 *
	 * @param array<string, mixed>|false $instance
	 * @param \WP_Widget $widget
	 * @param array<string, mixed> $args
	 * @return array<string, mixed>|false
	 */
	public function translateWidgetInstance(array|false $instance, \WP_Widget $widget, array $args): array|false
	{
		if ($instance === false || $this->currentWidgetId === '') {
			return $instance;
		}

		// Block widget content
		if ($widget instanceof \WP_Widget_Block && !empty($instance['content']) && is_string($instance['content'])) {
			$instance['content'] = signocore_ml_translate_string(
				'Widgets',
				$this->currentWidgetId . '_content',
				$instance['content']
			);
		}

		// Image widget caption and alt text
		if ($widget instanceof \WP_Widget_Media_Image) {
			if (!empty($instance['caption']) && is_string($instance['caption'])) {
				$instance['caption'] = signocore_ml_translate_string(
					'Widgets',
					$this->currentWidgetId . '_caption',
					$instance['caption']
				);
			}
			if (!empty($instance['alt']) && is_string($instance['alt'])) {
				$instance['alt'] = signocore_ml_translate_string(
					'Widgets',
					$this->currentWidgetId . '_alt',
					$instance['alt']
				);
			}
		}

		return $instance;
	}

	// -------------------------------------------------------------------------
	// WooCommerce hooks
	// -------------------------------------------------------------------------

	private function registerWooCommerceHooks(): void
	{
		add_filter('woocommerce_gateway_title', [$this, 'translateGatewayTitle'], 10, 2);
		add_filter('woocommerce_gateway_description', [$this, 'translateGatewayDescription'], 10, 2);
		add_filter('woocommerce_attribute_label', [$this, 'translateAttributeLabel'], 10, 2);
		add_filter('woocommerce_package_rates', [$this, 'translateShippingRates'], 10, 2);
		add_action('woocommerce_email', [$this, 'registerEmailFilters']);
	}

	/**
	 * Translate payment gateway title on checkout.
	 */
	public function translateGatewayTitle(string $title, string $gatewayId): string
	{
		return signocore_ml_translate_string('WooCommerce', "gateway_{$gatewayId}_title", $title);
	}

	/**
	 * Translate payment gateway description on checkout.
	 */
	public function translateGatewayDescription(string $description, string $gatewayId): string
	{
		if ($description === '') {
			return $description;
		}

		return signocore_ml_translate_string('WooCommerce', "gateway_{$gatewayId}_description", $description);
	}

	/**
	 * Translate product attribute label.
	 */
	public function translateAttributeLabel(string $label, string $name): string
	{
		return signocore_ml_translate_string('WooCommerce', "attribute_{$name}", $label);
	}

	/**
	 * Translate shipping rate labels.
	 *
	 * @param array<string, \WC_Shipping_Rate> $rates
	 * @param array<string, mixed> $package
	 * @return array<string, \WC_Shipping_Rate>
	 */
	public function translateShippingRates(array $rates, array $package): array
	{
		foreach ($rates as $rate) {
			$instanceId = $rate->get_instance_id();
			if ($instanceId <= 0) {
				continue;
			}

			$original = $rate->get_label();
			$translated = signocore_ml_translate_string('WooCommerce', "shipping_{$instanceId}_title", $original);

			if ($translated !== $original) {
				$rate->set_label($translated);
			}
		}

		return $rates;
	}

	/**
	 * Register email subject and heading filters for each WC email type.
	 *
	 * @param \WC_Emails $mailer
	 */
	public function registerEmailFilters($mailer): void
	{
		$emails = $mailer->get_emails();
		if (!is_array($emails)) {
			return;
		}

		foreach ($emails as $email) {
			$emailId = $email->id ?? '';
			if ($emailId === '') {
				continue;
			}

			add_filter("woocommerce_email_subject_{$emailId}", function (string $subject) use ($emailId): string {
				return signocore_ml_translate_string('WooCommerce', "email_{$emailId}_subject", $subject);
			});

			add_filter("woocommerce_email_heading_{$emailId}", function (string $heading) use ($emailId): string {
				return signocore_ml_translate_string('WooCommerce', "email_{$emailId}_heading", $heading);
			});

			add_filter("woocommerce_email_additional_content_{$emailId}", function (string $content) use ($emailId): string {
				return signocore_ml_translate_string('WooCommerce', "email_{$emailId}_additional_content", $content);
			});
		}
	}

	/**
	 * Check if WooCommerce hooks should be loaded.
	 */
	private function shouldLoadWooCommerceHooks(): bool
	{
		return class_exists('WooCommerce')
			&& LicenseManager::load()->can(Entitlements::WOOCOMMERCE);
	}
}
