


 
function _t(key, fallback) {
    return (window._t && window._t[key]) || fallback || key;
}



window.tpImgFallback = function (img) {
    img.onerror = null;
    img.style.display = 'none';
    if (img.parentNode) img.parentNode.classList.add('video-card__thumb--noimg');
};

 
(function() {
    var container = null;
    var timers = [];

    function getContainer() {
        if (container) return container;
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
        return container;
    }

    window.showToast = function(message, type) {
        type = type || 'error';
        var wrap = getContainer();
        var toast = document.createElement('div');
        toast.className = 'toast toast--' + type;

        var icons = {
            error: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
            warning: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
            success: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
            info: '<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>'
        };

        var iconSpan = document.createElement('span');
        iconSpan.className = 'toast__icon';
        iconSpan.innerHTML = icons[type] || icons.info;
        var textSpan = document.createElement('span');
        textSpan.className = 'toast__text';
        textSpan.textContent = message;
        var closeBtn = document.createElement('button');
        closeBtn.className = 'toast__close';
        closeBtn.type = 'button';
        closeBtn.setAttribute('aria-label', 'Close');
        closeBtn.innerHTML = '&times;';
        toast.appendChild(iconSpan);
        toast.appendChild(textSpan);
        toast.appendChild(closeBtn);

        closeBtn.addEventListener('click', function() {
            dismiss(toast);
        });

        wrap.appendChild(toast);

        
        requestAnimationFrame(function() {
            toast.classList.add('toast--visible');
        });

        var timer = setTimeout(function() { dismiss(toast); }, 4000);
        timers.push({ el: toast, t: timer });
    };

    function dismiss(toast) {
        toast.classList.remove('toast--visible');
        toast.classList.add('toast--exit');
        setTimeout(function() {
            if (toast.parentNode) toast.parentNode.removeChild(toast);
        }, 300);
    }
})();

 
function authModal(tab) {
    var modal = document.getElementById('authModal');
    if (!modal) return;
    modal.classList.add('open');
    document.body.style.overflow = 'hidden';
    if (tab) authSwitchTab(tab);
}

function authClose() {
    var modal = document.getElementById('authModal');
    if (!modal) return;
    modal.classList.remove('open');
    document.body.style.overflow = '';
}

function authSwitchTab(tab) {
    var tabs = document.querySelector('.auth-tabs');
    if (tabs) tabs.style.display = (tab === 'forgot') ? 'none' : '';
    document.querySelectorAll('.auth-tabs__btn').forEach(function(b) {
        b.classList.toggle('active', b.dataset.tab === tab);
    });
    document.querySelectorAll('.auth-panel').forEach(function(p) {
        p.classList.toggle('active', p.id === 'panel-' + tab);
    });
    
    var msg = document.getElementById('authMsg');
    if (msg) { msg.className = 'auth-msg'; msg.textContent = ''; }
}

document.addEventListener('DOMContentLoaded', function() {

    
    var modal = document.getElementById('authModal');
    if (modal) {
        var csrf = modal.dataset.csrf || '';

        
        modal.querySelector('.auth-modal__close').addEventListener('click', authClose);

        
        

        
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && modal.classList.contains('open')) authClose();
        });

        
        modal.querySelectorAll('.auth-tabs__btn').forEach(function(btn) {
            btn.addEventListener('click', function() { authSwitchTab(btn.dataset.tab); });
        });

        
        var captchaProvider = modal.dataset.captchaProvider || '';
        var captchaSiteKey = modal.dataset.captchaSiteKey || '';
        var captchaOnRegister = modal.dataset.captchaOnRegister === '1';

        function doAuthFetch(form, url, btn, msg, originalText, extraParams) {
            var body = new URLSearchParams(new FormData(form));
            body.append('csrf_token', csrf);
            if (extraParams) {
                for (var k in extraParams) body.append(k, extraParams[k]);
            }

            fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: body.toString()
            })
            .then(function(res) { return res.json().then(function(d) { return { ok: res.ok, data: d }; }); })
            .then(function(res) {
                btn.disabled = false;
                btn.textContent = originalText;
                if (res.data.success) {
                    if (res.data.message) {
                        msg.className = 'auth-msg success';
                        msg.textContent = res.data.message;
                        form.reset();
                    } else {
                        window.location.reload();
                    }
                } else {
                    msg.className = 'auth-msg error';
                    msg.textContent = res.data.error || _t('an_error_occurred', 'An error occurred.');
                    
                    if (typeof grecaptcha !== 'undefined' && captchaProvider === 'v2') {
                        try { grecaptcha.reset(); } catch(e) {}
                    }
                    if (typeof turnstile !== 'undefined' && captchaProvider === 'turnstile') {
                        try { turnstile.reset(); } catch(e) {}
                    }
                }
            })
            .catch(function() {
                btn.disabled = false;
                btn.textContent = originalText;
                msg.className = 'auth-msg error';
                msg.textContent = _t('network_error', 'Network error. Please try again.');
            });
        }

        function authSubmit(formId, url, needsCaptcha) {
            var form = document.getElementById(formId);
            if (!form) return;
            form.addEventListener('submit', function(e) {
                e.preventDefault();
                var btn = form.querySelector('.btn-submit');
                var msg = document.getElementById('authMsg');
                var originalText = btn.textContent;
                btn.disabled = true;
                btn.textContent = _t('please_wait', 'Please wait...');
                msg.className = 'auth-msg';
                msg.textContent = '';

                if (needsCaptcha && captchaProvider === 'v3' && captchaSiteKey && typeof grecaptcha !== 'undefined') {
                    grecaptcha.ready(function() {
                        grecaptcha.execute(captchaSiteKey, { action: 'register' }).then(function(token) {
                            doAuthFetch(form, url, btn, msg, originalText, { 'g-recaptcha-response': token });
                        });
                    });
                } else {
                    doAuthFetch(form, url, btn, msg, originalText);
                }
            });
        }

        var lp = (modal.dataset.langPrefix || window._langPrefix || '');
        authSubmit('formLogin', lp + '/login', false);
        authSubmit('formRegister', lp + '/register', captchaOnRegister);
        authSubmit('formForgot', lp + '/forgot-password', false);
    }

    
    document.querySelectorAll('.vote-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            if (btn.disabled) return;
            var videoId = btn.dataset.videoId;
            var type = btn.dataset.vote;
            var csrf = btn.dataset.csrf || '';
            var actions = btn.closest('.video-info__actions');

            
            var allVoteBtns = actions ? actions.querySelectorAll('.vote-btn') : [btn];
            allVoteBtns.forEach(function(b) { b.disabled = true; });

            fetch((window._langPrefix || '') + '/video/' + videoId + '/' + type, {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-Token': csrf
                }
            })
            .then(function(res) {
                if (res.status === 429) {
                    return res.json().then(function(d) { showToast(d.message || _t('too_many_requests', 'Too many requests. Please wait.'), 'warning'); return null; });
                }
                return res.json();
            })
            .then(function(data) {
                if (!data) return;
                if (data.error) {
                    if (data.error === 'auth_required') authModal('login');
                    return;
                }
                var likeBtn = actions ? actions.querySelector('.vote-btn.like') : null;
                var dislikeBtn = actions ? actions.querySelector('.vote-btn.dislike') : null;
                if (likeBtn) {
                    likeBtn.querySelector('.vote-count').textContent = data.likes;
                    likeBtn.classList.toggle('active', data.userVote === 'like');
                }
                if (dislikeBtn) {
                    dislikeBtn.querySelector('.vote-count').textContent = data.dislikes;
                    dislikeBtn.classList.toggle('active', data.userVote === 'dislike');
                }
            })
            .catch(function() {})
            .finally(function() {
                allVoteBtns.forEach(function(b) { b.disabled = false; });
            });
        });
    });

    
    var favBtn = document.getElementById('favoriteBtn');
    if (favBtn) {
        favBtn.addEventListener('click', function(e) {
            e.preventDefault();
            if (favBtn.disabled) return;
            var videoId = favBtn.dataset.videoId;
            var csrf = favBtn.dataset.csrf || '';
            favBtn.disabled = true;

            fetch((window._langPrefix || '') + '/favorite/' + videoId + '/toggle', {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'X-CSRF-Token': csrf
                }
            })
            .then(function(res) {
                if (res.status === 429) {
                    return res.json().then(function(d) { showToast(d.message || _t('too_many_requests', 'Too many requests. Please wait.'), 'warning'); return null; });
                }
                return res.json();
            })
            .then(function(data) {
                if (!data) return;
                if (data.error) {
                    if (data.error === 'auth_required') authModal('login');
                    return;
                }
                favBtn.classList.toggle('active', data.favorited);
                favBtn.title = data.favorited ? _t('remove_from_favorites', 'Remove from favorites') : _t('add_to_favorites', 'Add to favorites');
                var svg = favBtn.querySelector('svg');
                if (svg) svg.setAttribute('fill', data.favorited ? 'currentColor' : 'none');
            })
            .catch(function() {})
            .finally(function() {
                favBtn.disabled = false;
            });
        });
    }

    
    var siteHeader = document.getElementById('siteHeader');
    var scrollBurger = document.getElementById('scrollBurger');
    var scrollSidebar = document.getElementById('scrollSidebar');
    var scrollSidebarClose = document.getElementById('scrollSidebarClose');
    var scrollSidebarBackdrop = document.getElementById('scrollSidebarBackdrop');

    if (siteHeader) {
        var thresholdOn = 100;
        var thresholdOff = 30;
        var isScrolled = false;
        var ticking = false;

        function updateScrollState() {
            var scrollY = window.scrollY || window.pageYOffset;
            if (!isScrolled && scrollY > thresholdOn) {
                isScrolled = true;
                siteHeader.classList.add('header--scrolled');
                document.body.classList.add('header-scrolled');
            } else if (isScrolled && scrollY < thresholdOff) {
                isScrolled = false;
                siteHeader.classList.remove('header--scrolled');
                document.body.classList.remove('header-scrolled');
                if (scrollSidebar) scrollSidebar.classList.remove('open');
            }
            ticking = false;
        }

        window.addEventListener('scroll', function() {
            if (!ticking) {
                requestAnimationFrame(updateScrollState);
                ticking = true;
            }
        }, { passive: true });

        
        updateScrollState();
    }

    
    if (scrollBurger && scrollSidebar) {
        scrollBurger.addEventListener('click', function() {
            scrollSidebar.classList.toggle('open');
        });
        if (scrollSidebarBackdrop) {
            scrollSidebarBackdrop.addEventListener('click', function() {
                scrollSidebar.classList.remove('open');
            });
        }
        if (scrollSidebarClose) {
            scrollSidebarClose.addEventListener('click', function() {
                scrollSidebar.classList.remove('open');
            });
        }
        
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && scrollSidebar.classList.contains('open')) {
                scrollSidebar.classList.remove('open');
            }
        });
    }

    
    var burger = document.querySelector('.header__burger');
    var mobileNav = document.getElementById('mobileNav');
    var mobileNavBackdrop = document.getElementById('mobileNavBackdrop');
    var mobileNavClose = document.getElementById('mobileNavClose');

    window.closeMobileNav = function() {
        if (mobileNav) mobileNav.classList.remove('open');
        document.body.style.overflow = '';
    };

    if (burger && mobileNav) {
        burger.addEventListener('click', function() {
            mobileNav.classList.add('open');
            document.body.style.overflow = 'hidden';
        });
        if (mobileNavBackdrop) {
            mobileNavBackdrop.addEventListener('click', closeMobileNav);
        }
        if (mobileNavClose) {
            mobileNavClose.addEventListener('click', closeMobileNav);
        }
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && mobileNav.classList.contains('open')) {
                closeMobileNav();
            }
        });
    }

    
    function toggleTheme() {
        var html = document.documentElement;
        var current = html.getAttribute('data-theme') || 'light';
        var next = current === 'dark' ? 'light' : 'dark';
        html.classList.add('theme-transitioning');
        html.setAttribute('data-theme', next);
        localStorage.setItem('theme', next);
        uddSyncThemeSeg();
        setTimeout(function() {
            html.classList.remove('theme-transitioning');
        }, 350);
    }
    var themeBtnMobile = document.getElementById('themeToggleMobile');
    if (themeBtnMobile) themeBtnMobile.addEventListener('click', toggleTheme);

    
    var uddWrap = document.getElementById('uddWrap');
    var uddTrigger = document.getElementById('uddTrigger');
    var uddDropdown = document.getElementById('uddDropdown');

    function uddSyncThemeSeg() {
        var seg = document.getElementById('uddThemeSeg');
        if (!seg) return;
        var current = document.documentElement.getAttribute('data-theme') || 'light';
        seg.setAttribute('data-active', current);
        seg.querySelectorAll('.udd__seg-btn').forEach(function(b) {
            b.classList.toggle('active', b.dataset.themeVal === current);
        });
    }

    if (uddWrap && uddTrigger) {
        
        uddSyncThemeSeg();

        var uddCloseTimer = null;

        function uddOpen() {
            clearTimeout(uddCloseTimer);
            uddWrap.classList.add('open');
            uddTrigger.setAttribute('aria-expanded', 'true');
        }

        function uddClose() {
            uddWrap.classList.remove('open');
            uddTrigger.setAttribute('aria-expanded', 'false');
        }

        function uddDelayClose() {
            uddCloseTimer = setTimeout(uddClose, 200);
        }

        
        uddWrap.addEventListener('mouseenter', uddOpen);
        uddWrap.addEventListener('mouseleave', uddDelayClose);

        
        uddTrigger.addEventListener('click', function(e) {
            e.stopPropagation();
            if (uddWrap.classList.contains('open')) uddClose(); else uddOpen();
        });

        
        document.addEventListener('click', function(e) {
            if (uddWrap.classList.contains('open') && !uddWrap.contains(e.target)) {
                uddClose();
            }
        });

        
        document.addEventListener('keydown', function(e) {
            if (e.key === 'Escape' && uddWrap.classList.contains('open')) {
                uddClose();
                uddTrigger.focus();
            }
        });

        
        var seg = document.getElementById('uddThemeSeg');
        if (seg) {
            seg.addEventListener('click', function(e) {
                var btn = e.target.closest('.udd__seg-btn');
                if (!btn) return;
                var val = btn.dataset.themeVal;
                var current = document.documentElement.getAttribute('data-theme') || 'light';
                if (val !== current) {
                    toggleTheme();
                }
            });
        }
    }

    
    document.querySelectorAll('[data-vtype]').forEach(function(link) {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            var type = link.dataset.vtype;
            if (!type) return;
            
            var switchUrl = link.dataset.switchUrl;
            if (switchUrl) {
                window.location.href = switchUrl;
                return;
            }
            
            var expires = new Date(Date.now() + 365 * 864e5).toUTCString();
            document.cookie = 'tp_video_type=' + encodeURIComponent(type) + ';path=/;expires=' + expires + ';SameSite=Lax';
            var url = new URL(window.location.href);
            url.searchParams.delete('page');
            window.location.href = url.toString();
        });
    });

    
    var searchInput = document.querySelector('.header__search input');
    if (searchInput) {
        document.addEventListener('keydown', function(e) {
            if (e.key === '/' && document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') {
                e.preventDefault();
                searchInput.focus();
            }
        });
    }

    
    document.querySelectorAll('.comment__reply-btn').forEach(function(btn) {
        btn.addEventListener('click', function(e) {
            e.preventDefault();
            var commentId = btn.dataset.commentId;
            var form = document.querySelector('.comment-form');
            if (form) {
                var parentInput = form.querySelector('input[name="parent_id"]');
                if (!parentInput) {
                    parentInput = document.createElement('input');
                    parentInput.type = 'hidden';
                    parentInput.name = 'parent_id';
                    form.appendChild(parentInput);
                }
                parentInput.value = commentId;
                form.querySelector('textarea').focus();
                form.querySelector('textarea').placeholder = _t('reply_to_comment', 'Reply to comment...');
            }
        });
    });

    
    var titleInput = document.getElementById('title');
    var slugInput = document.getElementById('slug');
    if (titleInput && slugInput && !slugInput.value) {
        titleInput.addEventListener('input', function() {
            slugInput.value = titleInput.value
                .toLowerCase()
                .normalize('NFD')
                .replace(/[\u0300-\u036f]/g, '')
                .replace(/[^a-z0-9]+/g, '-')
                .replace(/^-|-$/g, '');
        });
    }

    
    (function() {
        
        
        
        var hoverOK = !!(window.matchMedia && window.matchMedia('(hover: hover)').matches);
        var activeThumb = null;
        var spriteEl = null;
        var progressEl = null;
        var spriteInterval = null;
        var currentFrame = 0;

        function startSprite(thumb) {
            if (!hoverOK) return;
            var src = thumb.getAttribute('data-timeline');
            var count = parseInt(thumb.getAttribute('data-timeline-count')) || 10;
            if (!src) return;

            activeThumb = thumb;
            currentFrame = 0;

            spriteEl = thumb.querySelector('.video-card__sprite');
            if (!spriteEl) {
                spriteEl = document.createElement('div');
                spriteEl.className = 'video-card__sprite';
                spriteEl.style.backgroundImage = 'url(' + src + ')';
                thumb.appendChild(spriteEl);
            }

            progressEl = thumb.querySelector('.video-card__preview-progress');
            if (!progressEl) {
                progressEl = document.createElement('div');
                progressEl.className = 'video-card__preview-progress';
                thumb.appendChild(progressEl);
            }

            var cols = 10;
            spriteEl.style.backgroundPosition = '0 0';
            spriteEl.style.backgroundSize = (cols * 100) + '% auto';
            spriteEl.classList.add('is-playing');
            thumb.classList.add('is-previewing');
            progressEl.style.width = '0%';

            spriteInterval = setInterval(function() {
                currentFrame = (currentFrame + 1) % count;
                var col = currentFrame % cols;
                var row = Math.floor(currentFrame / cols);
                spriteEl.style.backgroundPosition = '-' + (col * 100) + '% -' + (row * 100) + '%';
                progressEl.style.width = ((currentFrame + 1) / count * 100) + '%';
            }, 600);
        }

        function stopSprite() {
            if (spriteInterval) { clearInterval(spriteInterval); spriteInterval = null; }
            if (spriteEl) { spriteEl.classList.remove('is-playing'); spriteEl = null; }
            if (activeThumb) { activeThumb.classList.remove('is-previewing'); }
            if (progressEl) { progressEl.style.width = '0%'; progressEl = null; }
            activeThumb = null;
            currentFrame = 0;
        }

        document.addEventListener('mouseenter', function(e) {
            if (!e.target || !e.target.closest) return;
            var thumb = e.target.closest('.video-card__thumb[data-timeline]');
            if (!thumb) return;
            startSprite(thumb);
        }, true);

        document.addEventListener('mouseleave', function(e) {
            if (!e.target || !e.target.closest) return;
            var thumb = e.target.closest('.video-card__thumb[data-timeline]');
            if (!thumb) return;
            stopSprite();
        }, true);

        document.addEventListener('touchstart', function() {
            if (activeThumb) stopSprite();
        }, { passive: true });
    })();

    
    (function() {
        
        var hoverOK = !!(window.matchMedia && window.matchMedia('(hover: hover)').matches);
        var activeThumb = null;
        var activeVideo = null;
        var progressBar = null;
        var progressRAF = null;

        function startPreview(thumb) {
            if (!hoverOK) return;
            var src = thumb.getAttribute('data-preview');
            if (!src) return;

            
            
            
            var video = thumb.querySelector('.video-card__preview');
            if (!video) {
                video = document.createElement('video');
                video.className = 'video-card__preview';
                video.muted = true;
                video.loop = true;
                video.playsInline = true;
                video.setAttribute('muted', '');
                video.setAttribute('playsinline', '');
                video.preload = 'none';
                thumb.appendChild(video);
            }

            if (!video.src || video.src === '') {
                
                
                
                video.addEventListener('error', function () {
                    video.classList.remove('is-playing');
                    if (activeThumb) { activeThumb.classList.remove('is-previewing'); }
                }, { once: true });
                video.src = src;
            }

            activeThumb = thumb;
            activeVideo = video;

            progressBar = thumb.querySelector('.video-card__preview-progress');
            if (!progressBar) {
                progressBar = document.createElement('div');
                progressBar.className = 'video-card__preview-progress';
                thumb.appendChild(progressBar);
            }
            progressBar.style.width = '0%';

            video.currentTime = 0;
            var playPromise = video.play();
            if (playPromise !== undefined) {
                playPromise.then(function() {
                    video.classList.add('is-playing');
                    thumb.classList.add('is-previewing');
                    updateProgress();
                }).catch(function() {});
            }
        }

        function stopPreview() {
            if (progressRAF) {
                cancelAnimationFrame(progressRAF);
                progressRAF = null;
            }
            if (activeThumb) {
                activeThumb.classList.remove('is-previewing');
            }
            if (activeVideo) {
                activeVideo.classList.remove('is-playing');
                activeVideo.pause();
                activeVideo.currentTime = 0;
            }
            if (progressBar) {
                progressBar.style.width = '0%';
            }
            activeThumb = null;
            activeVideo = null;
            progressBar = null;
        }

        function updateProgress() {
            if (!activeVideo || !progressBar) return;
            if (activeVideo.duration && activeVideo.duration > 0) {
                var pct = (activeVideo.currentTime / activeVideo.duration) * 100;
                progressBar.style.width = pct + '%';
            }
            progressRAF = requestAnimationFrame(updateProgress);
        }

        
        document.addEventListener('mouseenter', function(e) {
            if (!e.target || !e.target.closest) return;
            var thumb = e.target.closest('.video-card__thumb[data-preview]');
            if (!thumb) return;
            startPreview(thumb);
        }, true);

        document.addEventListener('mouseleave', function(e) {
            if (!e.target || !e.target.closest) return;
            var thumb = e.target.closest('.video-card__thumb[data-preview]');
            if (!thumb) return;
            stopPreview();
        }, true);

        
        document.addEventListener('touchstart', function() {
            if (activeVideo) stopPreview();
        }, { passive: true });
    })();

    
    document.addEventListener('click', function(e) {
        var toggle = e.target.closest('.section-sort-dropdown__toggle');
        if (toggle) {
            e.preventDefault();
            var dd = toggle.closest('.section-sort-dropdown');
            var wasOpen = dd.classList.contains('open');
            
            document.querySelectorAll('.section-sort-dropdown.open').forEach(function(el) {
                el.classList.remove('open');
            });
            if (!wasOpen) dd.classList.add('open');
            return;
        }
        
        if (!e.target.closest('.section-sort-dropdown')) {
            document.querySelectorAll('.section-sort-dropdown.open').forEach(function(el) {
                el.classList.remove('open');
            });
        }
    });

     
    document.querySelectorAll('.header__search, .mobile-nav__search, .search-page__form').forEach(function(form) {
        var input = form.querySelector('input[name="q"]');
        if (!input) return;

        var box = document.createElement('div');
        box.className = 'search-suggest';
        form.style.position = 'relative';
        form.appendChild(box);

        var timer = null;
        var cache = {};

        input.addEventListener('input', function() {
            clearTimeout(timer);
            var q = this.value.trim();
            if (q.length < 2) { box.innerHTML = ''; box.style.display = 'none'; return; }
            if (cache[q]) { render(cache[q]); return; }
            timer = setTimeout(function() {
                fetch((window._langPrefix || '') + '/search/suggest?q=' + encodeURIComponent(q))
                    .then(function(r) { return r.json(); })
                    .then(function(items) { cache[q] = items; render(items); })
                    .catch(function() { box.style.display = 'none'; });
            }, 200);
        });

        function render(items) {
            if (!items.length) { box.innerHTML = ''; box.style.display = 'none'; return; }
            box.innerHTML = items.map(function(t) {
                return '<a href="' + (window._langPrefix || '') + '/search?q=' + encodeURIComponent(t) + '" class="search-suggest__item">' +
                    t.replace(/</g, '&lt;') + '</a>';
            }).join('');
            box.style.display = 'block';
        }

        input.addEventListener('blur', function() {
            setTimeout(function() { box.style.display = 'none'; }, 150);
        });
        input.addEventListener('focus', function() {
            if (box.innerHTML && this.value.trim().length >= 2) box.style.display = 'block';
        });
    });

});
