// Function to dynamically handle showing input field for custom values
jQuery(document).on("change", ".cf7-select", function() {
    let selectedValue = jQuery(this).val();
    // Check if the selected value is "custom" (replace 'custom' with the actual custom value)
    if (selectedValue === "iafwzdesk_custom_value") {
        // Add a text input right after the select element
        jQuery(this).after('<div style="position: relative;"><textarea type="text" class="iafwzdesk-setup-fm-custom-input" placeholder="Enter text or choose from options"> </textarea><div class="iafwzdesk-setup-fm-dropdownSuggestions"></div> </div>');
    } else {
        // Remove the custom input field if it exists
        jQuery(this).next().remove();
    }
});

let availableFields = []; // Declare globally

// Define iafwzdesk_updateAvailableFields in the global scope
const iafwzdesk_updateAvailableFields = (cf7Fields) => {
    if (cf7Fields && Array.isArray(cf7Fields) && cf7Fields.length > 0) {
        availableFields = cf7Fields
            .filter(row => row && typeof row.key === 'string' && !row.key.startsWith("iafwzdesk_")) // Ensure row exists and row.key doesn't start with "iafwzdesk_"
            .map(row => ({ key: row.key, label: row.label })); // Map to an object with key and label
    }
};


document.addEventListener('DOMContentLoaded', () => {
    // Event delegation for input events on dynamically added inputs
    document.body.addEventListener('input', (e) => {
        if (e.target.classList.contains('iafwzdesk-setup-fm-custom-input')) {
            const inputField = e.target;
            const dropdown = inputField.nextElementSibling;

            if (!dropdown || !dropdown.classList.contains('iafwzdesk-setup-fm-dropdownSuggestions')) return;

            const inputValue = inputField.value;
            const query = inputValue.split(' ').pop().toLowerCase();
            dropdown.innerHTML = ''; // Clear previous suggestions

            if (query) {
                const filteredFields = availableFields.filter(field =>
                    query === '' || field.label.toLowerCase().includes(query)
                );

                if (filteredFields.length > 0) {
                    filteredFields.forEach(field => {
                        const fieldSlug = field.key;
                        const suggestion = document.createElement('div');
                        suggestion.className = 'iafwzdesk-setup-fm-suggestion-item';
                        suggestion.textContent = field.label;
                        suggestion.dataset.field = `\${${fieldSlug}}`;

                        // Add click event to suggestion
                        suggestion.addEventListener('click', () => {
                            const words = inputValue.split(' ');
                            words.pop(); // Remove the last word
                            words.push(suggestion.dataset.field); // Add the selected key
                            inputField.value = words.join(' '); // Update the input value
                            dropdown.style.display = 'none'; // Hide the dropdown
                        });

                        dropdown.appendChild(suggestion);
                    });

                    dropdown.style.display = 'block'; // Show the dropdown
                } else {
                    dropdown.style.display = 'none'; // Hide the dropdown
                }
            } else {
                dropdown.style.display = 'none'; // Hide the dropdown
            }
        }
    });

    // Event listener for focus to handle empty input
    document.body.addEventListener('focus', (e) => {
        if (e.target.classList.contains('iafwzdesk-setup-fm-custom-input')) {
            const inputField = e.target;
            const dropdown = inputField.nextElementSibling;

            if (!dropdown || !dropdown.classList.contains('iafwzdesk-setup-fm-dropdownSuggestions')) return;

            if (inputField.value.trim() === '') {
                dropdown.innerHTML = ''; // Clear previous suggestions

                // Show all suggestions when input is empty
                availableFields.forEach(field => {
                    const fieldSlug = field.key;
                    const suggestion = document.createElement('div');
                    suggestion.className = 'iafwzdesk-setup-fm-suggestion-item';
                    suggestion.textContent = field.label;
                    suggestion.dataset.field = `\${${fieldSlug}}`;

                    // Add click event to suggestion
                    suggestion.addEventListener('click', () => {
                        inputField.value = suggestion.dataset.field; // Update the input value with the key
                        dropdown.style.display = 'none'; // Hide the dropdown
                    });

                    dropdown.appendChild(suggestion);
                });

                dropdown.style.display = 'block'; // Show the dropdown
            }
        }
    }, true);

    // Hide dropdown when clicking outside
    document.body.addEventListener('click', (e) => {
        document.querySelectorAll('.iafwzdesk-setup-fm-dropdownSuggestions').forEach((dropdown) => {
            if (!dropdown.previousElementSibling.contains(e.target) && !dropdown.contains(e.target)) {
                dropdown.style.display = 'none';
            }
        });
    });
});
