<?php
/**
 * Front-end helpers for language-aware nav menu locations.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translation_filter_nav_menu_locations_option' ) ) {
    /**
     * Ensures non-default languages fall back to default menu assignments when needed.
     *
     * @param mixed $value Stored option value.
     *
     * @return array<string, array<string, int>>
     */
    function wpr_translation_filter_nav_menu_locations_option( $value ) {
        // Normalize stored values to a consistent map.
        $normalized = wpr_translation_normalize_nav_menu_locations_map( $value );

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

        if ( is_admin() ) {
            // Avoid altering admin screens.
            return $normalized;
        }

        $overview     = wpr_translation_get_nav_menu_overview();
        $default_code = isset( $overview['default'] ) ? strtolower( sanitize_key( $overview['default'] ) ) : '';

        if ( '' === $default_code ) {
            // No default language means no fallback.
            return $normalized;
        }

        $language_code = wpr_translation_get_requested_nav_menu_language_code();

        if ( '' === $language_code || $language_code === $default_code ) {
            // Default language uses existing assignments.
            return $normalized;
        }

        foreach ( $normalized as $location => $assignments ) {
            if ( isset( $assignments[ $language_code ] ) ) {
                continue;
            }

            if ( isset( $assignments[ $default_code ] ) ) {
                // Mirror the default assignment for the current language.
                $normalized[ $location ][ $language_code ] = (int) $assignments[ $default_code ];
            }
        }

        return $normalized;
    }

    add_filter(
        'option_' . wpr_translation_get_nav_menu_locations_option_name(),
        'wpr_translation_filter_nav_menu_locations_option'
    );
}

if ( ! function_exists( 'wpr_translate_get_language_switcher_menu_markup' ) ) {
    /**
     * Build the language switcher markup for menu injection.
     *
     * @param string $location Menu location slug.
     *
     * @return string
     */
    function wpr_translate_get_language_switcher_menu_markup( $location ) {
        if ( ! function_exists( 'wpr_translate_language_switcher_widget_display' ) ) {
            return '';
        }

        // Build widget args for the menu-specific language switcher.
        $location_key = sanitize_key( $location );
        $widget_id    = 'wpr-menu-language-switcher-' . $location_key;
        $args         = array(
            'before_widget' => '',
            'after_widget'  => '',
            'before_title'  => '',
            'after_title'   => '',
            'widget_id'     => $widget_id,
            // Signal menu injection context so theme-specific markup can be applied.
            'wpr_translate_menu_injected' => true,
            'wpr_translate_menu_location' => $location_key,
        );

        // Capture the widget output so it can be embedded inside the nav menu markup.
        ob_start();
        wpr_translate_language_switcher_widget_display( $args, array( 'number' => 0 ) );
        return (string) ob_get_clean();
    }
}

if ( ! function_exists( 'wpr_translate_inject_language_switcher_into_menu' ) ) {
    /**
     * Inject the language switcher into configured menu locations.
     *
     * @param string $items Menu HTML.
     * @param object $args  Nav menu arguments.
     *
     * @return string
     */
    function wpr_translate_inject_language_switcher_into_menu( $items, $args ) {
        if ( is_admin() ) {
            // Do not inject into admin menu previews.
            return $items;
        }

        if ( ! isset( $args->theme_location ) ) {
            // Skip menus without theme location.
            return $items;
        }

        $location_key = sanitize_key( $args->theme_location );

        if ( '' === $location_key ) {
            // Invalid location key means no injection.
            return $items;
        }

        if ( function_exists( 'wpr_translate_debug_log' ) ) {
            $language_code = '';

            if ( function_exists( 'wpr_translate_get_current_language' ) ) {
                $current_language = wpr_translate_get_current_language();

                if ( is_array( $current_language ) && ! empty( $current_language['code'] ) ) {
                    $language_code = sanitize_key( $current_language['code'] );
                }
            }

            if ( '' === $language_code && function_exists( 'wpr_translation_get_requested_nav_menu_language_code' ) ) {
                $language_code = sanitize_key( wpr_translation_get_requested_nav_menu_language_code() );
            }

            wpr_translate_debug_log(
                'Front-end menu render.',
                array(
                    'location' => $location_key,
                    'language' => $language_code,
                )
            );
        }

        $settings = get_option( 'wpr_translate_settings', array() );
        $settings = is_array( $settings ) ? $settings : array();

        if ( empty( $settings['menu_language_switcher'] ) || ! is_array( $settings['menu_language_switcher'] ) ) {
            // No switcher settings configured.
            return $items;
        }

        $position = isset( $settings['menu_language_switcher'][ $location_key ] ) ? sanitize_key( $settings['menu_language_switcher'][ $location_key ] ) : '';

        if ( ! in_array( $position, array( 'before', 'after' ), true ) ) {
            // Only accept known positions.
            return $items;
        }

        $markup = wpr_translate_get_language_switcher_menu_markup( $location_key );

        if ( '' === trim( $markup ) ) {
            // Skip when the widget output is empty.
            return $items;
        }

        $menu_item_classes = array(
            'menu-item',
            'wpr-language-switcher-menu-item',
        );

        if ( function_exists( 'wpr_translate_is_wprentals_theme_active' ) && wpr_translate_is_wprentals_theme_active() ) {
            // Match WPRentals top-menu class conventions so dropdown styling/behavior works.
            $menu_item_classes[] = 'menu-item-type-custom';
            $menu_item_classes[] = 'menu-item-object-custom';
            $menu_item_classes[] = 'menu-item-has-children';
            $menu_item_classes[] = 'no-megamenu';
            $menu_item_classes[] = 'dropdown';
            $menu_item_classes[] = 'wpr-language-switcher-menu-item--wprentals';
        }

        $menu_item = '<li class="' . esc_attr( implode( ' ', array_unique( $menu_item_classes ) ) ) . '">' . $markup . '</li>';

        if ( 'before' === $position ) {
            // Prepend the switcher item.
            return $menu_item . $items;
        }

        // Append the switcher item.
        return $items . $menu_item;
    }

    add_filter( 'wp_nav_menu_items', 'wpr_translate_inject_language_switcher_into_menu', 10, 2 );
}
