let formFields = (typeof integrazoFCData !== 'undefined' && integrazoFCData.form_fields) 
    ? integrazoFCData.form_fields 
    : [];


jQuery(document).on('focus input', '.integrazo-wz-custom-textarea textarea', function () {
    const textarea = jQuery(this);
    const container = textarea.closest('.integrazo-wz-custom-textarea');
    const suggestionBoxId = 'integrazo-wz-custom-suggestions';
    let suggestionBox = container.find(`#${suggestionBoxId}`);

    // Create suggestion box if not exists
    if (suggestionBox.length === 0) {
        suggestionBox = jQuery('<div>', {
            id: suggestionBoxId,
            class: 'integrazo-wz-suggestion-box',
            css: {
                position: 'absolute',
                border: '1px solid #ccc',
                background: '#fff',
                zIndex: 999,
                maxHeight: '150px',
                overflowY: 'auto',
                overflowX: 'hidden',
                fontSize: '14px'
            }
        }).insertAfter(textarea);
    }

    // Adjust width same as textarea
    suggestionBox.css('width', textarea.outerWidth());

    // Always show all options
    suggestionBox.html('');
    formFields.forEach(field => {
        // Ensure field is object and has name & label
        if (typeof field === 'object' && field.name && field.label) {
            suggestionBox.append(
                jQuery('<div>', {
                    text: field.label,
                    class: 'integrazo-wz-suggestion-item',
                    css: {
                        padding: '6px 8px',
                        cursor: 'pointer',
                        borderBottom: '1px solid #eee'
                    }
                }).on('click', function () {
                    const currentText = textarea.val();
                    const cursorPos = textarea.prop('selectionStart');
                    const insertText = `\${${field.identifier}}`;

                    const newText = currentText.slice(0, cursorPos) + insertText + currentText.slice(cursorPos);
                    textarea.val(newText);

                    // Set cursor after inserted text
                    textarea[0].setSelectionRange(cursorPos + insertText.length, cursorPos + insertText.length);
                    textarea.focus();

                    // Hide suggestion after selection
                    suggestionBox.hide();
                })
            );
        }
    });

    suggestionBox.show(); // Always show on focus/input
});

// Hide suggestion box when clicking outside
jQuery(document).on('click', function (e) {
    if (!jQuery(e.target).closest('.integrazo-wz-custom-textarea').length) {
        jQuery('.integrazo-wz-suggestion-box').hide();
    }
});
