<?php

/**
 * Переключает язык (регионы) необходим плагин Polylang
 *
 */


// Проверяем существование функций Polylang
if (!function_exists('pll_languages_list') || !function_exists('pll_current_language')) {
    return;
}
?>

<style>
    .pl-lang-switcher-container {
        position: relative;
        display: inline-flex;
        border: 1px solid #e0e0e0;
        border-radius: 90px;
        padding: 6px;
        --pl-slider-width: 0px;
        --pl-slider-x: 0px;
        gap: 4px;
    }

    .pl-lang-switcher-button,
    .pl-lang-switcher-container a {
        position: relative;
        z-index: 2;
        border: none;
        background: transparent;
        color: #636363;
        font-weight: 600;
        font-size: 15px;
        line-height: 110%;
        text-align: center;
        border-radius: 90px;
        cursor: pointer;
        transition: all 180ms ease;
        white-space: nowrap;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        height: 29px;
        padding-left: 12px;
        padding-right: 12px;
    }

    .pl-lang-switcher-button:hover,
    .pl-lang-switcher-container a:hover {
        color: #222;
    }

    .pl-lang-switcher-button.pl-lang-switcher-active,
    .pl-lang-switcher-container a.pl-lang-switcher-active,
    .pl-lang-switcher-container a.pl-lang-switcher-current {
        color: #f8f8f8;
    }

    .pl-lang-switcher-slider {
        position: absolute;
        height: 29px;
        background: linear-gradient(90deg, #2b2c35 67.31%, #4f5870 92.9%);
        border-radius: 90px;
        z-index: 1;
        width: var(--pl-slider-width);
        transform: translateX(var(--pl-slider-x));
        transition: all 180ms cubic-bezier(0.4, 0.0, 0.2, 1);
    }
</style>

<div class="pl-lang-switcher-container" id="plLangSwitcherContainer">
    <div class="pl-lang-switcher-slider" id="plLangSwitcherSlider"></div>
    <?php
    $languages = pll_languages_list();
    $current_lang = pll_current_language('slug');

    if ($languages) {
        foreach ($languages as $lang_slug) {
            $is_current = ($lang_slug === $current_lang);
            $class = $is_current ? 'pl-lang-switcher-current' : '';

            $lang_url = '';
            if (function_exists('pll_home_url')) {
                if (is_singular() && function_exists('pll_get_post')) {
                    $translated_post_id = pll_get_post(get_the_ID(), $lang_slug);
                    if ($translated_post_id) {
                        $lang_url = get_permalink($translated_post_id);
                    } else {
                        $lang_url = pll_home_url($lang_slug);
                    }
                } else {
                    $lang_url = pll_home_url($lang_slug);
                }
            }

            $lang_name = '';
            if (function_exists('pll_languages_list')) {
                $lang_names = pll_languages_list(array('fields' => 'name'));
                $lang_slugs = pll_languages_list(array('fields' => 'slug'));
                $lang_index = array_search($lang_slug, $lang_slugs);
                if ($lang_index !== false && isset($lang_names[$lang_index])) {
                    $lang_name = $lang_names[$lang_index];
                } else {
                    $lang_name = strtoupper($lang_slug);
                }
            } else {
                $lang_name = strtoupper($lang_slug);
            }

            echo sprintf(
                '<a href="%s" class="%s" data-lang="%s">%s</a>',
                esc_url($lang_url),
                esc_attr($class),
                esc_attr($lang_slug),
                esc_html($lang_name)
            );
        }
    }
    ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const container = document.getElementById('plLangSwitcherContainer');
        if (!container) return;

        let isInitialized = false;

        function updateSliderPosition(target = null, animate = false) {
            if (!target) {
                target = container.querySelector('.pl-lang-switcher-current');
            }
            if (!target) return;

            const slider = container.querySelector('#plLangSwitcherSlider');
            const width = target.offsetWidth;
            const x = target.offsetLeft - 6;

            if (animate) {
                slider.style.transition = 'all 180ms cubic-bezier(0.4, 0.0, 0.2, 1)';
            } else {
                slider.style.transition = 'none';
            }

            container.style.setProperty('--pl-slider-width', width + 'px');
            container.style.setProperty('--pl-slider-x', x + 'px');
        }

        function initialize() {
            if (isInitialized) return;

            const activeLink = container.querySelector('.pl-lang-switcher-current');
            if (!activeLink || activeLink.offsetWidth === 0) {
                requestAnimationFrame(initialize);
                return;
            }

            updateSliderPosition(activeLink, false);
            isInitialized = true;

            setupClickHandlers();

            if (window.ResizeObserver) {
                const resizeObserver = new ResizeObserver(() => {
                    if (isInitialized) {
                        updateSliderPosition(null, false);
                    }
                });
                resizeObserver.observe(container);
            } else {
                window.addEventListener('resize', () => {
                    if (isInitialized) {
                        updateSliderPosition(null, false);
                    }
                });
            }
        }

        function setupClickHandlers() {
            container.addEventListener('click', function(e) {
                const link = e.target.closest('a');
                if (!link) return;

                e.preventDefault();

                container.querySelectorAll('a').forEach(a => a.classList.remove('pl-lang-switcher-current'));

                link.classList.add('pl-lang-switcher-current');

                updateSliderPosition(link, true);

                setTimeout(() => location.href = link.href, 20);
            });
        }

        initialize();
    });
</script>