(function ($) {
    $(function () {
        $('.tr-header-menu nav > ul > li').slice(-4).addClass('tr-header-menu-last-items');
    });
    // Initialize Masonry after all images have loaded
    document.addEventListener('DOMContentLoaded', function () {
        var grid = document.querySelector('#main-content .masonry');
        if (!grid) return;

        imagesLoaded(grid, { background: true }, function () {
            var msnry = new Masonry(grid, {
                itemSelector: '.masonry-item',
                columnWidth: '.masonry-item',
                percentPosition: true,
            });
            msnry.layout();
            // Fallback: ensure layout after all resources (works on reload)
            window.addEventListener('load', function () {
                msnry.layout();
            });
        });
    });

    // Reading Progress Bar
    var bar = document.getElementById('tr-progress-bar');

    var article = document.getElementById('tr-post-content');

    if (bar && article) {
        window.addEventListener('scroll', function () {
            var articleTop = article.offsetTop;
            var articleHeight = article.offsetHeight;
            var scrollTop = window.scrollY || document.documentElement.scrollTop;
            var windowHeight = window.innerHeight;

            // Progress starts when article starts, ends when article ends
            var progress = ((scrollTop - articleTop) / (articleHeight - windowHeight)) * 100;

            // Clamp between 0 and 100
            progress = Math.min(100, Math.max(0, progress));

            bar.style.width = progress + '%';
        }, { passive: true });
    }

    // Preloader
    var preloader = document.getElementById('tr-preloader');
    if (preloader) {
        window.addEventListener('load', function () {
            preloader.classList.add('tr-preloader-hidden');

            // Remove from DOM after transition ends
            preloader.addEventListener('transitionend', function () {
                preloader.remove();
            });
        });
    }

    // --- Back to Top ---
    const btn = document.getElementById('back-to-top');
    if (btn) {
        // native scroll event 
        window.addEventListener('scroll', function () {
            if (window.scrollY > 200) {
                btn.classList.add('visible');
            } else {
                btn.classList.remove('visible');
            }
        }, { passive: true });

        // Click handler
        btn.addEventListener('click', function () {
            window.scrollTo({ top: 0, behavior: 'smooth' });
        });
    }

})(jQuery);