/**
 * hero-slider.js — PRODUCTION READY
 *
 * Исправлено:
 * — Двойная инициализация (guard через data-атрибут)
 * — Автоплей останавливался после hover и visibilitychange
 * — z-index конфликты с Bitrix header/dropdown
 * — overflow:hidden на .ovh родителях
 * — Стрелки не кликались из-за pointer-events
 * — Fade effect ломал background-image
 */
 
(function () {
    'use strict';
 
    /* ---- Конфигурация ---- */
    var CONFIG = {
        selector:      '.hero-swiper',
        autoplayDelay: 2000,       // мс между слайдами
        speed:         800,        // мс анимации перехода
        loop:          true,
        effect:        'fade'
    };
 
    /* ---- Один экземпляр — guard ---- */
    var _instance = null;
    var _initialized = false;
 
    /* ------------------------------------------------------------------ */
    /*  ИНИЦИАЛИЗАЦИЯ                                                       */
    /* ------------------------------------------------------------------ */
    function initHeroSlider() {
 
        var el = document.querySelector(CONFIG.selector);
 
        if (!el) return;                             // слайдер не на странице
 
        /* Предотвращаем двойную инициализацию */
        if (el.getAttribute('data-hero-init') === '1') return;
        el.setAttribute('data-hero-init', '1');
 
        /* Уничтожаем предыдущий экземпляр, если он почему-то есть */
        if (el.swiper) {
            el.swiper.destroy(true, true);
        }
 
        /* Проверяем наличие Swiper */
        if (typeof Swiper === 'undefined') {
            console.error('[HeroSlider] Swiper not loaded');
            el.removeAttribute('data-hero-init');
            return;
        }
 
        /* Применяем фиксы до инициализации */
        fixOverflow();
        fixZIndex();
 
        /* ---- Создаём экземпляр ---- */
        _instance = new Swiper(CONFIG.selector, {
 
            effect:      CONFIG.effect,
            fadeEffect:  { crossFade: true },
            speed:       CONFIG.speed,
            loop:        CONFIG.loop,
 
            /* Автоплей */
            autoplay: {
                delay:                CONFIG.autoplayDelay,
                disableOnInteraction: false,   // продолжает после клика
                pauseOnMouseEnter:    true,    // пауза при наведении
                stopOnLastSlide:      false,
                waitForTransition:    true
            },
 
            /* Стрелки */
            navigation: {
                nextEl:        '.swiper-button-next',
                prevEl:        '.swiper-button-prev',
                disabledClass: 'swiper-button-disabled'
            },
 
            /* Пагинация */
            pagination: {
                el:        '.swiper-pagination',
                clickable: true
            },
 
            /* Клавиатура */
            keyboard: {
                enabled:       true,
                onlyInViewport: true
            },
 
            /* Тач/свайп */
            touchRatio:    1,
            simulateTouch: true,
            grabCursor:    true,
            allowTouchMove: true,
 
            /* Производительность */
            preloadImages:       true,
            watchSlidesProgress: false,
            updateOnWindowResize: true,
            resizeObserver:      true,
 
            /* Хуки */
            on: {
 
                init: function () {
                    _initialized = true;
                    ensureClickable();
                    /* Принудительно стартуем autoplay — некоторые версии Swiper
                       не стартуют автоматически при loop:true + fade */
                    safeAutoplayStart(this);
                },
 
                /* Восстанавливаем autoplay если он упал */
                autoplayStop: function () {
                    var sw = this;
                    setTimeout(function () {
                        safeAutoplayStart(sw);
                    }, 100);
                },
 
                slideChangeTransitionEnd: function () {
                    ensureClickable();
                },
 
                resize: function () {
                    this.update();
                }
            }
        });
 
        /* Восстановление при возврате на вкладку */
        document.addEventListener('visibilitychange', function () {
            if (!document.hidden) {
                safeAutoplayStart(_instance);
            }
        });
 
        /* Сохраняем глобально для дебага */
        window.heroSlider = _instance;
    }
 
    /* ------------------------------------------------------------------ */
    /*  ХЕЛПЕРЫ                                                             */
    /* ------------------------------------------------------------------ */
 
    /** Безопасный старт autoplay */
    function safeAutoplayStart(sw) {
        if (sw && sw.autoplay && !sw.destroyed && !sw.autoplay.running) {
            try { sw.autoplay.start(); } catch(e) {}
        }
    }
 
    /**
     * Убираем overflow:hidden на всех родителях .hero-slider.
     * Bitrix оборачивает контент в .ovh (overflow:hidden) — это скрывает
     * background-image на слайдах при position:absolute.
     */
    function fixOverflow() {
        var hero = document.querySelector('.hero-slider');
        if (!hero) return;
 
        var node = hero.parentElement;
        while (node && node !== document.body) {
            var cs = window.getComputedStyle(node);
            if (cs.overflow === 'hidden' || cs.overflowX === 'hidden' || cs.overflowY === 'hidden') {
                node.style.setProperty('overflow', 'visible', 'important');
            }
            node = node.parentElement;
        }
    }
 
    /**
     * Корректируем z-index:
     *   header → 1000
     *   dropdown → 1001
     *   hero-slider → 1
     */
    function fixZIndex() {
        /* Header */
        var header = document.querySelector('header, .main-header, .site-header');
        if (header) {
            header.style.setProperty('position', 'relative', 'important');
            header.style.setProperty('z-index',  '1000',     'important');
        }
 
        /* Dropdown меню */
        document.querySelectorAll(
            '.drop_menu-section, .drop_menu-section3, .submenu, .dropdown-menu'
        ).forEach(function (el) {
            el.style.setProperty('position', 'relative', 'important');
            el.style.setProperty('z-index',  '1001',     'important');
        });
 
        /* Слайдер */
        var slider = document.querySelector('.hero-slider');
        if (slider) {
            slider.style.setProperty('z-index', '1', 'important');
        }
    }
 
    /**
     * Гарантируем кликабельность кнопок, стрелок, пагинации.
     * Вызываем после каждого смены слайда на случай если
     * Bitrix перезаписывает стили.
     */
    function ensureClickable() {
        /* Hero кнопки */
        document.querySelectorAll('.hero-btn').forEach(function (btn) {
            btn.style.setProperty('pointer-events', 'auto', 'important');
            btn.style.setProperty('cursor',         'pointer', 'important');
            btn.style.setProperty('position',       'relative', 'important');
            btn.style.setProperty('z-index',        '100',     'important');
        });
 
        /* Стрелки */
        document.querySelectorAll('.swiper-button-next, .swiper-button-prev').forEach(function (btn) {
            btn.style.setProperty('pointer-events', 'auto', 'important');
            btn.style.setProperty('z-index',        '50',   'important');
        });
 
        /* Пагинация */
        var pag = document.querySelector('.hero-swiper .swiper-pagination');
        if (pag) {
            pag.style.setProperty('pointer-events', 'auto', 'important');
            pag.style.setProperty('z-index',        '50',   'important');
        }
 
        /* Контент */
        document.querySelectorAll('.hero-left').forEach(function (el) {
            el.style.setProperty('pointer-events', 'auto', 'important');
        });
    }
 
    /* ------------------------------------------------------------------ */
    /*  ЗАПУСК                                                              */
    /* ------------------------------------------------------------------ */
 
    /* Ждём DOM */
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', initHeroSlider);
    } else {
        /* DOM уже готов — запускаем через микротаск чтобы Swiper успел загрузиться */
        setTimeout(initHeroSlider, 0);
    }
 
    /* Обработчик ресайза — обновляем слайдер */
    var _resizeTimer;
    window.addEventListener('resize', function () {
        clearTimeout(_resizeTimer);
        _resizeTimer = setTimeout(function () {
            if (_instance && !_instance.destroyed) {
                _instance.update();
                _instance.updateSize();
                ensureClickable();
            }
        }, 200);
    });
 
    /* Переинициализация для динамического контента Bitrix (AJAX) */
    if (typeof BX !== 'undefined') {
        BX.addCustomEvent('onAjaxSuccess', function () {
            /* Сбрасываем guard чтобы можно было переинициализировать */
            var el = document.querySelector(CONFIG.selector);
            if (el) el.removeAttribute('data-hero-init');
            setTimeout(initHeroSlider, 150);
        });
    }
 
    /* Клики на .hero-btn — пробрасываем аналитику, останавливаем всплытие */
    document.addEventListener('click', function (e) {
        var btn = e.target.closest('.hero-btn');
        if (!btn) return;
 
        e.stopPropagation();   /* предотвращаем баги Bitrix */
 
        try {
            if (typeof ym !== 'undefined')   ym(54643111, 'reachGoal', 'hero_click');
            if (typeof gtag !== 'undefined') gtag('event', 'hero_click', { event_category: 'hero' });
        } catch (err) { /* тихо игнорируем */ }
    });
 
}());