<?php

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


if (!function_exists('pll_languages_list') || !function_exists('pll_current_language')) {
    return;
}


static $instance_counter = 0;
$instance_counter++;
$unique_id = 'plLangSwitcher' . $instance_counter;
?>

<style>
    .pl-lang-switcher-container {
        position: relative;
        display: inline-flex;
        border: 1px solid #e0e0e0;
        border-radius: 90px;
        padding: 6px;
        gap: 4px;
    }
    @media (max-width: 767px) {
        .pl-lang-switcher-container {
            width: 100%;
        }
    }

    .dark .pl-lang-switcher-container {
        border: 1px solid rgba(248, 248, 248, 0.05);
        backdrop-filter: blur(20px);
        background: linear-gradient(90deg, rgba(248, 248, 248, 0.04) 65.8%, rgba(255, 255, 255, 0.12) 100%);
        background-position: -1px 0;
        background-size: 101%;
    }

    .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: 40%;
        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;
    }

    @media (max-width: 767px) {
        .pl-lang-switcher-button,
        .pl-lang-switcher-container a{
            flex-grow: 1;
        }
    }


    .dark .pl-lang-switcher-button,
    .dark .pl-lang-switcher-container a {
        color: #b9b7b9;
    }


    .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;
    }

    .dark a.pl-lang-switcher-current {
        color: #303030;
    }

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

    .dark .pl-lang-switcher-slider {
        background: #faf8f5;
    }
</style>

<div class="pl-lang-switcher-container" data-switcher-id="<?php echo $unique_id; ?>">
    <div class="pl-lang-switcher-slider"></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 (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);
                }
            }

            elseif (is_post_type_archive()) {
                $post_type = get_post_type();
                if ($post_type && function_exists('pll_get_post_type_archive_link')) {
                    $lang_url = pll_get_post_type_archive_link($post_type, $lang_slug);
                }


                if (empty($lang_url)) {
                    $archive_link = get_post_type_archive_link($post_type);
                    if ($archive_link) {

                        $lang_url = str_replace(home_url(), pll_home_url($lang_slug), $archive_link);
                    } else {
                        $lang_url = pll_home_url($lang_slug);
                    }
                }
            }

            elseif (is_tax() || is_category() || is_tag()) {
                $queried_object = get_queried_object();
                if ($queried_object && function_exists('pll_get_term')) {
                    $translated_term = pll_get_term($queried_object->term_id, $lang_slug);
                    if ($translated_term) {
                        $lang_url = get_term_link($translated_term);
                    } else {
                        $lang_url = pll_home_url($lang_slug);
                    }
                } else {
                    $lang_url = pll_home_url($lang_slug);
                }
            }

            elseif (is_archive()) {

                if (is_author()) {
                    $author = get_queried_object();
                    if ($author) {
                        $author_posts_url = get_author_posts_url($author->ID);
                        $lang_url = str_replace(home_url(), pll_home_url($lang_slug), $author_posts_url);
                    } else {
                        $lang_url = pll_home_url($lang_slug);
                    }
                }

                elseif (is_date()) {
                    $current_url = home_url(add_query_arg(array(), $wp->request));
                    $lang_url = str_replace(home_url(), pll_home_url($lang_slug), $current_url);
                }

                else {
                    $lang_url = pll_home_url($lang_slug);
                }
            }

            else {
                if (function_exists('pll_home_url')) {
                    $lang_url = pll_home_url($lang_slug);
                }
            }


            if (empty($lang_url)) {
                $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);
            }

            // Замена названий языков на кастомные
            $custom_lang_names = array(
                'Fakel Fitness' => 'Фитнес-центр',
                'Fakel Gym' => 'Зал силовых'
            );

            if (isset($custom_lang_names[$lang_name])) {
                $display_name = $custom_lang_names[$lang_name];
            } else {
                $display_name = $lang_name;
            }

            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($display_name)
            );
        }
    }
    ?>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const containers = document.querySelectorAll('.pl-lang-switcher-container[data-switcher-id="<?php echo $unique_id; ?>"]');

        containers.forEach(function(container) {
            initLanguageSwitcher(container);
        });
    });

    function initLanguageSwitcher(container) {
        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('.pl-lang-switcher-slider');
            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';
            }

            slider.style.width = width + 'px';
            slider.style.transform = 'translateX(' + 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>