document.addEventListener('dblclick', function (event) {
    let elem = event.target;
    let imageId = elem.getAttribute('data-image-id') || elem.id || elem.tagName || "Unknown";

    // Debug log for the double-click event
    console.log('Double-click detected. Element: ', elem);
    console.log('Image ID or element ID to send: ', imageId);

    let jsonObject = {
        action: 'showImage',
        id: imageId
    };

    try {
        window.chrome.webview.postMessage(jsonObject); // Send JSON object directly
        console.log('Message sent: ', jsonObject); // Log the message that was sent
    } catch (err) {
        console.error('Error sending message to WebView2: ', err);
    }
});

document.addEventListener('DOMContentLoaded', function () {
    // Function to attach click handler to 'load-more' element
    function attachLoadMoreHandler() {
        const loadMoreMessage = document.querySelector('.load-more');

        // Debug log to check if the load-more element is found
        console.log('Attempting to find .load-more element: ', loadMoreMessage);

        if (loadMoreMessage) {
            loadMoreMessage.addEventListener('click', function () {
                let jsonObject = { action: 'loadOlderMessages' };
                console.log('Click event triggered. Sending message: ', jsonObject);

                try {
                    window.chrome.webview.postMessage(jsonObject); // Send JSON object directly
                } catch (err) {
                    console.error('Error sending loadOlderMessages action: ', err);
                }
            });
        } else {
            console.log('No .load-more element found.');
        }
    }

    // Call the function to attach the event handler
    attachLoadMoreHandler();

    // Optional: Use MutationObserver if the element might be added later
    const observer = new MutationObserver(function (mutationsList) {
        for (let mutation of mutationsList) {
            if (mutation.type === 'childList') {
                console.log('DOM mutation detected, reattaching .load-more click handler.');
                attachLoadMoreHandler(); // Try to attach again if new elements are added
            }
        }
    });

    // Observe the entire document for new elements being added
    observer.observe(document.body, { childList: true, subtree: true });
});


