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


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

    // Create suggestion box if not exists
    if (suggestionBox.length === 0) {
        suggestionBox = jQuery('<div>', {
            id: suggestionBoxId,
            class: 'integrazo-wczo-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-wczo-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-wczo-custom-textarea').length) {
        jQuery('.integrazo-wczo-suggestion-box').hide();
    }
});
