 document.addEventListener('DOMContentLoaded', () => {

    document.body.addEventListener('click', (event) => {

        const button = event.target.closest('.open-media');
        if (!button) return;

        if (!wp.media) {
            alert('Media library is not available. Make sure wp_enqueue_media() is called.');
            // show the full wp object in console for debugging
            console.debug('wp object:', wp);
            return;
        }

        const index = button.dataset.index;

        const frame = wp.media({
            title: 'Select a logo image',
            button: {
                text: 'Use this image'
            },
            multiple: false,
            library: {
                type: 'image'
            }
        });

        frame.on('select', () => {
            const attachment = frame
                .state()
                .get('selection')
                .first()
                .toJSON();

            // Store per button / per row
            console.log(`Row ${index} selected image:`, attachment.url);

            // Example: update preview near the clicked button
            const preview = button.closest('.row')?.querySelector('.image-preview');
            if (preview) preview.src = attachment.url;

            // Example: store in hidden input
            const input = button.closest('td')?.querySelector('.email-logo-input');

            // trigger change event to notify Alpine.js
            if (input) {
                input.value = attachment.url;
                // this notifies alpine.js of the change
                input.dispatchEvent(new Event('input', { bubbles: true }));
            }

        });

        frame.open();
    });

});