import React, { useState, useRef, useEffect } from 'react';
import { __ } from '@wordpress/i18n';
import Tooltip from './Tooltip';
import MultiSelect from './MultiSelect';
import IconPicker, { isImageValue } from './IconPicker';
import apiFetch from '@wordpress/api-fetch';

// Constant for "No Subscription Required" option
const ALL_SUBSCRIPTIONS_OPTION = { value: 'all', label: __('No Subscription Required', 'wpuf-pro') };

const AboutTabsSetup = ({ formData, setFormData, isEditing = false }) => {
    const [showDropdown, setShowDropdown] = useState(false);
    const [selectedContentType, setSelectedContentType] = useState(null);
    const [aboutTabsContent, setAboutTabsContent] = useState(formData.about_tabs_content || []);
    const [collapsedItems, setCollapsedItems] = useState(() => {
        // If editing, collapse all existing items by default
        if (isEditing && formData.about_tabs_content) {
            return formData.about_tabs_content.reduce((acc, item) => {
                acc[item.id] = true;
                return acc;
            }, {});
        }
        return {};
    });
    const [editingTitle, setEditingTitle] = useState(null);
    const [editTitleValue, setEditTitleValue] = useState('');
    const [draggedItem, setDraggedItem] = useState(null);
    const [dragOverItem, setDragOverItem] = useState(null);
    const [focusedItem, setFocusedItem] = useState(null);
    const [isSectionCollapsed, setIsSectionCollapsed] = useState(false); // Always start expanded
    const [subscriptionPacks, setSubscriptionPacks] = useState([]);
    const [isLoadingPacks, setIsLoadingPacks] = useState(false);
    const dropdownRef = useRef(null);
    const editTitleRef = useRef(null);

    // Close dropdown when clicking outside
    useEffect(() => {
        const handleClickOutside = (event) => {
            if (dropdownRef.current && !dropdownRef.current.contains(event.target)) {
                setShowDropdown(false);
            }
        };

        document.addEventListener('mousedown', handleClickOutside);
        return () => {
            document.removeEventListener('mousedown', handleClickOutside);
        };
    }, []);

    // Focus edit input when editing starts
    useEffect(() => {
        if (editingTitle !== null && editTitleRef.current) {
            editTitleRef.current.focus();
            editTitleRef.current.select();
        }
    }, [editingTitle]);

    // Load subscription packs from REST API
    useEffect(() => {
        let isMounted = true;
        async function fetchSubscriptionPacks() {
            setIsLoadingPacks(true);
            try {
                const data = await apiFetch({ path: '/wpuf/v1/wpuf_subscription' });
                if (!isMounted) return;

                // Transform response to options format
                if (data?.success && Array.isArray(data.subscriptions)) {
                    const packs = data.subscriptions
                        .filter(pack => pack.post_status === 'publish') // Only published subscriptions
                        .map(pack => ({
                            value: String(pack.ID),
                            label: pack.post_title || __('Unnamed Pack', 'wpuf-pro')
                        }));

                    // Add "No Subscription Required" option at the beginning
                    setSubscriptionPacks([
                        ALL_SUBSCRIPTIONS_OPTION,
                        ...packs
                    ]);
                } else {
                    // If no subscriptions or error, just show "No Subscription Required"
                    setSubscriptionPacks([ALL_SUBSCRIPTIONS_OPTION]);
                }
            } catch (e) {
                if (!isMounted) return;
                // Handle errors gracefully - permission denied, module not available, etc.
                // Just show "No Subscription Required" option
                setSubscriptionPacks([ALL_SUBSCRIPTIONS_OPTION]);
            } finally {
                if (isMounted) setIsLoadingPacks(false);
            }
        }
        fetchSubscriptionPacks();
        return () => {
            isMounted = false;
        };
    }, []);

    // Content type options
    const contentTypes = [
        { key: 'meta_field', label: __('Meta Field', 'wpuf-pro'), icon: '📋' },
        { key: 'section', label: __('Section', 'wpuf-pro'), icon: '📄' },
        { key: 'post_type', label: __('Post Type', 'wpuf-pro'), icon: '📝' },
        { key: 'comment', label: __('Comment', 'wpuf-pro'), icon: '💬' },
        { key: 'image_file', label: __('Image/File', 'wpuf-pro'), icon: '🖼️' }
    ];

    // Handle content type selection
    const handleContentTypeSelect = (contentType) => {
        setSelectedContentType(contentType);
        setShowDropdown(false);
        
        // Add new content item
        const newItem = {
            id: Date.now(),
            type: contentType.key,
            label: '',
            ...getDefaultFieldsForType(contentType.key)
        };
        
        const updatedContent = [...aboutTabsContent, newItem];
        setAboutTabsContent(updatedContent);
        updateFormData(updatedContent);
        
        // New items should be expanded when added (not collapsed)
        // So we don't add them to collapsedItems
        
        // Auto-scroll to the newly added content item
        setTimeout(() => {
            const newItemElement = document.querySelector(`[data-item-id="${newItem.id}"]`);
            if (newItemElement) {
                newItemElement.scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'center' 
                });
            }
        }, 100);
    };

    // Get default fields based on content type
    const getDefaultFieldsForType = (type) => {
        switch (type) {
            case 'meta_field':
                return {
                    meta_key: '',
                    field_icon: '',
                    profile_user_roles: ['all'],
                    viewer_roles: ['all'],
                    viewer_subscription_packs: ['all'],
                    viewer_access_logic: 'and',
                    field_view_type: 'hide',
                    custom_message: ''
                };
            case 'section':
                return {
                    field_icon: '',
                    profile_user_roles: ['all'],
                    viewer_roles: ['all']
                };
            case 'post_type':
                return {
                    post_type: '', // No default post type
                    count: 5,
                    profile_user_roles: ['all'],
                    viewer_roles: ['all']
                };
            case 'comment':
                return {
                    post_type: '', // No default post type
                    count: 5,
                    profile_user_roles: ['all'],
                    viewer_roles: ['all']
                };
            case 'image_file':
                return {
                    meta_key: '',
                    profile_user_roles: ['all'],
                    viewer_roles: ['all']
                };
            default:
                return {};
        }
    };

    // Update form data
    const updateFormData = (content) => {
        setFormData(prev => ({ ...prev, about_tabs_content: content }));
    };

    // Update content item
    const updateContentItem = (id, field, value) => {
        const updatedContent = aboutTabsContent.map(item => 
            item.id === id ? { ...item, [field]: value } : item
        );
        setAboutTabsContent(updatedContent);
        updateFormData(updatedContent);
    };

    // Remove content item
    const removeContentItem = (id) => {
        const updatedContent = aboutTabsContent.filter(item => item.id !== id);
        setAboutTabsContent(updatedContent);
        updateFormData(updatedContent);
    };

    // Toggle role selection
    const toggleRole = (itemId, roleType, role) => {
        const updatedContent = aboutTabsContent.map(item => {
            if (item.id === itemId) {
                const currentRoles = item[roleType] || [];
                const newRoles = currentRoles.includes(role)
                    ? currentRoles.filter(r => r !== role)
                    : [...currentRoles, role];
                return { ...item, [roleType]: newRoles };
            }
            return item;
        });
        setAboutTabsContent(updatedContent);
        updateFormData(updatedContent);
    };

    // Toggle collapse state
    const toggleCollapse = (itemId) => {
        setCollapsedItems(prev => ({
            ...prev,
            [itemId]: !prev[itemId]
        }));
    };

    // Start editing title
    const startEditTitle = (itemId, currentTitle) => {
        setEditingTitle(itemId);
        setEditTitleValue(currentTitle);
    };

    // Save edited title
    const saveEditTitle = () => {
        if (editingTitle !== null) {
            updateContentItem(editingTitle, 'label', editTitleValue);
            setEditingTitle(null);
            setEditTitleValue('');
        }
    };

    // Cancel editing title
    const cancelEditTitle = () => {
        setEditingTitle(null);
        setEditTitleValue('');
    };

    // Handle title edit key down
    const handleTitleEditKeyDown = (e) => {
        if (e.key === 'Enter') {
            e.preventDefault();
            saveEditTitle();
        } else if (e.key === 'Escape') {
            cancelEditTitle();
        }
    };

    // Drag and drop handlers
    const handleDragStart = (e, index) => {
        setDraggedItem(index);
        e.dataTransfer.effectAllowed = 'move';
    };

    const handleDragEnd = () => {
        setDraggedItem(null);
        setDragOverItem(null);
    };

    const handleDragOver = (e) => {
        e.preventDefault();
        e.dataTransfer.dropEffect = 'move';
    };

    const handleDragEnter = (e, index) => {
        if (draggedItem !== index) {
            setDragOverItem(index);
        }
    };

    const handleDragLeave = (e) => {
        if (e.target === e.currentTarget) {
            setDragOverItem(null);
        }
    };

    const handleDrop = (e, dropIndex) => {
        e.preventDefault();
        e.stopPropagation();
        
        if (draggedItem !== null && draggedItem !== dropIndex) {
            const newContent = [...aboutTabsContent];
            const draggedContentItem = newContent[draggedItem];
            
            // Remove from old position and insert at new position
            newContent.splice(draggedItem, 1);
            newContent.splice(dropIndex, 0, draggedContentItem);
            
            setAboutTabsContent(newContent);
            updateFormData(newContent);
        }
        
        setDraggedItem(null);
        setDragOverItem(null);
    };

    // Get available user roles from wpuf_ud global object
    const getUserRoles = () => {
        // Get dynamic roles from WordPress
        const dynamicRoles = (typeof wpuf_ud !== 'undefined' && wpuf_ud.roles) ? wpuf_ud.roles : {};
        
        // Return roles with "All" option
        return {
            all: __('All', 'wpuf-pro'),
            ...dynamicRoles
        };
    };

    // Get available meta fields
    const getMetaFields = () => {
        if (typeof wpuf_ud !== 'undefined' && wpuf_ud.user_meta_fields) {
            return wpuf_ud.user_meta_fields;
        }
        return {};
    };

    // Get available post types
    const getPostTypes = () => {
        // Get dynamic post types from WordPress
        return (typeof wpuf_ud !== 'undefined' && wpuf_ud.post_types) ? wpuf_ud.post_types : {};
    };

    // Render form fields based on content type
    const renderContentForm = (item) => {
        const userRoles = getUserRoles();
        const metaFields = getMetaFields();
        const postTypes = getPostTypes();

        switch (item.type) {
            case 'meta_field':
                return (
                    <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                        <label className="wpuf-flex-shrink-0 wpuf-w-40">
                            <span style={{
                                
                                fontWeight: 500,
                                fontSize: '14px',
                                lineHeight: '20px',
                                letterSpacing: '0%',
                                color: '#334155',
                                whiteSpace: 'nowrap'
                            }}>{__('Label', 'wpuf-pro')}</span>
                        </label>
                        <input
                            type="text"
                            className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                            value={item.label || ''}
                            onChange={(e) => updateContentItem(item.id, 'label', e.target.value)}
                            placeholder={__('Enter label', 'wpuf-pro')}
                        />
                    </div>
                );

            case 'section':
                return (
                    <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                        <label className="wpuf-flex-shrink-0 wpuf-w-40">
                            <span style={{
                                
                                fontWeight: 500,
                                fontSize: '14px',
                                lineHeight: '20px',
                                letterSpacing: '0%',
                                color: '#334155',
                                whiteSpace: 'nowrap'
                            }}>{__('Label', 'wpuf-pro')}</span>
                        </label>
                        <input
                            type="text"
                            className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                            value={item.label || ''}
                            onChange={(e) => updateContentItem(item.id, 'label', e.target.value)}
                            placeholder={__('Enter section label', 'wpuf-pro')}
                        />
                    </div>
                );

            case 'post_type':
                return (
                    <div className="wpuf-space-y-4">
                        {/* Label */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Label', 'wpuf-pro')}</span>
                            </label>
                            <input
                                type="text"
                                className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                                value={item.label || ''}
                                onChange={(e) => updateContentItem(item.id, 'label', e.target.value)}
                                placeholder={__('Enter label', 'wpuf-pro')}
                            />
                        </div>

                        {/* Post Type */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Post Type', 'wpuf-pro')}</span>
                            </label>
                            <select
                                className="wpuf-flex-1 wpuf-text-gray-700 wpuf-font-normal focus:wpuf-ring-transparent wpuf-border"
                                style={{
                                    maxWidth: '793px',
                                    width: '100%',
                                    height: '42px',
                                    borderRadius: '6px',
                                    borderWidth: '1px',
                                    paddingTop: '9px',
                                    paddingRight: '37px',
                                    paddingBottom: '9px',
                                    paddingLeft: '13px',
                                    backgroundColor: '#FFFFFF',
                                    borderColor: '#CBD5E1',
                                    borderStyle: 'solid',
                                    opacity: 1,
                                    boxSizing: 'border-box',
                                    fontSize: '16px',
                                    lineHeight: '1',
                                    display: 'flex',
                                    alignItems: 'center',
                                    backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'%23374151\' viewBox=\'0 0 24 24\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")',
                                    backgroundRepeat: 'no-repeat',
                                    backgroundPosition: 'right 13px center',
                                    backgroundSize: '16px',
                                    appearance: 'none',
                                    WebkitAppearance: 'none',
                                    MozAppearance: 'none'
                                }}
                                value={item.post_type || ''}
                                onChange={(e) => updateContentItem(item.id, 'post_type', e.target.value)}
                            >
                                {Object.entries(postTypes).map(([key, label]) => (
                                    <option key={key} value={key}>{label}</option>
                                ))}
                            </select>
                        </div>

                        {/* Post Count */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Post Count', 'wpuf-pro')}</span>
                            </label>
                            <input
                                type="number"
                                className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                                value={item.count || 5}
                                onChange={(e) => updateContentItem(item.id, 'count', parseInt(e.target.value))}
                                min="1"
                            />
                        </div>
                    </div>
                );

            case 'comment':
                return (
                    <div className="wpuf-space-y-4">
                        {/* Label */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Label', 'wpuf-pro')}</span>
                            </label>
                            <input
                                type="text"
                                className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                                value={item.label || ''}
                                onChange={(e) => updateContentItem(item.id, 'label', e.target.value)}
                                placeholder={__('Enter label', 'wpuf-pro')}
                            />
                        </div>

                        {/* Post Type Comment */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Post Type Comment', 'wpuf-pro')}</span>
                            </label>
                            <select
                                className="wpuf-flex-1 wpuf-text-gray-700 wpuf-font-normal focus:wpuf-ring-transparent wpuf-border"
                                style={{
                                    maxWidth: '793px',
                                    width: '100%',
                                    height: '42px',
                                    borderRadius: '6px',
                                    borderWidth: '1px',
                                    paddingTop: '9px',
                                    paddingRight: '37px',
                                    paddingBottom: '9px',
                                    paddingLeft: '13px',
                                    backgroundColor: '#FFFFFF',
                                    borderColor: '#CBD5E1',
                                    borderStyle: 'solid',
                                    opacity: 1,
                                    boxSizing: 'border-box',
                                    fontSize: '16px',
                                    lineHeight: '1',
                                    display: 'flex',
                                    alignItems: 'center',
                                    backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'%23374151\' viewBox=\'0 0 24 24\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")',
                                    backgroundRepeat: 'no-repeat',
                                    backgroundPosition: 'right 13px center',
                                    backgroundSize: '16px',
                                    appearance: 'none',
                                    WebkitAppearance: 'none',
                                    MozAppearance: 'none'
                                }}
                                value={item.post_type || ''}
                                onChange={(e) => updateContentItem(item.id, 'post_type', e.target.value)}
                            >
                                {Object.entries(postTypes).map(([key, label]) => (
                                    <option key={key} value={key}>{label}</option>
                                ))}
                            </select>
                        </div>

                        {/* Comment Count */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Comment Count', 'wpuf-pro')}</span>
                            </label>
                            <input
                                type="number"
                                className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                                value={item.count || 5}
                                onChange={(e) => updateContentItem(item.id, 'count', parseInt(e.target.value))}
                                min="1"
                            />
                        </div>
                    </div>
                );

            case 'image_file':
                return (
                    <div className="wpuf-space-y-4">
                        {/* Label */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Label', 'wpuf-pro')}</span>
                            </label>
                            <input
                                type="text"
                                className="wpuf-flex-1 !wpuf-m-0 !wpuf-leading-none !wpuf-py-[10px] !wpuf-px-[14px] wpuf-text-gray-700 !wpuf-shadow-sm placeholder:wpuf-text-gray-400 wpuf-border !wpuf-border-gray-300 !wpuf-rounded-[6px] focus:!wpuf-ring-transparent"
                                value={item.label || ''}
                                onChange={(e) => updateContentItem(item.id, 'label', e.target.value)}
                                placeholder={__('Enter label', 'wpuf-pro')}
                            />
                        </div>

                        {/* Meta Key for File */}
                        <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                            <label className="wpuf-flex-shrink-0 wpuf-w-40">
                                <span style={{
                                    
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Meta Key', 'wpuf-pro')}</span>
                            </label>
                            <select
                                className="wpuf-flex-1 wpuf-text-gray-700 wpuf-font-normal focus:wpuf-ring-transparent wpuf-border wpuf-min-w-0"
                                style={{
                                    maxWidth: '793px',
                                    width: '100%',
                                    height: '42px',
                                    borderRadius: '6px',
                                    borderWidth: '1px',
                                    paddingTop: '9px',
                                    paddingRight: '37px',
                                    paddingBottom: '9px',
                                    paddingLeft: '13px',
                                    backgroundColor: '#FFFFFF',
                                    borderColor: '#CBD5E1',
                                    borderStyle: 'solid',
                                    opacity: 1,
                                    boxSizing: 'border-box',
                                    fontSize: '16px',
                                    lineHeight: '1',
                                    display: 'flex',
                                    alignItems: 'center',
                                    backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'%23374151\' viewBox=\'0 0 24 24\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")',
                                    backgroundRepeat: 'no-repeat',
                                    backgroundPosition: 'right 13px center',
                                    backgroundSize: '16px',
                                    appearance: 'none',
                                    WebkitAppearance: 'none',
                                    MozAppearance: 'none'
                                }}
                                value={item.meta_key || ''}
                                onChange={(e) => updateContentItem(item.id, 'meta_key', e.target.value)}
                            >
                                <option value="">{__('- Select -', 'wpuf-pro')}</option>
                                <optgroup label={__('Profile Fields', 'wpuf-pro')}>
                                    <option value="user_login">{__('Username', 'wpuf-pro')}</option>
                                    <option value="first_name">{__('First Name', 'wpuf-pro')}</option>
                                    <option value="last_name">{__('Last Name', 'wpuf-pro')}</option>
                                    <option value="display_name">{__('Display Name', 'wpuf-pro')}</option>
                                    <option value="nickname">{__('Nickname', 'wpuf-pro')}</option>
                                    <option value="user_email">{__('E-mail', 'wpuf-pro')}</option>
                                    <option value="user_url">{__('Website', 'wpuf-pro')}</option>
                                    <option value="description">{__('Biographical Info', 'wpuf-pro')}</option>
                                </optgroup>
                                <optgroup label={__('Meta Keys', 'wpuf-pro')}>
                                    {Object.entries(metaFields).map(([key, label]) => (
                                        <option key={key} value={key}>{key}</option>
                                    ))}
                                </optgroup>
                            </select>
                        </div>
                    </div>
                );

            default:
                return null;
        }
    };

    // Render role dropdowns
    const renderRoleDropdowns = (item) => {
        const userRoles = getUserRoles();

        // Prepare options for viewer roles (include guest and logged_in)
        const viewerRoleOptions = {
            ...userRoles,
            guest: __('Guest', 'wpuf-pro'),
            logged_in: __('Logged In Users', 'wpuf-pro')
        };
        
        return (
            <div className="wpuf-space-y-4 wpuf-mt-4">
                {/* Profile User Role */}
                <div className="wpuf-flex wpuf-items-start wpuf-gap-2">
                    <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40 wpuf-pt-[10px]">
                        <span style={{
                            
                            fontWeight: 500,
                            fontSize: '14px',
                            lineHeight: '20px',
                            letterSpacing: '0%',
                            color: '#334155',
                            whiteSpace: 'nowrap'
                        }}>{__('Profile User Role', 'wpuf-pro')}</span>
                        <Tooltip className="wpuf-ml-2" content={__('Show this field if the currently viewed user profile has one of these roles.', 'wpuf-pro')}>
                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                        </Tooltip>
                    </label>
                    <div className="wpuf-flex-1">
                        <MultiSelect
                            options={userRoles}
                            value={item.profile_user_roles || []}
                            onChange={(roles) => updateContentItem(item.id, 'profile_user_roles', roles)}
                            placeholder={__('Select roles...', 'wpuf-pro')}
                            sortable={false}
                        />
                    </div>
                </div>

                {/* Viewer Role */}
                <div className="wpuf-flex wpuf-items-start wpuf-gap-2">
                    <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40 wpuf-pt-[10px]">
                        <span style={{
                            
                            fontWeight: 500,
                            fontSize: '14px',
                            lineHeight: '20px',
                            letterSpacing: '0%',
                            color: '#334155',
                            whiteSpace: 'nowrap'
                        }}>{__('Viewer Role', 'wpuf-pro')}</span>
                        <Tooltip className="wpuf-ml-2" content={__('Show this field if the viewer (current logged in user or guest) has one of these roles.', 'wpuf-pro')}>
                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                        </Tooltip>
                    </label>
                    <div className="wpuf-flex-1">
                        <MultiSelect
                            options={viewerRoleOptions}
                            value={item.viewer_roles || []}
                            onChange={(roles) => updateContentItem(item.id, 'viewer_roles', roles)}
                            placeholder={__('Select roles...', 'wpuf-pro')}
                            sortable={false}
                            exclusiveOptions={['all', 'logged_in']}
                        />
                        <p className="wpuf-text-xs wpuf-text-gray-500 wpuf-mt-1">
                            {__('Show this field only to viewers with these roles. Include "Guest" for non-logged-in users, or "Logged In Users" for any authenticated user.', 'wpuf-pro')}
                        </p>
                    </div>
                </div>

                {/* Viewer Subscription Pack - Only for meta_field type */}
                {item.type === 'meta_field' && (
                    <div className="wpuf-flex wpuf-items-start wpuf-gap-2">
                        <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40 wpuf-pt-[10px]">
                            <span style={{
                                fontWeight: 500,
                                fontSize: '14px',
                                lineHeight: '20px',
                                letterSpacing: '0%',
                                color: '#334155',
                                whiteSpace: 'nowrap'
                            }}>{__('Viewer Subs Pack', 'wpuf-pro')}</span>
                            <Tooltip className="wpuf-ml-2" content={__('Show this field only to viewers with these subscription packs. Requires logged-in users.', 'wpuf-pro')}>
                                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                            </Tooltip>
                        </label>
                        <div className="wpuf-flex-1">
                            {isLoadingPacks ? (
                                <div style={{ display: 'flex', alignItems: 'center', gap: '8px', padding: '8px 0' }}>
                                    <span>{__('Loading subscription packs…', 'wpuf-pro')}</span>
                                </div>
                            ) : (
                                <MultiSelect
                                    options={subscriptionPacks.reduce((acc, pack) => {
                                        acc[pack.value] = pack.label;
                                        return acc;
                                    }, {})}
                                    value={item.viewer_subscription_packs || ['all']}
                                    onChange={(packs) => updateContentItem(item.id, 'viewer_subscription_packs', packs)}
                                    placeholder={__('No Subscription Required', 'wpuf-pro')}
                                    sortable={false}
                                    exclusiveOptions={['all']}
                                />
                            )}
                            <p className="wpuf-text-xs wpuf-text-gray-500 wpuf-mt-1">
                                {__('Show this field only to viewers with these subscription packs. Requires logged-in users.', 'wpuf-pro')}
                            </p>
                        </div>
                    </div>
                )}

                {/* Access Logic - Only for meta_field type when restrictions are set */}
                {item.type === 'meta_field' && (!(item.viewer_roles || []).includes('all') || !(item.viewer_subscription_packs || ['all']).includes('all')) && (
                    <div className="wpuf-flex wpuf-items-start wpuf-gap-2">
                        <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40 wpuf-pt-[10px]">
                            <span style={{
                                fontWeight: 500,
                                fontSize: '14px',
                                lineHeight: '20px',
                                letterSpacing: '0%',
                                color: '#334155',
                                whiteSpace: 'nowrap'
                            }}>{__('Access Logic', 'wpuf-pro')}</span>
                            <Tooltip className="wpuf-ml-2" content={__('How to combine role and subscription restrictions.', 'wpuf-pro')}>
                                <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                            </Tooltip>
                        </label>
                        <div className="wpuf-flex-1">
                            <select
                                style={{
                                    width: '100%',
                                    padding: '8px 40px 8px 12px',
                                    border: '1px solid #D1D5DB',
                                    borderRadius: '6px',
                                    fontSize: '14px',
                                    backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'%23374151\' viewBox=\'0 0 24 24\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")',
                                    backgroundRepeat: 'no-repeat',
                                    backgroundPosition: 'right 8px center',
                                    backgroundSize: '16px',
                                    appearance: 'none'
                                }}
                                value={item.viewer_access_logic || 'and'}
                                onChange={(e) => updateContentItem(item.id, 'viewer_access_logic', e.target.value)}
                            >
                                <option value="and">{__('Require Both', 'wpuf-pro')}</option>
                                <option value="or">{__('Require Either', 'wpuf-pro')}</option>
                            </select>
                            <p className="wpuf-text-xs wpuf-text-gray-500 wpuf-mt-1">
                                {__('How to combine role and subscription restrictions. "Require Both" means viewer must have both a matching role AND subscription. "Require Either" means viewer needs either a matching role OR subscription. Note: Subscription checks are skipped when "Guest" or "Logged In Users" is included in viewer roles.', 'wpuf-pro')}
                            </p>
                        </div>
                    </div>
                )}

                {/* Restriction Behavior - Only for meta_field type when restrictions are set */}
                {item.type === 'meta_field' && (!(item.viewer_roles || []).includes('all') || !(item.viewer_subscription_packs || ['all']).includes('all')) && (
                    <>
                        <div className="wpuf-flex wpuf-items-start wpuf-gap-2">
                            <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40 wpuf-pt-[10px]">
                                <span style={{
                                    fontWeight: 500,
                                    fontSize: '14px',
                                    lineHeight: '20px',
                                    letterSpacing: '0%',
                                    color: '#334155',
                                    whiteSpace: 'nowrap'
                                }}>{__('Restriction Behavior', 'wpuf-pro')}</span>
                                <Tooltip className="wpuf-ml-2" content={__('What to show when viewer does not have required role or subscription.', 'wpuf-pro')}>
                                    <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                                </Tooltip>
                            </label>
                            <div className="wpuf-flex-1">
                                <select
                                    style={{
                                        width: '100%',
                                        padding: '8px 40px 8px 12px',
                                        border: '1px solid #D1D5DB',
                                        borderRadius: '6px',
                                        fontSize: '14px',
                                        backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'%23374151\' viewBox=\'0 0 24 24\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")',
                                        backgroundRepeat: 'no-repeat',
                                        backgroundPosition: 'right 8px center',
                                        backgroundSize: '16px',
                                        appearance: 'none'
                                    }}
                                    value={item.field_view_type || 'hide'}
                                    onChange={(e) => updateContentItem(item.id, 'field_view_type', e.target.value)}
                                >
                                    <option value="hide">{__('Hide completely', 'wpuf-pro')}</option>
                                    <option value="show_custom_message">{__('Show custom message', 'wpuf-pro')}</option>
                                </select>
                                <p className="wpuf-text-xs wpuf-text-gray-500 wpuf-mt-1">
                                    {__('What to show when viewer does not have required role or subscription.', 'wpuf-pro')}
                                </p>
                            </div>
                        </div>

                        {/* Custom Message - Only shown when show_custom_message is selected */}
                        {item.field_view_type === 'show_custom_message' && (
                            <div className="wpuf-flex wpuf-items-start wpuf-gap-2">
                                <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40 wpuf-pt-[10px]">
                                    <span style={{
                                        fontWeight: 500,
                                        fontSize: '14px',
                                        lineHeight: '20px',
                                        letterSpacing: '0%',
                                        color: '#334155',
                                        whiteSpace: 'nowrap'
                                    }}>{__('Custom Message', 'wpuf-pro')}</span>
                                    <Tooltip className="wpuf-ml-2" content={__('Message to display when viewer does not have required access. Use {login}, {register}, and {subscriptions} for dynamic content.', 'wpuf-pro')}>
                                        <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                                    </Tooltip>
                                </label>
                                <div className="wpuf-flex-1">
                                    <textarea
                                        style={{
                                            width: '100%',
                                            padding: '8px 12px',
                                            border: '1px solid #D1D5DB',
                                            borderRadius: '6px',
                                            fontSize: '14px',
                                            minHeight: '80px',
                                            resize: 'vertical'
                                        }}
                                        value={item.custom_message || ''}
                                        onChange={(e) => {
                                            const limitedValue = e.target.value.length > 500 ? e.target.value.substring(0, 500) : e.target.value;
                                            updateContentItem(item.id, 'custom_message', limitedValue);
                                        }}
                                        placeholder={__('Enter custom message to display. You can use {login}, {register}, and {subscriptions} for dynamic content.', 'wpuf-pro')}
                                        rows={4}
                                    />
                                    <p className="wpuf-text-xs wpuf-text-gray-500 wpuf-mt-1">
                                        {__('Message to display when viewer does not have required role. Use {login} and {register} for links, and {subscriptions} will show the selected subscription pack names (comma-separated).', 'wpuf-pro')}
                                        <span style={{
                                            display: 'block',
                                            marginTop: '4px',
                                            color: ((item.custom_message || '').length) >= 500 ? '#d63638' : '#646970',
                                            fontSize: '12px'
                                        }}>
                                            {(item.custom_message || '').length}/500 {__('characters', 'wpuf-pro')}
                                        </span>
                                    </p>
                                </div>
                            </div>
                        )}
                    </>
                )}
            </div>
        );
    };

    return (
        <div className="wpuf-mt-8">
            <div className="wpuf-flex wpuf-items-center wpuf-justify-between wpuf-mb-2">
                <h1
                    style={{
                        
                        fontWeight: 400,
                        fontSize: '18px',
                        lineHeight: '28px',
                        letterSpacing: '0%',
                        color: '#000000'
                    }}
                >
                    {__('Configure About Tab', 'wpuf-pro')}
                </h1>
                <button
                    type="button"
                    className="wpuf-p-2 wpuf-text-gray-400 hover:wpuf-text-gray-600"
                    onClick={() => setIsSectionCollapsed(!isSectionCollapsed)}
                >
                    <svg 
                        className={`wpuf-w-5 wpuf-h-5 wpuf-transition-transform ${isSectionCollapsed ? 'wpuf-rotate-180' : ''}`}
                        fill="none" 
                        stroke="currentColor" 
                        viewBox="0 0 24 24"
                    >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 15l7-7 7 7" />
                    </svg>
                </button>
            </div>
            
            {!isSectionCollapsed && (
                <div>
                    <p className="wpuf-mb-6"
                        style={{
                            
                            fontWeight: 400,
                            fontSize: '14px',
                            lineHeight: '20px',
                            letterSpacing: '0%',
                            color: '#D1D5DB!important'
                        }}
                    >
                        {__('Define content for About tab by selecting fields, post types, or files. Map custom meta—including WPUF fields—to showcase user data such as skills, achievements, media, and other key information.', 'wpuf-pro')}
                    </p>
            
            {/* Content Items - Appear above Add Content button */}
            {aboutTabsContent.length > 0 && (
                <div className="wpuf-space-y-2 wpuf-mb-6">
                    {aboutTabsContent.map((item, index) => {
                        const isCollapsed = collapsedItems[item.id];
                        const isDragging = draggedItem === index;
                        const isDragOver = dragOverItem === index;
                        
                        return (
                            <div 
                                key={item.id} 
                                data-item-id={item.id}
                                className={`wpuf-cursor-move wpuf-transition-all wpuf-group ${
                                    isDragging ? 'wpuf-opacity-50 wpuf-scale-[0.98]' : ''
                                } ${
                                    isDragOver ? 'wpuf-bg-emerald-50' : ''
                                }`}
                                style={{
                                    width: '793px',
                                    minHeight: item.type === 'section' && isCollapsed ? 'auto' : '56px',
                                    borderRadius: '6px',
                                    borderWidth: item.type === 'section' && isCollapsed ? '0px' : '1px',
                                    borderStyle: 'solid',
                                    borderColor: (!isCollapsed && focusedItem === item.id) ? '#059669' : (isDragOver ? '#059669' : '#E5E7EB'),
                                    backgroundColor: item.type === 'section' && isCollapsed ? 'transparent' : (isDragOver ? '#ECFDF5' : '#FFFFFF'),
                                    opacity: 1,
                                    paddingTop: item.type === 'section' && isCollapsed ? '0px' : (isCollapsed ? '10px' : '0px'),
                                    paddingBottom: item.type === 'section' && isCollapsed ? '0px' : (isCollapsed ? '10px' : '0px'),
                                    paddingLeft: item.type === 'section' && isCollapsed ? '0px' : (isCollapsed ? '20px' : '0px'),
                                    paddingRight: item.type === 'section' && isCollapsed ? '0px' : (isCollapsed ? '20px' : '0px'),
                                    transition: 'border-color 0.2s ease'
                                }}
                                draggable={!editingTitle}
                                onDragStart={(e) => handleDragStart(e, index)}
                                onDragEnd={handleDragEnd}
                                onDragOver={handleDragOver}
                                onDragEnter={(e) => handleDragEnter(e, index)}
                                onDragLeave={handleDragLeave}
                                onDrop={(e) => handleDrop(e, index)}
                                onFocus={() => setFocusedItem(item.id)}
                                onBlur={(e) => {
                                    // Only blur if focus is moving outside the card
                                    if (!e.currentTarget.contains(e.relatedTarget)) {
                                        setFocusedItem(null);
                                    }
                                }}
                            >
                                {/* Header with icon, title and actions */}
                                <div className={`wpuf-flex wpuf-items-center wpuf-justify-between ${isCollapsed ? '' : 'wpuf-px-5 wpuf-py-2'} ${!isCollapsed ? 'wpuf-border-b-[0.5px] wpuf-border-gray-200' : ''}`}>
                                    <div className="wpuf-flex wpuf-items-center wpuf-gap-3">
                                        {/* Drag Handle */}
                                        <svg className="wpuf-w-5 wpuf-h-5 wpuf-mr-2 wpuf-cursor-move wpuf-text-gray-400" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                            <path d="M3.125 5.625H16.875M3.125 10H16.875M3.125 14.375H16.875" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                        </svg>
                                        
                                        {/* Editable Title */}
                                        {editingTitle === item.id ? (
                                            <input
                                                ref={editTitleRef}
                                                type="text"
                                                className="wpuf-text-base wpuf-font-medium wpuf-text-gray-900 wpuf-border wpuf-border-emerald-500 wpuf-rounded wpuf-px-2 wpuf-py-1 wpuf-bg-white wpuf-outline-none"
                                                value={editTitleValue}
                                                onChange={(e) => setEditTitleValue(e.target.value)}
                                                onKeyDown={handleTitleEditKeyDown}
                                                onBlur={saveEditTitle}
                                                onClick={(e) => e.stopPropagation()}
                                            />
                                        ) : (
                                            <span 
                                                className={item.type === 'section' ? 'wpuf-cursor-pointer' : 'wpuf-cursor-pointer'}
                                                style={item.type === 'section' ? {
                                                    
                                                    fontWeight: 400,
                                                    fontSize: '20px',
                                                    lineHeight: '36px',
                                                    letterSpacing: '0%',
                                                    color: '#000000'
                                                } : {
                                                    
                                                    fontWeight: 400,
                                                    fontSize: '16px',
                                                    lineHeight: '24px',
                                                    letterSpacing: '0%',
                                                    color: '#374151'
                                                }}
                                                onClick={() => startEditTitle(item.id, item.label || '')}
                                            >
                                                {item.field_icon && (
                                                    isImageValue(item.field_icon)
                                                        ? <img src={item.field_icon} alt="" className="wpuf-field-icon wpuf-field-icon-img" style={{ width: '14px', height: '14px' }} />
                                                        : <i className={`${item.field_icon} wpuf-field-icon`} style={{ fontSize: '14px', color: '#374151', marginRight: '6px' }}></i>
                                                )}
                                                {item.type === 'meta_field' && (
                                                    <>
                                                        Meta: <span style={{
                                                            
                                                            fontWeight: 500,
                                                            fontSize: '16px',
                                                            lineHeight: '24px',
                                                            letterSpacing: '0%',
                                                            color: '#111827'
                                                        }}>{item.label || ''}</span>
                                                    </>
                                                )}
                                                {item.type === 'section' && (item.label ? `Section: ${item.label}` : 'Section:')}
                                                {item.type === 'post_type' && (
                                                    <>
                                                        Post Type: <span style={{
                                                            
                                                            fontWeight: 500,
                                                            fontSize: '16px',
                                                            lineHeight: '24px',
                                                            letterSpacing: '0%',
                                                            color: '#111827'
                                                        }}>{item.label || ''}</span>
                                                    </>
                                                )}
                                                {item.type === 'comment' && (
                                                    <>
                                                        Comment: <span style={{
                                                            
                                                            fontWeight: 500,
                                                            fontSize: '16px',
                                                            lineHeight: '24px',
                                                            letterSpacing: '0%',
                                                            color: '#111827'
                                                        }}>{item.label || ''}</span>
                                                    </>
                                                )}
                                                {item.type === 'image_file' && (
                                                    <>
                                                        Image/File: <span style={{
                                                            
                                                            fontWeight: 500,
                                                            fontSize: '16px',
                                                            lineHeight: '24px',
                                                            letterSpacing: '0%',
                                                            color: '#111827'
                                                        }}>{item.label || ''}</span>
                                                    </>
                                                )}
                                            </span>
                                        )}
                                    </div>
                                    <div className="wpuf-flex wpuf-items-center">
                                        <button
                                            type="button"
                                            className="wpuf-text-gray-600 hover:wpuf-text-red-600 wpuf-opacity-0 group-hover:wpuf-opacity-100 wpuf-transition-opacity"
                                            onClick={() => removeContentItem(item.id)}
                                        >
                                            <svg width="16" height="18" viewBox="0 0 16 18" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M10.2837 6.5L9.99519 14M6.00481 14L5.71635 6.5M14.023 3.82547C14.308 3.86851 14.592 3.91456 14.875 3.96358M14.023 3.82547L13.1332 15.3938C13.058 16.3707 12.2434 17.125 11.2637 17.125H4.73631C3.75655 17.125 2.94198 16.3707 2.86683 15.3938L1.97696 3.82547M14.023 3.82547C13.0677 3.6812 12.1013 3.57071 11.125 3.49527M1.125 3.96358C1.40798 3.91456 1.69198 3.86851 1.97696 3.82547M1.97696 3.82547C2.93231 3.6812 3.89874 3.57071 4.875 3.49527M11.125 3.49527V2.73182C11.125 1.74902 10.3661 0.928526 9.38382 0.897103C8.92435 0.882405 8.46304 0.875 8 0.875C7.53696 0.875 7.07565 0.882405 6.61618 0.897103C5.63388 0.928526 4.875 1.74902 4.875 2.73182V3.49527M11.125 3.49527C10.0938 3.41558 9.05164 3.375 8 3.375C6.94836 3.375 5.9062 3.41558 4.875 3.49527" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        </button>
                                        <button
                                            type="button"
                                            className="wpuf-p-2 wpuf-text-gray-400 hover:wpuf-text-gray-600"
                                            onClick={() => toggleCollapse(item.id)}
                                        >
                                            <svg 
                                                className={`wpuf-w-5 wpuf-h-5 wpuf-transition-transform ${isCollapsed ? 'wpuf-rotate-180' : ''}`} 
                                                fill="none" 
                                                stroke={(!isCollapsed && focusedItem === item.id) ? '#059669' : 'currentColor'}
                                                strokeWidth={(!isCollapsed && focusedItem === item.id) ? '1.5' : '2'}
                                                viewBox="0 0 24 24"
                                                style={{ transition: 'stroke 0.2s ease' }}
                                            >
                                                <path strokeLinecap="round" strokeLinejoin="round" d="M5 15l7-7 7 7" />
                                            </svg>
                                        </button>
                                    </div>
                                </div>
                                
                                {/* Content Form - Collapsible */}
                                {!isCollapsed && (
                                    <div className="wpuf-p-4">
                                        {/* Content Form Fields */}
                                        {renderContentForm(item)}
                                        
                                        {/* Select Meta Key Section for Meta Fields */}
                                        {item.type === 'meta_field' && (
                                            <div className="wpuf-mb-4 wpuf-mt-4">
                                                <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                                                    <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40">
                                                        <span style={{

                                                            fontWeight: 500,
                                                            fontSize: '14px',
                                                            lineHeight: '20px',
                                                            letterSpacing: '0%',
                                                            color: '#334155',
                                                            whiteSpace: 'nowrap'
                                                        }}>{__('Select Meta Key', 'wpuf-pro')}</span>
                                                        <Tooltip className="wpuf-ml-2" content={__('Choose a meta field to display in the user profile.', 'wpuf-pro')}>
                                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                                                        </Tooltip>
                                                    </label>

                                                    <select 
                                                        className="wpuf-flex-1 wpuf-text-gray-700 wpuf-font-normal focus:wpuf-ring-transparent wpuf-border"
                                                        style={{
                                                            maxWidth: '793px',
                                                            width: '100%',
                                                            height: '42px',
                                                            borderRadius: '6px',
                                                            borderWidth: '1px',
                                                            paddingTop: '9px',
                                                            paddingRight: '37px',
                                                            paddingBottom: '9px',
                                                            paddingLeft: '13px',
                                                            backgroundColor: '#FFFFFF',
                                                            borderColor: '#CBD5E1',
                                                            borderStyle: 'solid',
                                                            opacity: 1,
                                                            boxSizing: 'border-box',
                                                            fontSize: '16px',
                                                            lineHeight: '1',
                                                            display: 'flex',
                                                            alignItems: 'center',
                                                            backgroundImage: 'url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' stroke=\'%23374151\' viewBox=\'0 0 24 24\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")',
                                                            backgroundRepeat: 'no-repeat',
                                                            backgroundPosition: 'right 13px center',
                                                            backgroundSize: '16px',
                                                            appearance: 'none',
                                                            WebkitAppearance: 'none',
                                                            MozAppearance: 'none'
                                                        }}
                                                        value={item.meta_key || ''}
                                                        onChange={(e) => updateContentItem(item.id, 'meta_key', e.target.value)}
                                                    >
                                                        <option value="">{__('Select', 'wpuf-pro')}</option>
                                                        <optgroup label={__('Profile Fields', 'wpuf-pro')}>
                                                            <option value="user_login">{__('Username', 'wpuf-pro')}</option>
                                                            <option value="first_name">{__('First Name', 'wpuf-pro')}</option>
                                                            <option value="last_name">{__('Last Name', 'wpuf-pro')}</option>
                                                            <option value="display_name">{__('Display Name', 'wpuf-pro')}</option>
                                                            <option value="nickname">{__('Nickname', 'wpuf-pro')}</option>
                                                            <option value="user_email">{__('E-mail', 'wpuf-pro')}</option>
                                                            <option value="user_url">{__('Website', 'wpuf-pro')}</option>
                                                            <option value="description">{__('Biographical Info', 'wpuf-pro')}</option>
                                                        </optgroup>
                                                        <optgroup label={__('Meta Keys', 'wpuf-pro')}>
                                                            {Object.entries(getMetaFields()).map(([key, label]) => (
                                                                <option key={key} value={key}>{key}</option>
                                                            ))}
                                                        </optgroup>
                                                    </select>
                                                </div>
                                            </div>
                                        )}

                                        {/* Icon Picker for meta_field and section */}
                                        {(item.type === 'meta_field' || item.type === 'section') && (
                                            <div className="wpuf-mb-4 wpuf-mt-4">
                                                <div className="wpuf-flex wpuf-items-center wpuf-gap-2">
                                                    <label className="wpuf-flex wpuf-flex-shrink-0 wpuf-items-center wpuf-w-40">
                                                        <span style={{
                                                            fontWeight: 500,
                                                            fontSize: '14px',
                                                            lineHeight: '20px',
                                                            letterSpacing: '0%',
                                                            color: '#334155',
                                                            whiteSpace: 'nowrap'
                                                        }}>{__('Select Icon', 'wpuf-pro')}</span>
                                                        <Tooltip className="wpuf-ml-2" content={__('Choose an icon to display before the field label.', 'wpuf-pro')}>
                                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M9.375 9.375L9.40957 9.35771C9.88717 9.11891 10.4249 9.55029 10.2954 10.0683L9.70458 12.4317C9.57507 12.9497 10.1128 13.3811 10.5904 13.1423L10.625 13.125M17.5 10C17.5 14.1421 14.1421 17.5 10 17.5C5.85786 17.5 2.5 14.1421 2.5 10C2.5 5.85786 5.85786 2.5 10 2.5C14.1421 2.5 17.5 5.85786 17.5 10ZM10 6.875H10.0063V6.88125H10V6.875Z" stroke="#9CA3AF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"></path></svg>
                                                        </Tooltip>
                                                    </label>
                                                    <div className="wpuf-flex-1">
                                                        <IconPicker
                                                            value={item.field_icon || ''}
                                                            onChange={(val) => updateContentItem(item.id, 'field_icon', val)}
                                                            icons={(typeof wpuf_ud !== 'undefined' && wpuf_ud.icons) ? wpuf_ud.icons : []}
                                                        />
                                                    </div>
                                                </div>
                                            </div>
                                        )}

                                        {/* Role Selections */}
                                        {renderRoleDropdowns(item)}
                                        
                                        {/* Additional checkboxes for meta fields */}
                                        {item.type === 'meta_field' && (
                                            <div className="wpuf-mt-6 wpuf-pt-3 wpuf-border-t-[0.5px] wpuf-border-gray-200 wpuf-flex wpuf-gap-4">
                                                <label className="wpuf-flex wpuf-items-center wpuf-text-sm wpuf-text-gray-700 wpuf-cursor-pointer">
                                                    <div className="wpuf-relative wpuf-mr-3">
                                                        <input
                                                            type="checkbox"
                                                            className="wpuf-sr-only"
                                                            checked={item.show_in_listing || false}
                                                            onChange={(e) => updateContentItem(item.id, 'show_in_listing', e.target.checked)}
                                                        />
                                                        <div className={`wpuf-w-5 wpuf-h-5 wpuf-border-2 wpuf-rounded wpuf-flex wpuf-items-center wpuf-justify-center wpuf-transition-colors ${
                                                            item.show_in_listing 
                                                                ? 'wpuf-bg-emerald-600 wpuf-border-emerald-600' 
                                                                : 'wpuf-bg-white wpuf-border-gray-300 hover:wpuf-border-emerald-400'
                                                        }`}>
                                                            {item.show_in_listing && (
                                                                <svg width="12" height="10" viewBox="0 0 12 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                    <path d="M11.2588 0.990983C11.4931 1.22539 11.6248 1.54328 11.6248 1.87473C11.6248 2.20619 11.4931 2.52407 11.2588 2.75848L5.00877 9.00848C4.77436 9.24282 4.45648 9.37447 4.12502 9.37447C3.79357 9.37447 3.47568 9.24282 3.24127 9.00848L0.741271 6.50848C0.513573 6.27273 0.38758 5.95698 0.390428 5.62923C0.393276 5.30149 0.524737 4.98797 0.756497 4.75621C0.988258 4.52445 1.30177 4.39299 1.62952 4.39014C1.95726 4.38729 2.27302 4.51329 2.50877 4.74098L4.12502 6.35723L9.49127 0.990983C9.72568 0.756644 10.0436 0.625 10.375 0.625C10.7065 0.625 11.0244 0.756644 11.2588 0.990983Z" fill="white"/>
                                                                </svg>
                                                            )}
                                                        </div>
                                                    </div>
                                                    {__('Show in user listing table', 'wpuf-pro')}
                                                </label>
                                                <label className="wpuf-flex wpuf-items-center wpuf-text-sm wpuf-text-gray-700 wpuf-cursor-pointer">
                                                    <div className="wpuf-relative wpuf-mr-3">
                                                        <input
                                                            type="checkbox"
                                                            className="wpuf-sr-only"
                                                            checked={item.search_by_meta || false}
                                                            onChange={(e) => updateContentItem(item.id, 'search_by_meta', e.target.checked)}
                                                        />
                                                        <div className={`wpuf-w-5 wpuf-h-5 wpuf-border-2 wpuf-rounded wpuf-flex wpuf-items-center wpuf-justify-center wpuf-transition-colors ${
                                                            item.search_by_meta 
                                                                ? 'wpuf-bg-emerald-600 wpuf-border-emerald-600' 
                                                                : 'wpuf-bg-white wpuf-border-gray-300 hover:wpuf-border-emerald-400'
                                                        }`}>
                                                            {item.search_by_meta && (
                                                                <svg width="12" height="10" viewBox="0 0 12 10" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                                    <path d="M11.2588 0.990983C11.4931 1.22539 11.6248 1.54328 11.6248 1.87473C11.6248 2.20619 11.4931 2.52407 11.2588 2.75848L5.00877 9.00848C4.77436 9.24282 4.45648 9.37447 4.12502 9.37447C3.79357 9.37447 3.47568 9.24282 3.24127 9.00848L0.741271 6.50848C0.513573 6.27273 0.38758 5.95698 0.390428 5.62923C0.393276 5.30149 0.524737 4.98797 0.756497 4.75621C0.988258 4.52445 1.30177 4.39299 1.62952 4.39014C1.95726 4.38729 2.27302 4.51329 2.50877 4.74098L4.12502 6.35723L9.49127 0.990983C9.72568 0.756644 10.0436 0.625 10.375 0.625C10.7065 0.625 11.0244 0.756644 11.2588 0.990983Z" fill="white"/>
                                                                </svg>
                                                            )}
                                                        </div>
                                                    </div>
                                                    {__('Search by this meta in user listing table', 'wpuf-pro')}
                                                </label>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </div>
                        );
                    })}
                </div>
            )}

            {/* Add Content Button */}
            <div className="wpuf-relative" ref={dropdownRef}>
                <button
                    type="button"
                    className="wpuf-text-white wpuf-font-medium hover:wpuf-bg-emerald-700 wpuf-transition-colors wpuf-flex wpuf-items-center"
                    style={{
                        width: '162px',
                        height: '42px',
                        borderRadius: '6px',
                        paddingTop: '9px',
                        paddingRight: '17px',
                        paddingBottom: '9px',
                        paddingLeft: '15px',
                        backgroundColor: '#059669',
                        gap: '12px',
                        opacity: 1
                    }}
                    onClick={() => setShowDropdown(!showDropdown)}
                >
                    <svg className="wpuf-w-4 wpuf-h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4" />
                    </svg>
                    <span style={{
                        
                        fontWeight: 500,
                        fontSize: '16px',
                        lineHeight: '24px',
                        letterSpacing: '0%',
                        color: '#FFFFFF'
                    }}>
                        {__('Add Content', 'wpuf-pro')}
                    </span>
                </button>
                
                {/* Content Type Buttons */}
                {showDropdown && (
                    <div className="wpuf-mt-4 wpuf-p-4 wpuf-bg-white wpuf-border-[0.5px] wpuf-border-gray-200 wpuf-rounded-lg wpuf-w-[590px] wpuf-h-[100px]">
                        <div className="wpuf-flex wpuf-gap-2 wpuf-items-center wpuf-justify-center">
                            {contentTypes.map((type) => (
                                <button
                                    key={type.key}
                                    type="button"
                                    className="wpuf-flex wpuf-flex-col wpuf-items-center wpuf-justify-center wpuf-rounded-lg wpuf-border wpuf-text-sm wpuf-font-medium wpuf-transition-colors wpuf-w-[102px] wpuf-h-[68px] wpuf-gap-1 wpuf-p-3 wpuf-bg-white wpuf-border-gray-200 wpuf-text-gray-700 hover:wpuf-bg-emerald-50 hover:wpuf-border-emerald-200 hover:wpuf-text-emerald-700"
                                    onClick={() => handleContentTypeSelect(type)}
                                >
                                    <div className="wpuf-flex wpuf-items-center wpuf-justify-center">
                                        {type.key === 'meta_field' && (
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M11.25 14.0625H14.0625M14.0625 14.0625H16.875M14.0625 14.0625V11.25M14.0625 14.0625V16.875M5 8.75H6.875C7.91053 8.75 8.75 7.91053 8.75 6.875V5C8.75 3.96447 7.91053 3.125 6.875 3.125H5C3.96447 3.125 3.125 3.96447 3.125 5V6.875C3.125 7.91053 3.96447 8.75 5 8.75ZM5 16.875H6.875C7.91053 16.875 8.75 16.0355 8.75 15V13.125C8.75 12.0895 7.91053 11.25 6.875 11.25H5C3.96447 11.25 3.125 12.0895 3.125 13.125V15C3.125 16.0355 3.96447 16.875 5 16.875ZM13.125 8.75H15C16.0355 8.75 16.875 7.91053 16.875 6.875V5C16.875 3.96447 16.0355 3.125 15 3.125H13.125C12.0895 3.125 11.25 3.96447 11.25 5V6.875C11.25 7.91053 12.0895 8.75 13.125 8.75Z" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        )}
                                        {type.key === 'section' && (
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M3.125 10H16.875M3.125 13.125H16.875M3.125 16.25H16.875M4.6875 3.75H15.3125C16.1754 3.75 16.875 4.44956 16.875 5.3125C16.875 6.17544 16.1754 6.875 15.3125 6.875H4.6875C3.82456 6.875 3.125 6.17544 3.125 5.3125C3.125 4.44956 3.82456 3.75 4.6875 3.75Z" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        )}
                                        {type.key === 'post_type' && (
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M15.8333 16.6666H4.16667C3.24619 16.6666 2.5 15.9204 2.5 14.9999L2.5 4.99992C2.5 4.07944 3.24619 3.33325 4.16667 3.33325L12.5 3.33325C13.4205 3.33325 14.1667 4.07944 14.1667 4.99992V5.83325M15.8333 16.6666C14.9129 16.6666 14.1667 15.9204 14.1667 14.9999L14.1667 5.83325M15.8333 16.6666C16.7538 16.6666 17.5 15.9204 17.5 14.9999V7.49992C17.5 6.57944 16.7538 5.83325 15.8333 5.83325L14.1667 5.83325M10.8333 3.33325L7.5 3.33325M5.83333 13.3333H10.8333M5.83333 6.66659H10.8333V9.99992H5.83333V6.66659Z" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        )}
                                        {type.key === 'comment' && (
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M7.1875 10C7.1875 10.1726 7.04759 10.3125 6.875 10.3125C6.70241 10.3125 6.5625 10.1726 6.5625 10C6.5625 9.82741 6.70241 9.6875 6.875 9.6875C7.04759 9.6875 7.1875 9.82741 7.1875 10ZM7.1875 10H6.875M10.3125 10C10.3125 10.1726 10.1726 10.3125 10 10.3125C9.82741 10.3125 9.6875 10.1726 9.6875 10C9.6875 9.82741 9.82741 9.6875 10 9.6875C10.1726 9.6875 10.3125 9.82741 10.3125 10ZM10.3125 10H10M13.4375 10C13.4375 10.1726 13.2976 10.3125 13.125 10.3125C12.9524 10.3125 12.8125 10.1726 12.8125 10C12.8125 9.82741 12.9524 9.6875 13.125 9.6875C13.2976 9.6875 13.4375 9.82741 13.4375 10ZM13.4375 10H13.125M17.5 10C17.5 13.797 14.1421 16.875 10 16.875C9.26044 16.875 8.54588 16.7769 7.87098 16.5941C7.05847 17.1649 6.06834 17.5 5 17.5C4.83398 17.5 4.6698 17.4919 4.50806 17.4761C4.375 17.4631 4.24316 17.4449 4.11316 17.4216C4.5161 16.9461 4.80231 16.3689 4.92824 15.734C5.00378 15.3531 4.81725 14.9832 4.53903 14.7124C3.27475 13.4818 2.5 11.8238 2.5 10C2.5 6.20304 5.85786 3.125 10 3.125C14.1421 3.125 17.5 6.20304 17.5 10Z" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        )}
                                        {type.key === 'image_file' && (
                                            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M11.6668 3.33341H5.00016C4.55814 3.33341 4.13421 3.50901 3.82165 3.82157C3.50909 4.13413 3.3335 4.55805 3.3335 5.00008V13.3334M3.3335 13.3334V15.0001C3.3335 15.4421 3.50909 15.866 3.82165 16.1786C4.13421 16.4912 4.55814 16.6667 5.00016 16.6667H15.0002C15.4422 16.6667 15.8661 16.4912 16.1787 16.1786C16.4912 15.866 16.6668 15.4421 16.6668 15.0001V11.6667M3.3335 13.3334L7.15516 9.51175C7.46771 9.1993 7.89156 9.02377 8.3335 9.02377C8.77544 9.02377 9.19928 9.1993 9.51183 9.51175L11.6668 11.6667M16.6668 8.33341V11.6667M16.6668 11.6667L15.3452 10.3451C15.0326 10.0326 14.6088 9.8571 14.1668 9.8571C13.7249 9.8571 13.301 10.0326 12.9885 10.3451L11.6668 11.6667M11.6668 11.6667L13.3335 13.3334M15.0002 3.33341H18.3335M16.6668 1.66675V5.00008M11.6668 6.66675H11.6752" stroke="#6B7280" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
                                            </svg>
                                        )}
                                    </div>
                                    <span className="wpuf-text-sm wpuf-font-normal wpuf-leading-5 wpuf-text-gray-700">
                                        {type.label}
                                    </span>
                                </button>
                            ))}
                        </div>
                    </div>
                )}
            </div>
                </div>
            )}
        </div>
    );
};

export default AboutTabsSetup;