<?php
/**
 * REEID Translate — menu label runtime fallback.
 *
 * Uses existing saved menu-label translations only.
 * Does not scan, warm, translate, or expose extra admin screens.
 *
 * @package REEID_Translate
 */

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

if ( ! function_exists( 'reeid_menu_label_normalize' ) ) {
	/**
	 * Normalize a menu label to match legacy saved menu-label keys.
	 *
	 * @param string $text Source label.
	 * @return string
	 */
	function reeid_menu_label_normalize( $text ) {
		static $cache = array();

		$text = (string) $text;

		if ( isset( $cache[ $text ] ) ) {
			return $cache[ $text ];
		}

		$normalized = html_entity_decode( $text, ENT_QUOTES | ENT_HTML5, 'UTF-8' );
		$normalized = wp_strip_all_tags( $normalized );
		$normalized = trim( $normalized );

		if ( function_exists( 'mb_strtolower' ) ) {
			$normalized = mb_strtolower( $normalized, 'UTF-8' );
		} else {
			$normalized = strtolower( $normalized );
		}

		$normalized = preg_replace( '/[[:punct:]]+/u', '', $normalized );
		$normalized = preg_replace( '/\s+/u', ' ', (string) $normalized );
		$normalized = trim( (string) $normalized );

		$cache[ $text ] = $normalized;

		return $normalized;
	}
}

if ( ! function_exists( 'reeid_menu_label_saved_translation' ) ) {
	/**
	 * Look up a saved menu-label translation.
	 *
	 * @param string $label Source/current label.
	 * @param string $lang  Target language.
	 * @return string
	 */
	function reeid_menu_label_saved_translation( $label, $lang ) {
		$label = trim( wp_strip_all_tags( (string) $label ) );
		$lang  = sanitize_key( (string) $lang );

		if ( '' === $label || '' === $lang ) {
			return '';
		}

		$norm = reeid_menu_label_normalize( $label );

		$overrides = get_option( 'reeid_ui_dictionary_overrides', array() );
		$overrides = is_array( $overrides ) ? $overrides : array();

		if (
			isset( $overrides[ $lang ] ) &&
			is_array( $overrides[ $lang ] ) &&
			isset( $overrides[ $lang ][ $norm ] ) &&
			is_string( $overrides[ $lang ][ $norm ] ) &&
			'' !== trim( $overrides[ $lang ][ $norm ] )
		) {
			return sanitize_text_field( wp_strip_all_tags( $overrides[ $lang ][ $norm ] ) );
		}

		$stored = get_option( 'reeid_ui_dictionary', array() );
		$stored = is_array( $stored ) ? $stored : array();

		if ( empty( $stored ) ) {
			return '';
		}

		$decoded = html_entity_decode( $label, ENT_QUOTES | ENT_HTML5, 'UTF-8' );

		$candidates = array_unique(
			array(
				$norm,
				trim( (string) $decoded ),
				$label,
			)
		);

		foreach ( $candidates as $candidate ) {
			$key = md5( $lang . '|' . (string) $candidate );

			if (
				isset( $stored[ $key ] ) &&
				is_string( $stored[ $key ] ) &&
				'' !== trim( $stored[ $key ] )
			) {
				return sanitize_text_field( wp_strip_all_tags( $stored[ $key ] ) );
			}
		}

		return '';
	}
}

add_filter(
	'wp_nav_menu_objects',
	function ( $items, $args ) {
		if ( is_admin() || ! is_array( $items ) || empty( $items ) ) {
			return $items;
		}

		if ( ! function_exists( 'reeid_current_language' ) ) {
			return $items;
		}

		$lang        = sanitize_key( (string) reeid_current_language() );
		$source_lang = sanitize_key( (string) get_option( 'reeid_translation_source_lang', 'en' ) );

		if ( '' === $source_lang ) {
			$source_lang = 'en';
		}

		if ( '' === $lang || $lang === $source_lang ) {
			return $items;
		}

		foreach ( $items as $item ) {
			if ( ! is_object( $item ) || empty( $item->title ) || ! is_string( $item->title ) ) {
				continue;
			}

			if ( ! empty( $item->ID ) ) {
				$manual = get_post_meta( (int) $item->ID, '_reeid_menu_label_overrides', true );
				$manual = is_array( $manual ) ? $manual : array();

				if (
					isset( $manual[ $lang ] ) &&
					is_string( $manual[ $lang ] ) &&
					'' !== trim( $manual[ $lang ] )
				) {
					$item->title = sanitize_text_field( wp_strip_all_tags( $manual[ $lang ] ) );
					continue;
				}
			}

			$title = trim( (string) $item->title );

			$title = preg_replace( '/\s*-\s*[0-9.]+\s*km$/i', '', $title );
			$title = preg_replace( '/\s*-\s*km$/i', '', (string) $title );
			$title = ltrim( (string) $title, '- ' );
			$title = trim( (string) $title );

			if ( '' === $title ) {
				continue;
			}

			$saved = reeid_menu_label_saved_translation( $title, $lang );

			if ( '' !== $saved ) {
				$item->title = $saved;
			}
		}

		return $items;
	},
	28,
	2
);


if ( ! function_exists( 'reeid_prepare_menu_label_translations_for_lang' ) ) {
	/**
	 * Prepare saved menu-label translations for one language.
	 *
	 * Runs only after an authorized admin translation action.
	 * No frontend OpenAI calls. No background worker.
	 *
	 * @param string $lang Target language.
	 * @return void
	 */
	function reeid_prepare_menu_label_translations_for_lang( $lang ) {
		$lang = sanitize_key( (string) $lang );

		if ( '' === $lang ) {
			return;
		}

		$source_lang = sanitize_key( (string) get_option( 'reeid_translation_source_lang', 'en' ) );

		if ( '' === $source_lang ) {
			$source_lang = 'en';
		}

		if ( $lang === $source_lang ) {
			return;
		}

		if ( ! function_exists( 'wp_get_nav_menus' ) || ! function_exists( 'wp_get_nav_menu_items' ) ) {
			return;
		}

		if ( ! function_exists( 'reeid_translate_html_with_openai' ) ) {
			return;
		}

		$menus = wp_get_nav_menus();

		if ( empty( $menus ) ) {
			return;
		}

		$labels = array();

		foreach ( (array) $menus as $menu ) {
			$items = wp_get_nav_menu_items( $menu->term_id );

			if ( ! is_array( $items ) ) {
				continue;
			}

			foreach ( $items as $item ) {
				if ( ! isset( $item->title ) || ! is_string( $item->title ) ) {
					continue;
				}

				$label = trim( wp_strip_all_tags( html_entity_decode( $item->title, ENT_QUOTES | ENT_HTML5, 'UTF-8' ) ) );

				if ( '' === $label || '-' === $label ) {
					continue;
				}

				$labels[] = $label;
			}
		}

		$labels = array_values( array_unique( array_filter( $labels, 'strlen' ) ) );

		if ( empty( $labels ) ) {
			return;
		}

		$stored = get_option( 'reeid_ui_dictionary', array() );
		$stored = is_array( $stored ) ? $stored : array();

		$missing = array();

		foreach ( $labels as $label ) {
			$norm = reeid_menu_label_normalize( $label );

			if ( '' === $norm ) {
				continue;
			}

			$key = md5( $lang . '|' . $norm );

			if (
				! isset( $stored[ $key ] ) ||
				! is_string( $stored[ $key ] ) ||
				'' === trim( $stored[ $key ] )
			) {
				$missing[] = $label;
			}
		}

		$missing = array_slice( array_values( array_unique( $missing ) ), 0, 30 );

		if ( empty( $missing ) ) {
			return;
		}

		foreach ( $missing as $label ) {
			$translated = reeid_translate_html_with_openai(
				$label,
				$source_lang,
				$lang,
				'classic',
				'neutral',
				'Translate this navigation menu label only. Return only the translated label.'
			);

			$translated = is_string( $translated ) ? trim( wp_strip_all_tags( $translated ) ) : '';

			if ( '' === $translated || $translated === $label ) {
				continue;
			}

			$norm = reeid_menu_label_normalize( $label );

			if ( '' === $norm ) {
				continue;
			}

			$stored[ md5( $lang . '|' . $norm ) ] = sanitize_text_field( $translated );
		}

		update_option( 'reeid_ui_dictionary', $stored, false );
	}
}