<script>
    document.addEventListener('DOMContentLoaded', function() {
        const handleInputChange = (event) => {
            const target = event.target;
            // Dotted paths are usually stored in 'id', fallback to 'name'
            let name = target.getAttribute('id') || target.getAttribute('name');
            if (!name) return;

            // Normalize input names like data[sections_builder][uuid][data][headline] to dot notation
            name = name.replace(/\[/g, '.').replace(/\]/g, '');

            // Target the preview iframe inside the Filament Peek modal
            const iframe = document.querySelector('.filament-peek-panel-body iframe');
            if (iframe && iframe.contentWindow) {
                iframe.contentWindow.postMessage({
                    source: 'filament-visual-editor',
                    data: {
                        [name]: target.value
                    }
                }, '*');
            }
        };

        // Listen to all inputs and changes globally on the parent document
        document.addEventListener('input', handleInputChange, true);
        document.addEventListener('change', handleInputChange, true);
    });
</script>
