document.addEventListener('DOMContentLoaded', function() {
    // This event listener is delegated to the document to handle elements
    // that might be added to the DOM dynamically, e.g., in list views.
    document.body.addEventListener('click', function(e) {
        // We are only interested in clicks on our copy button
        if (!e.target.classList.contains('spdfed-copy-button')) {
            return;
        }

        const button = e.target;
        const targetSelector = button.getAttribute('data-clipboard-target');
        const textToCopy = document.querySelector(targetSelector);
        
        // Find the feedback element. We assume it's the next sibling of the button's parent container.
        // This is more robust than relying on a specific ID pattern.
        const feedbackElement = button.parentElement.nextElementSibling;

        if (textToCopy) {
            textToCopy.select();
            textToCopy.setSelectionRange(0, 99999); // For mobile devices

            try {
                const successful = document.execCommand('copy');
                if (feedbackElement) {
                    feedbackElement.textContent = successful ? 'Copied!' : 'Copy failed.';
                }
            } catch (err) {
                if (feedbackElement) {
                    feedbackElement.textContent = 'Oops, unable to copy.';
                }
            }

            // Clear the feedback message after a couple of seconds
            if (feedbackElement) {
                setTimeout(function() {
                    feedbackElement.textContent = '';
                }, 2000);
            }

            // Deselect the text
            window.getSelection().removeAllRanges();
        }
    });
}); 