<?php
use MintyPHP\I18n;
use MintyPHP\Http\Request;

$locales = defined('APP_LOCALES') ? APP_LOCALES : [I18n::$defaultLocale];
$returnTarget = Request::pathWithQuery();
$variant = $variant ?? 'select';
$baseUrl = lurl('lang');
$isLoggedIn = !empty($_SESSION['user']['id']);
$publicTarget = Request::stripLocale($returnTarget);
$publicTarget = ltrim($publicTarget, '/');
$base = \MintyPHP\Router::getBaseUrl();
$base = rtrim($base, '/');
$publicTarget = ltrim($publicTarget, '/');
?>

<?php if ($variant === 'dropdown'): ?>
    <details class="dropdown">
        <summary>
            <i class="bi bi-translate"></i>
        </summary>
        <ul dir="rtl">
            <?php foreach ($locales as $locale): ?>
                <?php
                $isActive = $locale === I18n::$locale;
                $label = strtoupper((string) $locale);
                $publicUrl = $base . '/' . $locale . ($publicTarget !== '' ? '/' . $publicTarget : '');
                $switchUrl = $isLoggedIn
                    ? ($baseUrl . '?locale=' . $locale . '&return=' . urlencode($returnTarget))
                    : $publicUrl;
                ?>
                <li dir="ltr">
                    <a href="<?php e($switchUrl); ?>"
                       <?php if ($isActive) { ?>aria-current="true"<?php } ?>>
                        <?php e($label); ?>
                    </a>
                </li>
            <?php endforeach; ?>
        </ul>
    </details>
<?php else: ?>
    <?php if ($isLoggedIn): ?>
        <form class="nav nav--lang" method="get" action="<?php e($baseUrl); ?>" aria-label="Language switcher">
            <input type="hidden" name="return" value="<?php e($returnTarget); ?>">
            <select class="lang-select" name="locale" onchange="this.form.submit()">
                <?php foreach ($locales as $locale): ?>
                    <option value="<?php e($locale); ?>" <?php if ($locale === I18n::$locale) { ?>selected<?php } ?>>
                        <?php e(strtoupper((string) $locale)); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </form>
    <?php else: ?>
        <div class="nav nav--lang" role="listbox" aria-label="Language switcher">
            <?php foreach ($locales as $locale): ?>
                <?php
                $publicUrl = $base . '/' . $locale . ($publicTarget !== '' ? '/' . $publicTarget : '');
                ?>
                <a href="<?php e($publicUrl); ?>" class="lang-link"
                   <?php if ($locale === I18n::$locale) { ?>aria-current="true"<?php } ?>>
                    <?php e(strtoupper((string) $locale)); ?>
                </a>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>
<?php endif; ?>
