<?php
/**
 * Site-wide language switcher (Google Translate powered).
 *
 * Usage:
 *   $lang_prefix = '../';  // '' from root, '../' from app/ or auth/
 *   $lang_switcher_variant = 'dashboard'; // dashboard | landing | auth
 *
 *   In <head>:  include with $lang_switcher_part = 'head';
 *   In header:  include with $lang_switcher_part = 'widget';
 */
if (!isset($lang_prefix)) {
    $lang_prefix = '../';
}

$lang_switcher_part = $lang_switcher_part ?? 'both';
$lang_switcher_variant = $lang_switcher_variant ?? 'dashboard';
$is_dark_variant = in_array($lang_switcher_variant, ['dashboard', 'landing', 'auth'], true);
$trigger_class = $is_dark_variant ? 'lang-switcher-trigger lang-switcher-trigger--dark' : 'lang-switcher-trigger';
$menu_class = $is_dark_variant ? 'lang-switcher-menu lang-switcher-menu--dark' : 'lang-switcher-menu';
$wrapper_class = 'lang-switcher' . ($lang_switcher_variant === 'auth' ? ' lang-switcher--auth' : '');

if (($lang_switcher_part === 'head' || $lang_switcher_part === 'both') && !defined('LANG_SWITCHER_HEAD_LOADED')) {
    define('LANG_SWITCHER_HEAD_LOADED', true);
    echo '<link rel="stylesheet" href="' . htmlspecialchars($lang_prefix, ENT_QUOTES, 'UTF-8') . 'assets/css/language-switcher.css">' . "\n";
    echo '<script src="' . htmlspecialchars($lang_prefix, ENT_QUOTES, 'UTF-8') . 'assets/js/language-switcher.js"></script>' . "\n";
    echo '<script src="https://translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>' . "\n";
}

if ($lang_switcher_part === 'widget' || $lang_switcher_part === 'both') {
    if (!defined('LANG_SWITCHER_WIDGET_LOADED')) {
        define('LANG_SWITCHER_WIDGET_LOADED', true);
        ?>
        <div class="<?php echo $wrapper_class; ?>" id="lang-switcher">
            <button
                type="button"
                id="lang-switcher-btn"
                class="<?php echo $trigger_class; ?>"
                aria-haspopup="listbox"
                aria-expanded="false"
                aria-label="Change language"
            >
                <span class="lang-switcher-flag" id="lang-switcher-flag">🇺🇸</span>
                <span class="lang-switcher-label" id="lang-switcher-label">English</span>
                <span class="lang-switcher-code" id="lang-switcher-code">EN</span>
                <i class="fa-solid fa-chevron-down text-[10px] opacity-60"></i>
            </button>
            <div id="lang-switcher-menu" class="<?php echo $menu_class; ?>" role="listbox" aria-label="Languages"></div>
        </div>
        <div id="google_translate_element" aria-hidden="true"></div>
        <?php
    }
}
