(function () {
    document.addEventListener('DOMContentLoaded', function () {
        var lightbox = document.getElementById('fk-lightbox');
        if (!lightbox) {
            return;
        }

        var img = lightbox.querySelector('.fk-lightbox-img');
        var caption = lightbox.querySelector('.fk-lightbox-caption');
        var closeBtn = lightbox.querySelector('.fk-lightbox-close');
        var backdrop = lightbox.querySelector('.fk-lightbox-backdrop');

        function openLightbox(src, alt) {
            img.src = src;
            img.alt = alt || '';
            caption.textContent = alt || '';
            caption.hidden = !alt;
            lightbox.hidden = false;
            document.body.classList.add('fk-lightbox-open');
            closeBtn.focus();
        }

        function closeLightbox() {
            lightbox.hidden = true;
            img.src = '';
            document.body.classList.remove('fk-lightbox-open');
        }

        document.querySelectorAll('.fk-img-open').forEach(function (button) {
            button.addEventListener('click', function () {
                openLightbox(button.dataset.src, button.dataset.caption);
            });
        });

        closeBtn.addEventListener('click', closeLightbox);
        backdrop.addEventListener('click', closeLightbox);

        document.addEventListener('keydown', function (event) {
            if (event.key === 'Escape' && !lightbox.hidden) {
                closeLightbox();
            }
        });
    });
})();
