(function($){
    elementor.hooks.addAction('panel/open_editor/widget', function(panel, model, view) {

        // Prevent typing inside the readonly input
        panel.$el.on('keydown', '[data-setting="acf_repeater_subfield"] input[readonly]', function(e) {
            e.preventDefault(); // block any typing or keypress
        });

        panel.$el.on('click focus', '[data-setting="acf_repeater_subfield"] input[readonly]', function() {
            const $input = $(this);

            // Get the current repeater field selection to load subfields
            const $repeaterSelect = $input.closest('.elementor-control').prevAll('[data-setting="acf_repeater_field"]').find('select');
            const selectedRepeater = $repeaterSelect.val();

            if (!selectedRepeater) {
                alert('Please select a Repeater Field first.');
                $input.blur();
                return;
            }

            // Fetch subfields via AJAX
            $.post(trfxAjax.ajaxurl, {
                action: 'get_acf_repeater_subfields',
                repeater_name: selectedRepeater
            }, function(response) {
                if (response.success && response.data) {
                    const subfields = Object.entries(response.data).map(([key, label]) => ({
                        label: label,
                        value: key
                    }));

                    if ($input.data('ui-autocomplete')) {
                        $input.autocomplete('destroy');
                    }

                    $input.autocomplete({
                        minLength: 0,
                        source: subfields,
                        focus: function(event, ui) {
                            // Show label in input on arrow key navigation
                            $input.val(ui.item.label);
                            return false;
                        },
                        select: function(event, ui) {
                            // Set selected value and update model
                            $input.val(ui.item.label);

                            if (typeof elementor !== 'undefined' && elementor.channels && elementor.channels.data) {
                                const editorPanel = elementor.channels.data.request('editor:model');
                                if (editorPanel && editorPanel.setSetting) {
                                    editorPanel.setSetting('acf_repeater_subfield', ui.item.value);
                                }
                            }
                            return false;
                        }
                    }).autocomplete("search", ""); // Show dropdown immediately
                }
            });
        });

    });
})(jQuery);
