/*
    This script is responsible for trimming image title/name on the image results page. (Since I haven't figured out how to make this work in CSS.)
*/
document.addEventListener('DOMContentLoaded', function() {
    let imagesContainer = document.querySelector('.images');
    let observer;

    // Function to trim image titles based on the image width
    function trimTitles() {
        const images = document.querySelectorAll('.images .image');
        images.forEach((element) => {
            // Skip if the image has already been processed
            if (element.classList.contains('checked')) return;

            const imgElement = element.querySelector('img.clickable');
            const titleElement = element.querySelector('.img_title.clickable');
            const detailsElement = element.querySelector('.details');

            // Only process if the image is fully loaded
            if (imgElement.complete && imgElement.naturalWidth) {
                const imageWidth = imgElement.clientWidth;

                // Set the width of the details div and title to match the image width
                detailsElement.style.width = imageWidth + 'px';
                titleElement.style.maxWidth = imageWidth + 'px';

                // Mark this image as processed and add it to the "checked" blacklist
                element.classList.add('checked');
            }
        });
    }

    // Run trimTitles periodically every 500ms
    setInterval(trimTitles, 500);

    // Observe for dynamically added images
    function observeNewImages() {
        observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(function(node) {
                    if (node.nodeType === 1 && node.classList.contains('image') && !node.classList.contains('checked')) {
                        trimTitles(); // Call trimTitles for newly added image
                    }
                });
            });
        });

        // Observe the images container for changes
        observer.observe(imagesContainer, { childList: true, subtree: true });
    }

    // Run initial title trimming after page load
    trimTitles();

    // Start observing for dynamic image loading
    observeNewImages();
});