<?php
/**
 * Frontend rendering logic for the language switcher widget.
 *
 * @package WPR_Translate
 */

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

if ( ! function_exists( 'wpr_translate_is_wprentals_theme_active' ) ) {
    /**
     * Detect whether WPRentals (or its child theme) is active.
     *
     * @return bool
     */
    function wpr_translate_is_wprentals_theme_active() {
        if ( ! function_exists( 'wp_get_theme' ) ) {
            return false;
        }

        $theme      = wp_get_theme();
        $candidates = array();

        if ( $theme ) {
            $candidates[] = strtolower( sanitize_key( (string) $theme->get_template() ) );
            $candidates[] = strtolower( sanitize_key( (string) $theme->get_stylesheet() ) );

            $parent = $theme->parent();

            if ( $parent ) {
                $candidates[] = strtolower( sanitize_key( (string) $parent->get_template() ) );
                $candidates[] = strtolower( sanitize_key( (string) $parent->get_stylesheet() ) );
            }
        }

        $candidates = array_filter( array_unique( $candidates ) );

        return in_array( 'wprentals', $candidates, true );
    }
}

/**
 * Render the Bootstrap language dropdown markup for the widget.
 *
 * @param string $wrapper_id   Wrapper identifier.
 * @param string $button_id    Button identifier.
 * @param string $button_label Visible text for the toggle button.
 * @param string $flag_url     URL for the current language flag.
 * @param string $current_code Selected language code.
 * @param int    $current_id   Current post identifier.
 * @param string $items_markup List items markup.
 * @param bool   $is_wprentals Whether WPRentals menu compatibility should be applied.
 */
function wpr_translate_render_language_switcher_dropdown( $wrapper_id, $button_id, $button_label, $flag_url, $current_code, $current_id, $items_markup, $is_wprentals = false ) {
    // Build the current language label and flag markup.
    $flag_alt       = sprintf( __( '%s flag', 'wpr-translate' ), $button_label );
    $flag_classname = '' !== $flag_url ? 'wpr-language-switcher-flag' : 'wpr-language-switcher-flag wpr-language-switcher-flag--hidden';
    $flag_markup  = '<span class="' . esc_attr( $flag_classname ) . '" aria-hidden="true">';
    $flag_markup .= '<img class="wpr-language-switcher-flag-img" width="18" height="14" loading="lazy" decoding="async" alt="' . esc_attr( $flag_alt ) . '"';

    if ( '' !== $flag_url ) {
        $flag_markup .= ' src="' . esc_url( $flag_url ) . '"';
    }

    $flag_markup .= ' />';
    $flag_markup .= '</span>';

    $wrapper_classes = array(
        'dropdown',
        'wpr-language-switcher',
    );

    $toggle_classes = array(
        'btn',
        'dropdown-toggle',
        'wpr-language-switcher-toggle',
    );

    $menu_classes = array(
        'dropdown-menu',
        'wpr-language-switcher-menu',
    );

    if ( $is_wprentals ) {
        // WPRentals header menu expects bootstrap-3 style hooks and sub-menu classes.
        $wrapper_classes[] = 'wpr-language-switcher--wprentals';
        $toggle_classes[]  = 'menu-item-link';
        $menu_classes[]    = 'sub-menu';
    }

    $toggle_attrs = ' data-bs-toggle="dropdown"';

    if ( $is_wprentals ) {
        $toggle_attrs .= ' data-toggle="dropdown" aria-haspopup="true"';
    }

    echo '<div id="' . esc_attr( $wrapper_id ) . '" class="' . esc_attr( implode( ' ', $wrapper_classes ) ) . '" data-current-post-id="' . esc_attr( $current_id ) . '" data-current-language-code="' . esc_attr( $current_code ) . '" data-flag-alt-template="' . esc_attr( __( '%s flag', 'wpr-translate' ) ) . '">';
    $screen_reader_text = esc_html__( 'Select language', 'wpr-translate' );

    echo '<button id="' . esc_attr( $button_id ) . '" class="' . esc_attr( implode( ' ', $toggle_classes ) ) . '" type="button"' . $toggle_attrs . ' aria-expanded="false" data-selected-language-code="' . esc_attr( $current_code ) . '">';
    echo '<span class="screen-reader-text">' . esc_html( $screen_reader_text ) . '</span>';
    echo '<div class="wpr-language-switcher-current">' . $flag_markup . '<div class="wpr-language-switcher-label">' . esc_html( $button_label ) . '</div></div>';
    echo '</button>';
    echo '<ul class="' . esc_attr( implode( ' ', $menu_classes ) ) . '" aria-labelledby="' . esc_attr( $button_id ) . '">';
    echo $items_markup; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- Safe, all attributes escaped during build.
    echo '</ul>';
    echo '</div>';
}

/**
 * Render the widget on the frontend.
 *
 * @param array $args        Display arguments.
 * @param array $widget_args Additional widget arguments.
 */
function wpr_translate_language_switcher_widget_display( $args, $widget_args ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedParameter
    // Resolve the widget instance settings.
    $number   = isset( $widget_args['number'] ) ? (int) $widget_args['number'] : 0;
    $options  = wpr_translate_language_switcher_get_options();
    $instance = isset( $options[ $number ] ) ? $options[ $number ] : array();


    $title = isset( $instance['title'] ) ? $instance['title'] : '';

    // Load active languages and bail if fewer than two exist.
    $languages = wpr_translate_get_active_languages();


    if ( ! is_array( $languages ) || count( $languages ) < 2 ) {
        return;
    }

    // Detect the current post or term context.
    $current_post_id = 0;
    $current_term    = null;
    $current_taxonomy = '';
    $is_term_context = false;

    if ( ! is_admin() && function_exists( 'is_singular' ) && is_singular() ) {
        $current_post_id = get_queried_object_id();
    }

    if ( ! $current_post_id && class_exists( 'WP_Post' ) ) {
        global $wp_query;

        if ( isset( $wp_query ) && is_object( $wp_query ) && isset( $wp_query->post ) && $wp_query->post instanceof WP_Post ) {
            $current_post_id = (int) $wp_query->post->ID;
        } elseif ( isset( $GLOBALS['post'] ) && $GLOBALS['post'] instanceof WP_Post ) {
            $current_post_id = (int) $GLOBALS['post']->ID;
        }
    }

    if ( ! is_admin() && function_exists( 'get_queried_object' ) ) {
        // Capture the current term when rendering taxonomy archives so the switcher can follow translations.
        $queried_object = get_queried_object();

        if ( $queried_object instanceof WP_Term ) {
            $current_term      = $queried_object;
            $current_taxonomy  = sanitize_key( $current_term->taxonomy );
            $is_term_context   = ( '' !== $current_taxonomy );

        }
    }

    $current_language = wpr_translate_get_context_language( $current_post_id );
    $current_code     = $current_language ? strtolower( $current_language['code'] ) : '';


    if ( $current_term && '' !== $current_taxonomy && function_exists( 'wpr_translate_get_element_language' ) ) {
        // Align the active language with the viewed term to show the correct selection state.
        $term_language = wpr_translate_get_element_language( $current_term->term_id, 'tax_' . $current_taxonomy );

        if ( is_array( $term_language ) ) {
            $current_language = $term_language;
            $current_code     = isset( $term_language['code'] ) ? strtolower( $term_language['code'] ) : $current_code;

        }
    }

    $translation_map   = array();
    $fallback_post_id  = 0;
    $fallback_term_id  = 0;
    $fallback_term_url = '';
    $front_page_id     = (int) get_option( 'page_on_front' );
    $front_page_map    = array();
    $is_front_page     = false;

    if ( $current_post_id && function_exists( 'wpr_translation_get_element_type' ) && function_exists( 'wpr_translation_get_translation_group' ) ) {
        $post_type = get_post_type( $current_post_id );

        if ( $post_type ) {
            $element_type      = wpr_translation_get_element_type( $post_type );
            $translation_group = wpr_translation_get_translation_group( $current_post_id, $element_type );

            if ( ! empty( $translation_group['translations'] ) ) {
                foreach ( $translation_group['translations'] as $mapped_code => $post_id ) {
                    $normalized_code = strtolower( $mapped_code );
                    $target_id       = absint( $post_id );

                    if ( '' === $normalized_code || ! $target_id ) {
                        continue;
                    }

                    $status = get_post_status( $target_id );

                    if ( false === $status ) {
                        continue;
                    }

                    $is_viewable = ( 'publish' === $status );

                    if ( ! $is_viewable && function_exists( 'is_post_status_viewable' ) ) {
                        $status_object = get_post_status_object( $status );
                        $is_viewable   = $status_object ? is_post_status_viewable( $status_object ) : false;
                    }

                    if ( ! $is_viewable ) {
                        continue;
                    }

                    $translation_map[ $normalized_code ] = $target_id;

                }

                if ( ! $fallback_post_id ) {
                    $source_code = isset( $translation_group['source_language'] ) ? strtolower( $translation_group['source_language'] ) : '';

                    if ( '' !== $source_code && isset( $translation_map[ $source_code ] ) ) {
                        $fallback_post_id = $translation_map[ $source_code ];

                    }

                    if ( ! $fallback_post_id ) {
                        foreach ( $translation_group['translations'] as $fallback_code => $fallback_id ) {
                            $fallback_post_id = absint( $fallback_id );

                            if ( $fallback_post_id ) {
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    if ( $front_page_id && function_exists( 'wpr_translation_get_element_type' ) && function_exists( 'wpr_translation_get_translation_group' ) ) {
        $front_page_type = get_post_type( $front_page_id );

        if ( $front_page_type ) {
            $front_page_element = wpr_translation_get_element_type( $front_page_type );
            $front_page_group   = wpr_translation_get_translation_group( $front_page_id, $front_page_element );

            if ( ! empty( $front_page_group['translations'] ) && is_array( $front_page_group['translations'] ) ) {
                foreach ( $front_page_group['translations'] as $mapped_code => $post_id ) {
                    $normalized_code = strtolower( $mapped_code );
                    $target_id       = absint( $post_id );

                    if ( '' === $normalized_code || ! $target_id ) {
                        continue;
                    }

                    $front_page_map[ $normalized_code ] = $target_id;
                }
            }
        }
    }

    if ( $front_page_id && $current_post_id ) {
        // Treat the front page and its translations as a special context.
        $is_front_page = ( (int) $current_post_id === (int) $front_page_id );

        if ( ! $is_front_page && ! empty( $front_page_map ) ) {
            $is_front_page = in_array( (int) $current_post_id, array_map( 'intval', $front_page_map ), true );
        }
    }

    if ( $current_term && '' !== $current_taxonomy && function_exists( 'wpr_translate_lookup_translated_term_id_strict' ) ) {
        // Build the taxonomy translation map using the shared meta-first lookup helpers.
        $canonical_term_id = absint( $current_term->term_id );

        if ( function_exists( 'wpr_translate_resolve_original_term_id' ) ) {
            $resolved_canonical = absint( wpr_translate_resolve_original_term_id( $canonical_term_id, $current_taxonomy ) );

            if ( $resolved_canonical > 0 ) {
                $canonical_term_id = $resolved_canonical;
            }
        }

        $default_term_language = '';

        if ( function_exists( 'wpr_translation_get_default_language_code' ) ) {
            $default_term_language = strtolower( sanitize_key( wpr_translation_get_default_language_code( $languages ) ) );
        }

        foreach ( $languages as $language_entry ) {
            $mapped_code = isset( $language_entry['code'] ) ? strtolower( sanitize_key( $language_entry['code'] ) ) : '';

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

            $target_id = 0;

            if ( '' !== $default_term_language && $mapped_code === $default_term_language ) {
                $target_id = $canonical_term_id;
            } else {
                $strict_target = wpr_translate_lookup_translated_term_id_strict( $canonical_term_id, $current_taxonomy, $mapped_code );

                if ( is_numeric( $strict_target ) ) {
                    $target_id = absint( $strict_target );
                }
            }

            if ( $target_id <= 0 ) {
                continue;
            }

            $term_object = get_term( $target_id, $current_taxonomy );

            if ( ! ( $term_object instanceof WP_Term ) ) {
                continue;
            }

            $translation_map[ $mapped_code ] = $target_id;
        }

        if ( ! $fallback_term_id ) {
            if ( '' !== $default_term_language && isset( $translation_map[ $default_term_language ] ) ) {
                $fallback_term_id = $translation_map[ $default_term_language ];
            } elseif ( $canonical_term_id > 0 ) {
                $fallback_term_id = $canonical_term_id;
            }
        }
    }

    if ( $fallback_term_id && $is_term_context ) {
        // Preserve a fallback term URL in case the target language lacks a direct translation.
        $maybe_fallback_link = get_term_link( (int) $fallback_term_id, $current_taxonomy );

        if ( ! is_wp_error( $maybe_fallback_link ) ) {
            $fallback_term_url = $maybe_fallback_link;

        }
    }

    if ( ! $fallback_post_id ) {
        $fallback_post_id = $current_post_id;

    }

    $default_language      = wpr_translate_get_default_language();
    $default_language_code = $default_language && ! empty( $default_language['code'] ) ? $default_language['code'] : '';

    if ( $default_language_code ) {
        $normalized_default_code = strtolower( $default_language_code );

        if ( isset( $translation_map[ $normalized_default_code ] ) ) {
            $fallback_post_id = $translation_map[ $normalized_default_code ];

        }
    }

    $fallback_post_url = '';

    if ( $fallback_post_id ) {
        if ( function_exists( 'wpr_translation_get_post_language_permalink' ) && $default_language_code ) {
            $fallback_post_url = wpr_translation_get_post_language_permalink( $fallback_post_id, $default_language_code );
        }

        if ( '' === $fallback_post_url && function_exists( 'get_permalink' ) ) {
            $fallback_post_url = get_permalink( $fallback_post_id );

        }
    }

    $widget_id   = isset( $args['widget_id'] ) ? $args['widget_id'] : uniqid( 'wpr-language-switcher', true );
    $wrapper_id  = 'wpr-language-switcher-' . sanitize_html_class( $widget_id );
    $button_id   = $wrapper_id . '-toggle';
    $payload     = array(
        'currentPostId'       => $current_post_id,
        'currentLanguageCode' => $current_code,
        'ajaxUrl'             => admin_url( 'admin-ajax.php' ),
        'cookieNonce'         => wp_create_nonce( 'wpr_translate_language_cookie' ),
        'languages'           => array(),
    );
    $dropdown_items              = array();
    $current_button_label        = esc_html__( 'Choose language', 'wpr-translate' );
    $current_button_flag         = '';
    $current_language_code       = $current_code;
    $is_menu_injected_switcher   = ! empty( $args['wpr_translate_menu_injected'] );
    $use_wprentals_menu_dropdown = $is_menu_injected_switcher && wpr_translate_is_wprentals_theme_active();

    // Build each dropdown option with its navigation data and flag.
    foreach ( $languages as $language ) {
        $code           = strtolower( $language['code'] );
        $selected       = selected( $current_code, $code, false );
        $language_label = isset( $language['name'] ) ? sanitize_text_field( $language['name'] ) : '';
        $router         = function_exists( 'wpr_translate_language_router_get_switch_url' ) ? wpr_translate_language_router_get_switch_url( $language ) : '';
        $target         = isset( $translation_map[ $code ] ) ? $translation_map[ $code ] : 0;
        $url            = '';
        $flag_code = '';
        $flag_url  = '';

        // Strip country/region details from labels like "English ( United States )".
        if ( '' !== $language_label ) {
            $language_label = trim( preg_replace( '/\s*\([^)]*\)\s*$/', '', $language_label ) );
        }

        if ( '' === $language_label && ! empty( $language['code'] ) ) {
            $language_label = strtoupper( sanitize_key( $language['code'] ) );
        }

        if ( $target ) {
            if ( $is_term_context ) {
                $term_link = get_term_link( (int) $target, $current_taxonomy );

                if ( ! is_wp_error( $term_link ) ) {
                    $url = $term_link;

                }
            } elseif ( function_exists( 'wpr_translation_get_post_language_permalink' ) ) {
                $url = wpr_translation_get_post_language_permalink( $target, $language['code'] );

            }
        }

        if ( $is_front_page && $target && ! empty( $front_page_map ) && isset( $front_page_map[ $code ] ) && (int) $front_page_map[ $code ] === (int) $target && '' !== $router ) {
            // Use the language root URL for translated front pages instead of the page permalink.
            $url = $router;
        }

        if ( '' === $url && ! $target ) {
            if ( $current_post_id && ! $is_term_context && '' !== $fallback_post_url ) {
                // For singular posts without translations, fall back to the default-language URL.
                $url = $fallback_post_url;

            } elseif ( $is_term_context && '' !== $fallback_term_url ) {
                // For term archives without translations, fall back to the default-language term URL.
                $url = $fallback_term_url;

            } elseif ( '' !== $router ) {
                // Use the router URL for non-singular contexts (archives, search, etc.).
                $url = $router;

            }
        }

        $can_set_cookie = true;

        if ( ! $target ) {
            if ( $current_post_id && ! $is_term_context && '' !== $fallback_post_url && $url === $fallback_post_url ) {
                // Do not set the cookie when falling back to the default-language post URL.
                $can_set_cookie = false;
            } elseif ( $is_term_context && '' !== $fallback_term_url && $url === $fallback_term_url ) {
                // Do not set the cookie when falling back to the default-language term URL.
                $can_set_cookie = false;
            }
        }

        if ( ! empty( $language['flag'] ) ) {
            $flag_code = sanitize_key( $language['flag'] );
        }

        if ( '' === $flag_code && ! empty( $language['code'] ) ) {
            $flag_code = sanitize_key( $language['code'] );
        }

        if ( '' !== $flag_code && defined( 'WPR_TRANSLATE_URL' ) ) {
            $flag_url = WPR_TRANSLATE_URL . 'assets/img/flags/4x3/' . $flag_code . '.svg';
        }

        $payload['languages'][ $code ] = array(
            'languageCode'      => $language['code'],
            'name'              => $language_label,
            'translationPostId' => $target,
            'targetUrl'         => $url,
            'routerUrl'         => $router,
            'fallbackUrl'       => $fallback_post_url,
        );

        if ( '' !== $flag_url ) {
            $payload['languages'][ $code ]['flagUrl'] = $flag_url;
        }

        if ( '' !== $selected ) {
            $current_button_label  = $language_label;
            $current_button_flag   = $flag_url;
            $current_language_code = $language['code'];
        }

        $flag_classname = '' !== $flag_url ? 'wpr-language-switcher-flag' : 'wpr-language-switcher-flag wpr-language-switcher-flag--hidden';
        $flag_alt       = sprintf( __( '%s flag', 'wpr-translate' ), $language_label );
        $item_label     = '<div class="wpr-language-switcher-item-content">';
        $item_label    .= '<span class="' . esc_attr( $flag_classname ) . '" aria-hidden="true">';
        $item_label    .= '<img class="wpr-language-switcher-flag-img" width="18" height="14" loading="lazy" decoding="async" alt="' . esc_attr( $flag_alt ) . '"';

        if ( '' !== $flag_url ) {
            $item_label .= ' src="' . esc_url( $flag_url ) . '"';
        }

        $item_label .= ' />';
        $item_label .= '</span>';
        $item_label .= '<div class="wpr-language-switcher-item-label">' . esc_html( $language_label ) . '</div>';
        $item_label .= '</div>';

        $item_row_classes = array();
        $item_classes     = array(
            'dropdown-item',
            'wpr-language-switcher-item',
        );

        if ( $use_wprentals_menu_dropdown ) {
            $item_row_classes[] = 'menu-item';
            $item_row_classes[] = 'menu-item-type-custom';
            $item_row_classes[] = 'menu-item-object-custom';
            $item_classes[]     = 'menu-item-link';
        }

        $dropdown_items[] = '<li role="presentation"' . ( ! empty( $item_row_classes ) ? ' class="' . esc_attr( implode( ' ', $item_row_classes ) ) . '"' : '' ) . '><button type="button" class="' . esc_attr( implode( ' ', $item_classes ) ) . '" data-language-code="' . esc_attr( $language['code'] ) . '" data-translation-id="' . absint( $target ) . '" data-target-url="' . esc_url( $url ) . '" data-router-url="' . esc_url( $router ) . '" data-fallback-url="' . esc_url( $fallback_post_url ) . '" data-can-set-cookie="' . esc_attr( $can_set_cookie ? '1' : '0' ) . '" data-flag-url="' . esc_url( $flag_url ) . '" data-label="' . esc_attr( $language_label ) . '">' . $item_label . '</button></li>';
    }

    $payload_json = wp_json_encode( $payload );

    echo isset( $args['before_widget'] ) ? $args['before_widget'] : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

    if ( '' !== $title ) {
        if ( isset( $args['before_title'] ) ) {
            echo $args['before_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }

        echo esc_html( $title );

        if ( isset( $args['after_title'] ) ) {
            echo $args['after_title']; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }
    }

    // Output the Bootstrap-styled language dropdown.
    wpr_translate_render_language_switcher_dropdown(
        $wrapper_id,
        $button_id,
        $current_button_label,
        $current_button_flag,
        $current_language_code,
        $current_post_id,
        implode( '', $dropdown_items ),
        $use_wprentals_menu_dropdown
    );

    $script = sprintf(
        'document.addEventListener("DOMContentLoaded",function(){var container=document.getElementById("%1$s");if(!container){return;}var payload=%2$s||{};var toggle=container.querySelector(".wpr-language-switcher-toggle");var label=container.querySelector(".wpr-language-switcher-label");var flagWrapper=container.querySelector(".wpr-language-switcher-flag");var flagImage=flagWrapper?flagWrapper.querySelector("img"):null;var altTemplate=container.getAttribute("data-flag-alt-template")||"%3$s";var ajaxUrl=payload.ajaxUrl||"";var cookieNonce=payload.cookieNonce||"";var storeCookie=function(nextCode){if(!ajaxUrl||!cookieNonce||!nextCode){return;}var data=new FormData();data.append("action","wpr_translate_set_language_cookie");data.append("language",nextCode);data.append("nonce",cookieNonce);data.append("current_post_id",String(payload.currentPostId||0));if(navigator.sendBeacon){try{navigator.sendBeacon(ajaxUrl,data);return;}catch(err){}}if(window.fetch){fetch(ajaxUrl,{method:"POST",credentials:"same-origin",body:data,keepalive:true}).catch(function(){});return;}var xhr=new XMLHttpRequest();xhr.open("POST",ajaxUrl,true);xhr.withCredentials=true;xhr.send(data);};if(toggle){toggle.setAttribute("data-current-post-id",String(payload.currentPostId||0));toggle.setAttribute("data-selected-language-code",payload.currentLanguageCode||"");}var updateButton=function(item){if(!item){return;}var nextLabel=item.getAttribute("data-label")||"";var nextFlag=item.getAttribute("data-flag-url")||"";var nextCode=item.getAttribute("data-language-code")||"";if(label){label.textContent=nextLabel;}if(flagWrapper){flagWrapper.classList.toggle("wpr-language-switcher-flag--hidden",!nextFlag);}if(flagImage){if(nextFlag){flagImage.setAttribute("src",nextFlag);}else{flagImage.removeAttribute("src");}var altValue=altTemplate.replace("%s",nextLabel||nextCode||"");flagImage.setAttribute("alt",altValue);}if(toggle){toggle.setAttribute("data-selected-language-code",nextCode);}};var items=container.querySelectorAll(".wpr-language-switcher-item");items.forEach(function(item){item.addEventListener("click",function(){updateButton(item);var nextCode=item.getAttribute("data-language-code")||"";var canSetCookie=item.getAttribute("data-can-set-cookie");if(canSetCookie==="1"){storeCookie(nextCode);}var targetUrl=item.getAttribute("data-target-url")||"";var routerUrl=item.getAttribute("data-router-url")||"";var fallbackUrl=item.getAttribute("data-fallback-url")||"";var nextUrl=targetUrl||routerUrl||fallbackUrl;if(nextUrl){window.location.href=nextUrl;}});});var initialCode=payload.currentLanguageCode||"";if(initialCode){items.forEach(function(item){if(item.getAttribute("data-language-code")===initialCode){updateButton(item);}});} });',
        esc_js( $wrapper_id ),
        $payload_json ? $payload_json : '{}',
        esc_js( __( '%s flag', 'wpr-translate' ) )
    );

    echo '<script type="text/javascript">' . $script . '</script>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped

    if ( $use_wprentals_menu_dropdown ) {
        // Ensure click-to-open works with WPRentals header navigation behavior.
        $menu_script = sprintf(
            'document.addEventListener("DOMContentLoaded",function(){var container=document.getElementById("%1$s");if(!container){return;}var toggle=container.querySelector(".wpr-language-switcher-toggle");var menuItem=container.closest(".wpr-language-switcher-menu-item--wprentals");if(!toggle||!menuItem){return;}var closeMenu=function(){menuItem.classList.remove("is-open");toggle.setAttribute("aria-expanded","false");};toggle.addEventListener("click",function(event){event.preventDefault();event.stopPropagation();if(menuItem.classList.contains("is-open")){closeMenu();return;}menuItem.classList.add("is-open");toggle.setAttribute("aria-expanded","true");});document.addEventListener("click",function(event){if(!menuItem.contains(event.target)){closeMenu();}});document.addEventListener("keyup",function(event){if(event.key==="Escape"){closeMenu();}});});',
            esc_js( $wrapper_id )
        );

        echo '<script type="text/javascript">' . $menu_script . '</script>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
    }

    echo isset( $args['after_widget'] ) ? $args['after_widget'] : ''; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
