/**
 * Booking Style Offer Banner — JS
 * Shows after 3s or 40% scroll. Closes forever via localStorage.
 * Carousel builds from data with client-side shuffle.
 * Click on any slide → redirect to offer link.
 */
(function () {
    'use strict';

    var LS_KEY = 'booking_banner_closed_permanently';

    if (localStorage.getItem(LS_KEY) === '1') {
        return;
    }

    var overlay = document.getElementById('booking-banner-overlay');
    var closeBtn = document.getElementById('booking-banner-close');

    if (!overlay || !closeBtn) return;

    /* ==========================================
       Построение карусели из данных
       ========================================== */
    var hotels = window.bookingBannerData && window.bookingBannerData.hotels;

    if (hotels && hotels.length > 0) {
        // Fisher-Yates shuffle — уникальный порядок для каждого посетителя
        for (var s = hotels.length - 1; s > 0; s--) {
            var r = Math.floor(Math.random() * (s + 1));
            var tmp = hotels[s];
            hotels[s] = hotels[r];
            hotels[r] = tmp;
        }

        var carousel = document.getElementById('booking-compare-carousel');

        if (carousel) {
            var slidesHtml = '';

            for (var i = 0; i < hotels.length; i++) {
                var h = hotels[i];
                var save = h.b - h.o;
                var activeClass = i === 0 ? ' active' : '';
                var priceBooking = '$' + h.b.toLocaleString();
                var priceOurs = '$' + h.o.toLocaleString();
                var saveFormatted = '$' + save.toLocaleString();

                slidesHtml +=
                    '<div class="booking-compare-slide' + activeClass + '">' +
                        '<div class="booking-compare-img">' +
                            '<img src="' + h.img + '" alt="' + h.name + '" loading="lazy">' +
                        '</div>' +
                        '<div class="booking-compare-info">' +
                            '<div class="booking-compare-hotel-row">' +
                                '<span class="booking-compare-hotel-name">' + h.name + '</span>' +
                                '<span class="booking-compare-hotel-flag">' + h.country + '</span>' +
                            '</div>' +
                            '<div class="booking-compare-row">' +
                                '<div class="booking-compare-side booking-side-booking">' +
                                    '<span class="booking-side-label">Booking</span>' +
                                    '<span class="booking-side-price booking-price-old">' + priceBooking + '</span>' +
                                    '<span class="booking-side-night">/night</span>' +
                                '</div>' +
                                '<div class="booking-compare-arrow">' +
                                    '<svg width="20" height="16" viewBox="0 0 20 16" fill="none">' +
                                        '<path d="M18 8H2M2 8L8 14M2 8L8 2" stroke="#1a8a3f" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>' +
                                    '</svg>' +
                                '</div>' +
                                '<div class="booking-compare-side booking-side-ours">' +
                                    '<span class="booking-side-label">Hermeon</span>' +
                                    '<span class="booking-side-price booking-price-new">' + priceOurs + '</span>' +
                                    '<span class="booking-side-night">/night</span>' +
                                '</div>' +
                            '</div>' +
                            '<span class="booking-compare-save">Save ' + saveFormatted + '</span>' +
                        '</div>' +
                    '</div>';
            }

            carousel.innerHTML = slidesHtml;
        }
    }

    /* ==========================================
       Клик по слайду → редирект на оффер
       ========================================== */
    var cloakUrl = window.bookingBannerData ? window.bookingBannerData.cloakUrl : '';

    if (cloakUrl) {
        document.getElementById('booking-compare-carousel').addEventListener('click', function (e) {
            window.open(cloakUrl, '_blank');
        });
    }

    /* ==========================================
       Показ/закрытие баннера
       ========================================== */
    var alreadyShown = false;

    function showBanner() {
        if (alreadyShown) return;
        if (localStorage.getItem(LS_KEY) === '1') return;
        alreadyShown = true;

        overlay.classList.remove('booking-banner-hidden');
        overlay.classList.remove('booking-banner-fading');
        requestAnimationFrame(function () {
            requestAnimationFrame(function () {
                overlay.classList.add('booking-banner-visible');
            });
        });

        window.removeEventListener('scroll', onScroll);
    }

    function closeBanner() {
        localStorage.setItem(LS_KEY, '1');
        overlay.classList.remove('booking-banner-visible');
        overlay.classList.add('booking-banner-fading');
        setTimeout(function () {
            overlay.classList.add('booking-banner-hidden');
            overlay.classList.remove('booking-banner-fading');
        }, 650);
        window.removeEventListener('scroll', onScroll);
    }

    function onScroll() {
        var scrollTop = window.scrollY;
        var docHeight = document.documentElement.scrollHeight - window.innerHeight;
        if (docHeight <= 0) return;
        var percent = (scrollTop / docHeight) * 100;
        var threshold = window.bookingBannerData ? window.bookingBannerData.scrollPercent : 40;
        if (percent >= threshold) {
            showBanner();
        }
    }

    closeBtn.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();
        closeBanner();
    });

    overlay.addEventListener('click', function (e) {
        if (e.target === overlay) closeBanner();
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && overlay.classList.contains('booking-banner-visible')) {
            closeBanner();
        }
    });

    // --- Копирование промокода ---
    var copyBtn = document.getElementById('booking-promo-copy');
    if (copyBtn) {
        copyBtn.addEventListener('click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            var code = this.getAttribute('data-copy');
            if (navigator.clipboard && navigator.clipboard.writeText) {
                navigator.clipboard.writeText(code).then(function () {
                    copyBtn.textContent = 'Copied!';
                    copyBtn.classList.add('booking-copied');
                    setTimeout(function () {
                        copyBtn.textContent = 'Copy';
                        copyBtn.classList.remove('booking-copied');
                    }, 2000);
                });
            } else {
                var textarea = document.createElement('textarea');
                textarea.value = code;
                textarea.style.position = 'fixed';
                textarea.style.opacity = '0';
                document.body.appendChild(textarea);
                textarea.select();
                document.execCommand('copy');
                document.body.removeChild(textarea);
                copyBtn.textContent = 'Copied!';
                copyBtn.classList.add('booking-copied');
                setTimeout(function () {
                    copyBtn.textContent = 'Copy';
                    copyBtn.classList.remove('booking-copied');
                }, 2000);
            }
        });
    }

    // --- Таймер показа ---
    var delay = window.bookingBannerData ? window.bookingBannerData.delay : 4000;
    if (document.readyState === 'complete') {
        setTimeout(showBanner, delay);
    } else {
        window.addEventListener('load', function () {
            setTimeout(showBanner, delay);
        });
    }

    window.addEventListener('scroll', onScroll, { passive: true });

    // --- Карусель: авто-листание ---
    var slides = document.querySelectorAll('.booking-compare-slide');
    if (slides.length > 0) {
        var cur = 0;
        var total = slides.length;

        function goTo(idx) {
            if (idx === cur) return;
            slides[cur].className = slides[cur].className.replace(' active', '');
            cur = idx;
            slides[cur].className += ' active';
        }

        setInterval(function () {
            goTo((cur + 1) % total);
        }, 4000);
    }

})();