// User Profile Container Edit Component
// Multiple layout templates with pattern selection

import {__} from '@wordpress/i18n';
import {
    __experimentalHeading as Heading,
    __experimentalText as Text,
    Button,
    Card,
    CardBody,
    CardMedia,
    Notice,
    PanelBody,
    SelectControl,
    Spinner,
    Modal
} from '@wordpress/components';
import {InspectorControls, useBlockProps, useInnerBlocksProps, InnerBlocks, BlockContextProvider} from '@wordpress/block-editor';
import {Fragment, useEffect, useState} from '@wordpress/element';
import {useDispatch, useSelect} from '@wordpress/data';

// Register custom WordPress data store for profile state management
if (!wp.data.select('wpuf-ud/profile-state')) {
    wp.data.registerStore('wpuf-ud/profile-state', {
        reducer: (state = {}, action) => {
            let newState;
            switch (action.type) {
                case 'STORE_LAYOUT_STATE':
                    newState = {
                        ...state,
                        [action.layoutName]: {
                            ...action.stateSnapshot,
                            storedAt: Date.now()
                        }
                    };
                    return newState;
                case 'CLEAR_LAYOUT_STATE':
                    newState = { ...state };
                    delete newState[action.layoutName];
                    return newState;
                case 'CLEAR_ALL_STATES':
                    return {};
                default:
                    return state;
            }
        },
        actions: {
            storeLayoutState: (layoutName, stateSnapshot) => ({
                type: 'STORE_LAYOUT_STATE',
                layoutName,
                stateSnapshot
            }),
            clearLayoutState: (layoutName) => ({
                type: 'CLEAR_LAYOUT_STATE',
                layoutName
            }),
            clearAllStates: () => ({
                type: 'CLEAR_ALL_STATES'
            })
        },
        selectors: {
            getStoredState: (state, layoutName) => state[layoutName] || null,
            getAllStoredStates: (state) => state,
            getStoredLayoutNames: (state) => Object.keys(state),
            hasStoredState: (state, layoutName) => !!state[layoutName]
        }
    });
}

// Confirmation Modal Component
const ConfirmationModal = ({ isOpen, onConfirm, onCancel, title, message, confirmText, cancelText }) => {
    if (!isOpen) return null;

    return (
        <Modal
            title={title}
            onRequestClose={onCancel}
            className="wpuf-confirmation-modal"
        >
            <div className="wpuf-modal-content">
                <p>{message}</p>
                <div className="wpuf-modal-actions">
                    <Button
                        variant="secondary"
                        onClick={onCancel}
                    >
                        {cancelText}
                    </Button>
                    <Button
                        variant="primary"
                        onClick={onConfirm}
                        className="wpuf-confirm-button"
                    >
                        {confirmText}
                    </Button>
                </div>
            </div>
        </Modal>
    );
};

// Layout 1: Column-based template (35% / 65% split with modern styling)
const LAYOUT_1_TEMPLATE = [
    ['core/columns', {
        className: 'wpuf-flex wpuf-flex-row wpuf-gap-8 wpuf-border wpuf-border-gray-200 wpuf-rounded-lg wpuf-p-8'
    }, [
        ['core/column', {
            width: '35%',
            className: 'wpuf-profile-sidebar',
            style: {
                border: {
                    style: 'none',
                    width: '0px'
                },
                spacing: {
                    padding: {
                        right: 'var:preset|spacing|40',
                        top: '0',
                        bottom: '0',
                        left: '0'
                    }
                }
            },
            layout: {
                type: 'constrained',
                justifyContent: 'left',
                contentSize: '75%'
            }
        }, [
            ['wpuf-ud/avatar', {
                avatarSize: 'custom',
                fallbackType: 'gravatar',
                customSize: 100,
                style: {
                    spacing: {
                        margin: {
                            bottom: '10px'
                        }
                    }
                }
            }],
            ['wpuf-ud/name', {
                nameFormat: 'first_last',
                headingLevel: 'h2',
                fontFamily: 'manrope',
                style: {
                    typography: {
                        fontStyle: 'normal',
                        fontWeight: '700'
                    }
                }
            }],
            ['wpuf-ud/contact', {
                showFields: ['email', 'website'],
                layoutStyle: 'vertical',
                showLabels: false,
                iconColor: '#707070',
                style: {
                    typography: {
                        fontSize: '14px',
                        lineHeight: '1.7'
                    },
                    spacing: {
                        margin: {
                            bottom: '20px',
                            top: 'var:preset|spacing|20'
                        }
                    }
                }
            }],
            ['core/heading', {
                level: 4,
                content: 'SOCIAL',
                style: {
                    spacing: {
                        margin: {
                            top: 'var:preset|spacing|40',
                            right: '0'
                        }
                    },
                    color: {
                        text: '#707070'
                    },
                    elements: {
                        link: {
                            color: {
                                text: '#707070'
                            }
                        }
                    },
                    typography: {
                        fontStyle: 'normal',
                        fontWeight: '700'
                    }
                },
                fontSize: 'small'
            }],
            ['wpuf-ud/social', {
                layoutStyle: 'layout-2',
                style: {
                    spacing: {
                        margin: {
                            right: '0',
                            top: 'var:preset|spacing|20'
                        },
                        padding: {
                            right: 'var:preset|spacing|20',
                            left: '0',
                            top: '0'
                        }
                    }
                }
            }],
            ['core/heading', {
                level: 4,
                content: 'BIO',
                style: {
                    spacing: {
                        margin: {
                            top: 'var:preset|spacing|40'
                        }
                    },
                    color: {
                        text: '#707070'
                    },
                    elements: {
                        link: {
                            color: {
                                text: '#707070'
                            }
                        }
                    },
                    typography: {
                        fontStyle: 'normal',
                        fontWeight: '700'
                    }
                },
                fontSize: 'small'
            }],
            ['wpuf-ud/bio', {
                characterLimit: 100,
                style: {
                    spacing: {
                        margin: {
                            top: 'var:preset|spacing|20'
                        },
                        padding: {
                            right: '0'
                        }
                    },
                    typography: {
                        fontSize: '14px'
                    }
                }
            }],
            // Insertion point for unmatched blocks before tabs
            ['wpuf-ud/unmatched-blocks', {}],
        ]],
        ['core/column', {
            width: '65%',
            className: 'wpuf-profile-content',
            layout: {
                type: 'default'
            }
        }, [
            ['wpuf-ud/tabs', {
                style: {
                    spacing: {
                        margin: {
                            top: '100px'
                        }
                    }
                }
            }, [
                ['core/heading', {
                    level: 4,
                    content: 'BIO',
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|40'
                            }
                        },
                        color: {
                            text: '#707070'
                        },
                        elements: {
                            link: {
                                color: {
                                    text: '#707070'
                                }
                            }
                        },
                        typography: {
                            fontStyle: 'normal',
                            fontWeight: '700'
                        }
                    },
                    fontSize: 'small'
                }],
                ['wpuf-ud/bio', {
                    characterLimit: 100,
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|20'
                            },
                            padding: {
                                right: '0'
                            }
                        },
                        typography: {
                            fontSize: '14px'
                        }
                    }
                }],
            ]]
        ]]
    ]]
];

// Layout 2: Centered design with 17%/65%/17% columns and modern styling
const LAYOUT_2_TEMPLATE = [
    ['core/columns', {
        verticalAlignment: null,
        style: {
            spacing: {
                margin: {
                    top: 'var:preset|spacing|40',
                    bottom: 'var:preset|spacing|40'
                }
            }
        }
    }, [
        ['core/column', {
            verticalAlignment: 'top',
            width: '17%'
        }, []],
        ['core/column', {
            verticalAlignment: 'top',
            width: '65%',
            layout: {
                type: 'default'
            }
        }, [
            ['core/group', {
                layout: {
                    type: 'flex',
                    orientation: 'vertical',
                    justifyContent: 'center'
                }
            }, [
                ['wpuf-ud/avatar', {
                    avatarSize: 'custom',
                    fallbackType: 'gravatar',
                    customSize: 100,
                    style: {
                        spacing: {
                            margin: {
                                bottom: '10px'
                            }
                        }
                    }
                }],
                ['wpuf-ud/name', {
                    nameFormat: 'first_last',
                    headingLevel: 'h2',
                    fontFamily: 'manrope',
                    style: {
                        typography: {
                            fontStyle: 'normal',
                            fontWeight: '700'
                        }
                    }
                }],
                ['core/group', {
                    style: {
                        spacing: {
                            padding: {
                                left: 'var:preset|spacing|50',
                                right: 'var:preset|spacing|50',
                                top: 'var:preset|spacing|30',
                                bottom: 'var:preset|spacing|30'
                            },
                            margin: {
                                top: '0',
                                bottom: '0'
                            }
                        },
                        border: {
                            color: '#e1e5e8',
                            top: {
                                width: '1px',
                                style: 'dashed'
                            },
                            bottom: {
                                width: '1px',
                                style: 'dashed'
                            }
                        },
                    },
                    layout: {
                        type: 'flex',
                        flexWrap: 'nowrap',
                        justifyContent: 'center',
                        verticalAlignment: 'top'
                    }
                }, [
                    ['wpuf-ud/contact', {
                        showFields: ['email'],
                        layoutStyle: 'vertical',
                        iconColor: '#059669',
                        style: {
                            typography: {
                                fontSize: '14px',
                                lineHeight: '1.7'
                            },
                            spacing: {
                                margin: {
                                    bottom: '0',
                                    top: '0'
                                }
                            },
                            layout: {
                                selfStretch: 'fit'
                            }
                        }
                    }],
                    ['wpuf-ud/contact', {
                        showFields: ['website'],
                        layoutStyle: 'vertical',
                        iconColor: '#059669',
                        style: {
                            typography: {
                                fontSize: '14px',
                                lineHeight: '1.7'
                            },
                            spacing: {
                                margin: {
                                    bottom: '0',
                                    top: '0'
                                }
                            },
                            layout: {
                                selfStretch: 'fit'
                            }
                        }
                    }],
                    // Insertion point for unmatched blocks before tabs
                    ['wpuf-ud/unmatched-blocks', {}],
                ]]
            ]],
            ['core/group', {
                style: {
                    border: {
                        top: {
                            width: '0px',
                            style: 'none'
                        },
                        right: {
                            width: '0px',
                            style: 'none'
                        },
                        bottom: {
                            width: '1px'
                        },
                        left: {
                            width: '0px',
                            style: 'none'
                        }
                    },
                    spacing: {
                        margin: {
                            bottom: '0'
                        },
                        padding: {
                            bottom: 'var:preset|spacing|40'
                        }
                    }
                },
                layout: {
                    type: 'flex',
                    orientation: 'vertical',
                    justifyContent: 'center'
                }
            }, [
                ['wpuf-ud/social', {
                    layoutStyle: 'layout-3',
                    iconColor: '#059669',
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|40'
                            }
                        },
                        layout: {
                            selfStretch: 'fit'
                        }
                    }
                }],
                ['wpuf-ud/bio', {
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|30'
                            }
                        },
                        typography: {
                            fontSize: '14px'
                        }
                    }
                }]
            ]],
            // Insertion point for unmatched blocks before tabs
            ['wpuf-ud/unmatched-blocks', {}],
        ]],
        ['core/column', {
            width: '17%',
            layout: {
                type: 'default'
            }
        }, []]
    ]],
    ['core/columns', {
        verticalAlignment: 'top',
        style: {
            spacing: {
                margin: {
                    top: '0',
                    bottom: 'var:preset|spacing|40'
                }
            }
        }
    }, [
        ['core/column', {
            verticalAlignment: 'top',
            width: '17%'
        }, []],
        ['core/column', {
            width: '65%'
        }, [
            ['wpuf-ud/tabs', {
                style: {
                    spacing: {
                        padding: {
                            top: '0',
                            bottom: '0'
                        }
                    }
                }
            }, [
                ['core/heading', {
                    level: 4,
                    content: 'BIO',
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|40'
                            }
                        },
                        color: {
                            text: '#707070'
                        },
                        elements: {
                            link: {
                                color: {
                                    text: '#707070'
                                }
                            }
                        },
                        typography: {
                            fontStyle: 'normal',
                            fontWeight: '700'
                        }
                    },
                    fontSize: 'small'
                }],
                ['wpuf-ud/bio', {
                    characterLimit: 100,
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|20'
                            },
                            padding: {
                                right: '0'
                            }
                        },
                        typography: {
                            fontSize: '14px'
                        }
                    }
                }],
            ]]
        ]],
        ['core/column', {
            width: '17%',
            layout: {
                type: 'default'
            }
        }, []]
    ]]
];

// Layout 3: Comprehensive profile with directory section
const LAYOUT_3_TEMPLATE = [
    ['core/group', {
        layout: {
            type: 'flex',
            flexWrap: 'nowrap'
        }
    }, [
        ['wpuf-ud/avatar', {
            avatarSize: 'custom',
            fallbackType: 'gravatar',
            customSize: 100,
            style: {
                spacing: {
                    margin: {
                        bottom: '10px'
                    }
                }
            }
        }]
    ]],
    ['core/group', {
        layout: {
            type: 'flex',
            flexWrap: 'nowrap',
            justifyContent: 'right'
        }
    }, [
        ['wpuf-ud/social', {
            layoutStyle: 'layout-3',
            style: {
                spacing: {
                    margin: {
                        bottom: '0',
                        top: '0'
                    },
                    padding: {
                        bottom: '0',
                        right: '0',
                        top: '0'
                    }
                }
            }
        }]
    ]],
    ['wpuf-ud/name', {
        nameFormat: 'first_last',
        headingLevel: 'h2',
        fontFamily: 'manrope',
        style: {
            typography: {
                fontStyle: 'normal',
                fontWeight: '700'
            }
        }
    }],
    ['wpuf-ud/contact', {
        showFields: ['email', 'website'],
        layoutStyle: 'vertical',
        showLabels: false,
        iconColor: '#707070',
        style: {
            typography: {
                fontSize: '14px',
                lineHeight: '1.7'
            },
            spacing: {
                margin: {
                    bottom: '0',
                    top: 'var:preset|spacing|20'
                }
            }
        }
    }],
    ['wpuf-ud/bio', {
        style: {
            spacing: {
                margin: {
                    top: 'var:preset|spacing|30'
                }
            },
            typography: {
                fontSize: '14px'
            }
        }
    }],
    // Insertion point for unmatched blocks before tabs
    ['wpuf-ud/unmatched-blocks', {}],
    ['core/columns', {
        verticalAlignment: 'top'
    }, [
        ['core/column', {
            verticalAlignment: 'top',
            width: '65%'
        }, [
            ['wpuf-ud/tabs', {
                style: {
                    spacing: {
                        margin: {
                            top: 'var:preset|spacing|50'
                        }
                    }
                }
            }, [
                ['core/heading', {
                    level: 4,
                    content: 'BIO',
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|40'
                            }
                        },
                        color: {
                            text: '#707070'
                        },
                        elements: {
                            link: {
                                color: {
                                    text: '#707070'
                                }
                            }
                        },
                        typography: {
                            fontStyle: 'normal',
                            fontWeight: '700'
                        }
                    },
                    fontSize: 'small'
                }],
                ['wpuf-ud/bio', {
                    characterLimit: 100,
                    style: {
                        spacing: {
                            margin: {
                                top: 'var:preset|spacing|20'
                            },
                            padding: {
                                right: '0'
                            }
                        },
                        typography: {
                            fontSize: '14px'
                        }
                    }
                }],
            ]]
        ]]
    ]]
];

// Layout patterns configuration
const LAYOUT_PATTERNS = [
    {
        name: 'layout-1',
        title: __('Navigator', 'wpuf-pro'),
        template: LAYOUT_1_TEMPLATE
    },
    {
        name: 'layout-2',
        title: __('Centered', 'wpuf-pro'),
        template: LAYOUT_2_TEMPLATE
    },
    {
        name: 'layout-3',
        title: __('Spotlight', 'wpuf-pro'),
        template: LAYOUT_3_TEMPLATE
    }
];

// Get available blocks, filtering out any that aren't registered
const getAvailableBlocks = () => {
    const allBlocks = [
        // Core layout blocks
        'core/group',
        'core/stack',
        'core/columns',
        'core/column',
        'core/row',
        'core/heading',
        'core/paragraph',
        'core/spacer',
        'core/separator',
        'core/buttons',
        'core/button',
        'core/list',
        'core/list-item',
        'core/image',
        'core/embed',
        // WPUF User Directory blocks
        'wpuf-ud/avatar',
        'wpuf-ud/cover-photo',
        'wpuf-ud/name',
        'wpuf-ud/contact',
        'wpuf-ud/bio',
        'wpuf-ud/custom-field',
        'wpuf-ud/files',
        'wpuf-ud/tabs',
        'wpuf-ud/posts',
        'wpuf-ud/comments',
        'wpuf-ud/social'
    ];

    // Filter to only include blocks that are actually registered
    if (typeof wp !== 'undefined' && wp.blocks && wp.blocks.getBlockType) {
        return allBlocks.filter(blockName => wp.blocks.getBlockType(blockName));
    }

    // Fallback to core blocks if wp.blocks isn't available
    return [
        'core/group',
        'core/stack',
        'core/columns',
        'core/column',
        'core/heading',
        'core/paragraph',
        'core/spacer',
        'core/separator'
    ];
};

// Navigation Buttons Component for Editor Preview
const NavigationButtons = ({ user, canEdit }) => {
    // In the editor, we can't check WPUF options directly, so we'll show the button
    // if the user can edit (same user) and add a note that it depends on WPUF settings
    const showEditButton = canEdit;

    return (
        <div className="wpuf-profile-navigation wpuf-flex wpuf-justify-between wpuf-items-center wpuf-mb-6 wpuf-py-3">
            {/* Back button (left side) */}
            <button
                type="button"
                className="wpuf-nav-button wpuf-back-button wpuf-inline-flex wpuf-items-center wpuf-gap-2 wpuf-px-4 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-700 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-shadow-sm hover:wpuf-bg-gray-50 hover:wpuf-text-gray-900 focus:wpuf-outline-none focus:wpuf-ring-2 focus:wpuf-ring-offset-2 focus:wpuf-ring-indigo-500 wpuf-transition-colors wpuf-duration-200"
                disabled // Disabled in editor
                style={{ cursor: 'default' }}
            >
                {/* Left arrow icon */}
                <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="M15 19l-7-7 7-7" />
                </svg>
                {__('Back', 'wpuf-pro')}
            </button>

            {/* Edit profile button (right side) - only show if user can edit */}
            {showEditButton ? (
                <button
                    type="button"
                    className="wpuf-nav-button wpuf-edit-button wpuf-inline-flex wpuf-items-center wpuf-gap-2 wpuf-px-4 wpuf-py-2 wpuf-text-sm wpuf-font-medium wpuf-text-gray-700 wpuf-bg-white wpuf-border wpuf-border-gray-300 wpuf-rounded-md wpuf-shadow-sm hover:wpuf-bg-gray-50 hover:wpuf-text-gray-900 focus:wpuf-outline-none focus:wpuf-ring-2 focus:wpuf-ring-offset-2 focus:wpuf-ring-indigo-500 wpuf-transition-colors wpuf-duration-200"
                    disabled // Disabled in editor
                    style={{ cursor: 'default' }}
                    title={__('Edit Profile (requires WPUF account page configuration)', 'wpuf-pro')}
                >
                    {__('Edit Profile', 'wpuf-pro')}
                    {/* Edit icon */}
                    <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="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                    </svg>
                </button>
            ) : (
                // Empty space to maintain flexbox layout balance
                <div></div>
            )}
        </div>
    );
};

// Helper function to check if blocks are available
const areBlocksAvailable = () => {
    if (typeof wp === 'undefined' || !wp.blocks) {
        return false;
    }

    // Check if core blocks are available
    const coreBlocks = ['core/columns', 'core/column', 'core/heading', 'core/group'];
    const coreAvailable = coreBlocks.every(blockName => wp.blocks.getBlockType(blockName));

    // Check if WPUF blocks are available (they might not be registered yet)
    const wpufBlocks = ['wpuf-ud/avatar', 'wpuf-ud/name', 'wpuf-ud/contact', 'wpuf-ud/bio', 'wpuf-ud/tabs'];
    const wpufAvailable = wpufBlocks.every(blockName => wp.blocks.getBlockType(blockName));

    return coreAvailable && wpufAvailable;
};

// Helper function to convert template to blocks
const convertTemplateToBlocks = (template) => {
    if (!Array.isArray(template)) {
        return [];
    }

    if (typeof wp === 'undefined' || !wp.blocks || !wp.blocks.createBlock) {
        return [];
    }

    return template.map((item, index) => {
        // Check if item is already a block object (has name and clientId properties)
        if (item && typeof item === 'object' && item.name && item.clientId) {
            return item;
        }

        if (!Array.isArray(item) || item.length === 0) {
            return null;
        }

        const [blockName, attributes = {}, innerContent = []] = item;

        if (typeof blockName !== 'string') {
            return null;
        }

        try {
            // Convert inner content to blocks recursively
            const innerBlocks = Array.isArray(innerContent) ? convertTemplateToBlocks(innerContent) : [];

            return wp.blocks.createBlock(blockName, attributes, innerBlocks);
        		} catch (error) {
			return null;
		}
    }).filter(block => block !== null);
};

// Helper function to create blocks safely
const createBlocksSafely = (template) => {
    	if (!areBlocksAvailable()) {
		// Return a simple fallback template with only core blocks
        return convertTemplateToBlocks([
            ['core/group', {className: 'wpuf-profile-fallback'}, [
                ['core/heading', {level: 2}, 'User Profile'],
                ['core/paragraph', {}, 'Profile content will be displayed here.']
            ]]
        ]);
    }

    try {
        return convertTemplateToBlocks( template );
    	} catch (error) {
		// Try to create a minimal fallback template
		try {
			return convertTemplateToBlocks([
				['core/group', {className: 'wpuf-profile-error-fallback'}, [
					['core/heading', {level: 2}, 'User Profile'],
					['core/paragraph', {}, 'There was an error loading the profile layout. Please try selecting a different layout.']
				]]
			]);
		} catch (fallbackError) {
            console.error('❌ Fallback template creation also failed:', fallbackError);
			return [];
		}
	}
};

// Function to check if we have a stored state for a layout using WordPress store
const getStoredStateForLayout = (layoutName) => {
    const storedState = wp.data.select('wpuf-ud/profile-state').getStoredState(layoutName);
    if (storedState) {
        return storedState;
    }
    return null;
};

// Function to manually restore a stored layout state using WordPress store
const restoreLayoutState = (layoutName, replaceInnerBlocks, setAttributes) => {
    const storedState = getStoredStateForLayout(layoutName);
    if (!storedState) {
        return false;
    }

    try {
        // Use the existing restoreCapturedState function
        const restoreResult = restoreCapturedState(storedState, replaceInnerBlocks, setAttributes);
        return restoreResult;
    } catch (error) {
        return false;
    }
};

// Deep state cloning function to capture complete block state
const captureCurrentState = (clientId, innerBlocks, selectedPattern, attributes) => {
    const select = wp.data.select;
    const blockEditor = select('core/block-editor');

    // Get all inner blocks recursively with full state
    const captureInnerBlocks = (blocks, depth = 0) => {
        if (!Array.isArray(blocks)) return [];

        return blocks.map((block, index) => {
            if (!block || !block.name) return null;

            // Get the complete block object from the store
            const fullBlock = blockEditor.getBlock(block.clientId) || block;

            // Deep clone attributes to avoid reference issues
            const clonedAttributes = JSON.parse(JSON.stringify(block.attributes || {}));



            // Recursively capture inner blocks
            const innerBlocksCaptured = block.innerBlocks && block.innerBlocks.length > 0
                ? captureInnerBlocks(block.innerBlocks, depth + 1)
                : [];

            // Check if block type is available
            let blockTypeInfo = null;
            try {
                blockTypeInfo = wp.blocks.getBlockType ? wp.blocks.getBlockType(block.name) : null;
            } catch (error) {
                console.warn(`Could not get block type for ${block.name}:`, error);
            }

            return {
                name: block.name,
                attributes: clonedAttributes,
                innerBlocks: innerBlocksCaptured,
                clientId: block.clientId,
                // Store additional metadata
                isValid: blockTypeInfo !== null,
                // Capture block order for restoration
                originalIndex: index,
                depth: depth,
                // Store block type info for debugging
                blockType: blockTypeInfo
            };
        }).filter(block => block !== null);
    };

    // Capture the complete state
    const stateSnapshot = {
        // Block container information
        containerClientId: clientId,
        selectedPattern: selectedPattern,
        containerAttributes: { ...attributes },

        // All inner blocks with complete state
        innerBlocks: captureInnerBlocks(innerBlocks),

        // Metadata for restoration
        capturedAt: Date.now(),
        blockCount: innerBlocks ? innerBlocks.length : 0,

        // User context (important for restoration)
        userId: attributes.userId,
        userObject: attributes.userObject,
        canEdit: attributes.canEdit,

        // Additional context
        componentSpacing: attributes.componentSpacing
    };

    return stateSnapshot;
};



// Function to restore captured state
const restoreCapturedState = (stateSnapshot, replaceInnerBlocks, setAttributes) => {
    if (!stateSnapshot || !stateSnapshot.innerBlocks) {
        return false;
    }

    try {
        // Restore container attributes
        if (stateSnapshot.containerAttributes) {
            setAttributes({
                ...stateSnapshot.containerAttributes,
                // Ensure we don't override critical attributes
                hasSelectedPattern: true,
                selectedPattern: stateSnapshot.selectedPattern
            });
        }

        // Convert captured blocks back to block objects for restoration
        const restoreBlocksRecursively = (capturedBlocks) => {
            if (!Array.isArray(capturedBlocks)) return [];

            return capturedBlocks.map(capturedBlock => {
                if (!capturedBlock || !capturedBlock.name) return null;

                try {
                    // Create a new block with the captured attributes
                    const block = wp.blocks.createBlock(
                        capturedBlock.name,
                        capturedBlock.attributes,
                        capturedBlock.innerBlocks ? restoreBlocksRecursively(capturedBlock.innerBlocks) : []
                    );

                    return block;
                } catch (error) {
                    return null;
                }
            }).filter(block => block !== null);
        };

        const restoredBlocks = restoreBlocksRecursively(stateSnapshot.innerBlocks);

        // Replace inner blocks with restored blocks
        if (restoredBlocks.length > 0) {
            replaceInnerBlocks(stateSnapshot.containerClientId, restoredBlocks);
            return true;
        } else {
            return false;
        }

    } catch (error) {
        return false;
    }
};

// Function to process template with selective block replacement
const processTemplateWithState = (template, currentState) => {
    if (!template || !Array.isArray(template)) {
        return template;
    }

    if (!currentState || !currentState.innerBlocks) {
        return template;
    }

    // Create a map of available wpuf-ud/* blocks from current state for quick lookup
    const availableWpufBlocks = new Map();
    const processedBlocks = new Set(); // Track which blocks we've used

    // Recursively collect all wpuf-ud/* blocks from current state
    const collectWpufBlocks = (blocks, depth = 0) => {
        if (!Array.isArray(blocks)) return;

        blocks.forEach((block, index) => {
            if (!block || !block.name) return;

            // If it's a wpuf-ud/* block and we haven't processed it yet
            if (block.name.startsWith('wpuf-ud/') && !processedBlocks.has(block.clientId)) {
                const blockKey = block.name;

                // Store first occurrence (as per requirement #3)
                if (!availableWpufBlocks.has(blockKey)) {
                    availableWpufBlocks.set(blockKey, {
                        block: block,
                        clientId: block.clientId,
                        depth: depth,
                        index: index
                    });
                }
            }

            // Recursively process inner blocks
            if (block.innerBlocks && block.innerBlocks.length > 0) {
                collectWpufBlocks(block.innerBlocks, depth + 1);
            }
        });
    };

    collectWpufBlocks(currentState.innerBlocks);

    // Recursively process template and replace wpuf-ud/* blocks
    const processTemplateRecursively = (templateBlocks) => {
        if (!Array.isArray(templateBlocks)) return templateBlocks;

        return templateBlocks.map(templateBlock => {
            if (!Array.isArray(templateBlock) || templateBlock.length === 0) {
                return templateBlock;
            }

            const [blockName, attributes = {}, innerContent = []] = templateBlock;

            // If this is a wpuf-ud/* block, check if we have a replacement
            if (blockName.startsWith('wpuf-ud/')) {
                // Special handling for unmatched-blocks insertion point
                if (blockName === 'wpuf-ud/unmatched-blocks') {
                    // Mark this as an insertion point for later processing
                    return {
                        type: 'insertion-point'
                    };
                }



                const replacement = availableWpufBlocks.get(blockName);

                if (replacement) {
                    // Mark this block as processed
                    processedBlocks.add(replacement.clientId);

                    // Special handling for tabs block - preserve inner blocks as about tab content
                    if (blockName === 'wpuf-ud/tabs') {
                        // For tabs block, we need to preserve the inner blocks as-is, not process them recursively
                        // because they represent the about tab content
                        const preservedInnerBlocks = replacement.block.innerBlocks || [];

                        return [
                            blockName,
                            replacement.block.attributes, // Use stored attributes
                            preservedInnerBlocks
                        ];
                    }

                    // Use the stored state block with its attributes
                    return [
                        blockName,
                        replacement.block.attributes, // Use stored attributes (requirement #3)
                        replacement.block.innerBlocks ? processTemplateRecursively(replacement.block.innerBlocks) : []
                    ];
                } else {
                    // Keep template default (requirement #4)
                    return [
                        blockName,
                        attributes,
                        Array.isArray(innerContent) ? processTemplateRecursively(innerContent) : []
                    ];
                }
            } else {
                // Non-wpuf-ud/* block - keep as-is but process inner content
                return [
                    blockName,
                    attributes,
                    Array.isArray(innerContent) ? processTemplateRecursively(innerContent) : []
                ];
            }
        });
    };

    // Process the template
    const processedTemplate = processTemplateRecursively(template);

    // Recursively collect unmatched blocks from current state
    const unmatchedBlocks = [];

    // Define layout blocks that should not be preserved
    const layoutBlocks = [
        'core/group',
        'core/columns',
        'core/column',
        'core/row',
        'core/stack'
    ];

    const collectUnmatchedBlocks = (blocks, depth = 0) => {
        if (!Array.isArray(blocks)) return;

        blocks.forEach((block, index) => {
            if (!block || !block.name) return;

            // If it's any block and we haven't processed it yet
            if (!processedBlocks.has(block.clientId)) {
                // Skip layout blocks - they should not be preserved
                if (layoutBlocks.includes(block.name)) {
                    return;
                }

                unmatchedBlocks.push(block);
            }

            // Recursively process inner blocks
            if (block.innerBlocks && block.innerBlocks.length > 0) {
                collectUnmatchedBlocks(block.innerBlocks, depth + 1);
            }
        });
    };

    collectUnmatchedBlocks(currentState.innerBlocks);

    // Insert unmatched blocks at specific insertion points
    if (unmatchedBlocks.length > 0) {

        // Convert unmatched blocks to template format
        const unmatchedTemplateBlocks = unmatchedBlocks.map(block => [
            block.name,
            block.attributes,
            block.innerBlocks ? processTemplateRecursively(block.innerBlocks) : []
        ]);



        // Replace insertion point markers with unmatched blocks
        let insertionPointsReplaced = 0;

        const replaceInsertionPoints = (blocks, depth = 0) => {
            if (!Array.isArray(blocks)) return blocks;

            const result = [];

            for (let i = 0; i < blocks.length; i++) {
                const block = blocks[i];

                // Handle insertion point markers - replace with unmatched blocks
                if (block && typeof block === 'object' && block.type === 'insertion-point') {
                    result.push(...unmatchedTemplateBlocks);
                    insertionPointsReplaced++;
                    continue;
                }

                if (!Array.isArray(block) || block.length === 0) {
                    result.push(block);
                    continue;
                }

                const [blockName, attributes = {}, innerContent = []] = block;

                // Process inner content recursively
                const processedInnerContent = Array.isArray(innerContent) ? replaceInsertionPoints(innerContent, depth + 1) : innerContent;

                result.push([blockName, attributes, processedInnerContent]);
            }

            return result;
        };

        // Replace insertion points with unmatched blocks
        const finalTemplate = replaceInsertionPoints(processedTemplate);

        // Only append to the end if no insertion points were replaced
        if (insertionPointsReplaced === 0) {
            finalTemplate.push(...unmatchedTemplateBlocks);
        }

        return finalTemplate;
    }

    return processedTemplate;
};

// Hook to get user data
const useUserData = (clientId) => {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);

    // Get directory context if available
    const directoryContext = useSelect((select) => {
        return select('core/block-editor').getBlockParents(clientId).reduce((context, parentId) => {
            const parentBlock = select('core/block-editor').getBlock(parentId);
            if (parentBlock && parentBlock.name === 'wpuf-ud/directory') {
                return {
                    ...context,
                    isInDirectory: true,
                    directoryId: parentBlock.attributes.directory_id,
                    users: parentBlock.attributes.users || [],
                    totalUsers: parentBlock.attributes.totalUsers || 0,
                    userIndex: parentBlock.attributes.userIndex || 0
                };
            }
            return context;
        }, {});
    }, [clientId]);

    useEffect(() => {
        const fetchUser = () => {
            setLoading(true);
            setError(null);

            // If we're in directory mode, get user from directory context
            if (directoryContext.isInDirectory && directoryContext.users && directoryContext.users.length > 0) {
                const userIndex = directoryContext.userIndex || 0;
                const directoryUser = directoryContext.users[userIndex];

                if (directoryUser) {
                    // Transform directory user to match our expected format
                    const transformedUser = {
                        id: directoryUser.id,
                        user_login: directoryUser.user_login || directoryUser.username,
                        display_name: directoryUser.display_name || directoryUser.name,
                        user_email: directoryUser.user_email || '',
                        user_url: directoryUser.user_url || '',
                        bio: directoryUser.bio || directoryUser.description || '',
                        avatar: directoryUser.avatar || '',
                        first_name: directoryUser.first_name || '',
                        last_name: directoryUser.last_name || '',
                        nickname: directoryUser.nickname || '',
                        user_registered: directoryUser.user_registered || directoryUser.registered_date || '',
                        roles: directoryUser.roles || ['subscriber'],
                        class_list: directoryUser.class_list || '',
                        // Ensure these fields are present for name formatting
                        username: directoryUser.user_login || directoryUser.username,
                        name: directoryUser.display_name || directoryUser.name
                    };
                    setUser(transformedUser);
                    setLoading(false);
                    return;
                }
            }

            // Fallback to user detection logic
            const detectUser = async () => {
                try {
                    // Try URL first, then current user (auto detection)
                    const urlParams = new URLSearchParams(window.location.search);
                    let userId = urlParams.get('id') || urlParams.get('user') || urlParams.get('user_id') || urlParams.get('author') || window.wpufUserDirectory?.current_user_id;

                    if (!userId) {
                        throw new Error('No user ID found');
                    }

                    // Use the current user profile API endpoint for proper user data structure
                    const response = await wp.apiFetch({
                        path: `/wpuf/v1/user-profile/current`,
                        headers: { 'X-WP-Nonce': window.wpufUserDirectory?.rest_nonce || '' }
                    });

                    if (response && response.id) {
                        // Transform the API response to match our expected format
                        const transformedUser = {
                            id: response.id,
                            user_login: response.username,
                            display_name: response.name,
                            user_email: response.user_email || '',
                            user_url: response.user_url || '',
                            bio: response.description || '',
                            avatar: response.avatar_urls?.['96'] || response.avatar_urls?.['150'] || '',
                            first_name: response.first_name || '',
                            last_name: response.last_name || '',
                            nickname: response.nickname || '',
                            user_registered: response.registered_date || '',
                            roles: response.roles || ['subscriber'],
                            class_list: '',
                            // Ensure these fields are present for name formatting
                            username: response.username,
                            name: response.name
                        };
                        setUser(transformedUser);
                    } else {
                        throw new Error('Invalid user data received');
                    }
                		} catch (err) {
			setError(err.message || 'Failed to load user');
		} finally {
                    setLoading(false);
                }
            };

            detectUser();
        };

        fetchUser();
    }, [directoryContext]);

    // Generate mock user data for development/preview
    const generateMockUser = () => {
        const generateAvatarUrl = (size, seed) => {
            return `https://api.dicebear.com/7.x/avataaars/svg?seed=${seed}&size=${size}`;
        };

        const mockUser = {
            id: Math.floor(Math.random() * 1000) + 1,
            user_login: `user${Math.floor(Math.random() * 1000)}`,
            display_name: `User ${Math.floor(Math.random() * 1000)}`,
            user_email: `user${Math.floor(Math.random() * 1000)}@example.com`,
            user_url: 'https://example.com',
            bio: 'This is a sample bio for demonstration purposes. It shows how the user profile will look with real content.',
            avatar: generateAvatarUrl(150, Math.random()),
            first_name: 'John',
            last_name: 'Doe',
            nickname: 'johndoe',
            user_registered: new Date().toISOString(),
            // Add additional fields that might be expected from the current user API
            roles: ['subscriber'],
            class_list: '',
            // Ensure these fields are present for name formatting
            username: `user${Math.floor(Math.random() * 1000)}`,
            name: `User ${Math.floor(Math.random() * 1000)}`
        };

        return mockUser;
    };

    // If no user is found, use mock data for better editor experience
    if (!user && !loading && !error) {
        const mockUser = generateMockUser();
        setUser(mockUser);
        setLoading(false);
    }

    return { user, loading, error };
};

// Pattern Selection Component
const PatternSelection = ({ onSelectPattern, onBack }) => {
    const blockProps = useBlockProps({
        className: 'wpuf-p-8'
    });

    return (
        <div {...blockProps}>
            {/* Back Button */}
            <div className="wpuf-mb-6">
                    <Button
                        variant="secondary"
                        onClick={onBack}
                        className="wpuf-back-to-layout-btn"
                    >
                        <svg className="wpuf-w-4 wpuf-h-4 wpuf-mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15 19l-7-7 7-7" />
                        </svg>
                        {__('Back to Current Layout', 'wpuf-pro')}
                    </Button>
                </div>

            <div className="wpuf-text-center wpuf-mb-8">
                <Heading level={2} className="wpuf-text-2xl wpuf-font-semibold wpuf-mb-2">
                    {__('Choose a layout for your user profile', 'wpuf-pro')}
                </Heading>
                <Text className="wpuf-text-gray-600">
                    {__('Select a pre-designed layout or start with a blank canvas to create your own.', 'wpuf-pro')}
                </Text>
            </div>

            <div className="wpuf-grid wpuf-grid-cols-1 md:wpuf-grid-cols-2 wpuf-gap-6">
                {LAYOUT_PATTERNS.map((pattern) => (
                    <Card
                        key={pattern.name}
                        className="wpuf-cursor-pointer wpuf-transition-all wpuf-duration-300 wpuf-ease-in-out hover:wpuf-shadow-lg hover:wpuf-scale-105 wpuf-border wpuf-border-gray-200 hover:wpuf-border-blue-300"
                        onClick={() => onSelectPattern(pattern.name, pattern.template)}
                    >
                        <CardMedia className="wpuf-aspect-video wpuf-bg-gray-50 wpuf-flex wpuf-items-center wpuf-justify-center">
                            <img
                                alt={pattern.name}
                                // https://wpuf.test/wp-content/plugins/wpuf-pro/modules/user-directory/images/profile-layout-1.png
                                src={(window.wpufUserDirectory?.asset_url || '') + '/images/profile-' + pattern.name + '.png'}
                                className="wpuf-w-full wpuf-h-full wpuf-object-cover"
                            />
                        </CardMedia>
                        <CardBody className="wpuf-p-4">
                            <Heading level={3} className="wpuf-text-lg wpuf-font-medium wpuf-mb-2">
                                {pattern.title}
                            </Heading>
                        </CardBody>
                    </Card>
                ))}
            </div>
        </div>
    );
};

const Edit = ({ attributes, setAttributes, clientId }) => {
    const {
        block_instance_id,
        componentSpacing,
        hasSelectedPattern,
        selectedPattern
    } = attributes;

    // Get WordPress store selectors and dispatchers
    const profileStateSelect = useSelect((select) => select('wpuf-ud/profile-state'), []);
    const profileStateDispatch = useDispatch('wpuf-ud/profile-state');

    // Get stored states from WordPress store with proper reactivity
    const preservedStates = useSelect((select) => {
        const states = select('wpuf-ud/profile-state').getAllStoredStates();
        return states;
    }, []);

    const storedLayoutNames = useSelect((select) => {
        const names = select('wpuf-ud/profile-state').getStoredLayoutNames();
        return names;
    }, []);

    // Function to store previous state using WordPress store
    const storePreviousState = (currentState) => {
        if (!currentState) {
            return;
        }

        // Store as single "previous_state" in WordPress data store
        try {
            profileStateDispatch.storeLayoutState('previous_state', currentState);
        } catch (error) {
            // Silent error handling
        }

        // Force a re-render by dispatching a dummy action to trigger useSelect updates
        setTimeout(() => {
            // Dispatch a dummy action to trigger store subscription updates
            profileStateDispatch.clearLayoutState('dummy');
            profileStateDispatch.storeLayoutState('dummy', { test: true });
            profileStateDispatch.clearLayoutState('dummy');
        }, 100);
    };



    // Get user data
    const { user, loading, error } = useUserData(clientId);

    // Get dispatch function
    const { replaceInnerBlocks } = useDispatch('core/block-editor');



    // Get inner blocks to detect if any exist
    const innerBlocks = useSelect((select) => {
        return select('core/block-editor').getBlocks(clientId);
    }, [clientId]);

    // Check if Directory block exists on the page
    const hasDirectoryBlock = useSelect((select) => {
        const { getBlocks } = select('core/block-editor');
        const checkBlocks = (blocks) => {
            for (const block of blocks) {
                if (block.name === 'wpuf-ud/directory') {
                    return true;
                }
                if (block.innerBlocks && block.innerBlocks.length > 0) {
                    if (checkBlocks(block.innerBlocks)) {
                        return true;
                    }
                }
            }
            return false;
        };
        return checkBlocks(getBlocks());
    }, []);

    // Confirmation modal state
    const [showConfirmation, setShowConfirmation] = useState(false);
    const [pendingPattern, setPendingPattern] = useState(null);
    const [pendingTemplate, setPendingTemplate] = useState(null);
    const [isSwitchingLayout, setIsSwitchingLayout] = useState(false);
    const [previousPattern, setPreviousPattern] = useState(null);

    // Set block instance ID
    useEffect(() => {
        if (!block_instance_id && clientId) {
            setAttributes({ block_instance_id: clientId });
        }
    }, [block_instance_id, clientId, setAttributes]);

        // Handle pattern selection with selective block replacement
    const handlePatternSelection = (patternName, template) => {
        // Check if we have stored previous state
        const previousState = getStoredStateForLayout('previous_state');

        if (previousState) {
            // Process template with selective block replacement
            const processedTemplate = processTemplateWithState(template, previousState);

            // Apply the processed template
            applyPatternSelection(patternName, processedTemplate);
        } else {
            applyPatternSelection(patternName, template);
        }
    };

    // Apply pattern selection (called after confirmation or when no existing blocks)
    const applyPatternSelection = (patternName, template) => {
        setAttributes({
            hasSelectedPattern: true,
            selectedPattern: patternName
        });

        // Reset switching layout flag
        setIsSwitchingLayout(false);

        // Replace inner blocks with the new template
        if (template && template.length > 0) {
            try {
                const blocks = createBlocksSafely(template);

                if (blocks && blocks.length > 0) {
                    replaceInnerBlocks(clientId, blocks);
                } else {
                    // No blocks created, keeping existing inner blocks
                }
            } catch (error) {
                // Error creating blocks from template
            }
        }
    };

        // Handle confirmation modal actions (only for clearing current layout)
    const handleConfirmPatternChange = () => {
        if (pendingPattern === 'clear') {
            // Store the current pattern before clearing
            if (hasSelectedPattern && selectedPattern) {
                setPreviousPattern(selectedPattern);
            }

            // Clear blocks and show pattern selection
            setAttributes({ hasSelectedPattern: false });
            replaceInnerBlocks(clientId, []);
            setIsSwitchingLayout(true); // Set flag to show back button
        }
        setShowConfirmation(false);
        setPendingPattern(null);
        setPendingTemplate(null);
    };

    const handleCancelPatternChange = () => {
        setShowConfirmation(false);
        setPendingPattern(null);
        setPendingTemplate(null);
    };

    // Handle going back to current layout
    const handleBackToCurrentLayout = () => {
        // Reset switching layout flag
        setIsSwitchingLayout(false);

        // Try to restore the exact previous state first (preserves user customizations)
        const previousState = getStoredStateForLayout('previous_state');

        if (previousState) {
            // Restore the complete previous state including customizations
            const restoreResult = restoreCapturedState(previousState, replaceInnerBlocks, setAttributes);

            if (restoreResult) {
                // Successfully restored previous state with customizations
                return;
            }
        }

        // Fallback: restore just the layout template (loses customizations)
        if (previousPattern) {
            setAttributes({
                hasSelectedPattern: true,
                selectedPattern: previousPattern
            });

            const template = getTemplateByPattern(previousPattern);
            if (template && template.length > 0) {
                try {
                    const blocks = createBlocksSafely(template);
                    if (blocks && blocks.length > 0) {
                        replaceInnerBlocks(clientId, blocks);
                    }
                } catch (error) {
                    // Error creating blocks from template
                }
            }
        }
    };

    // Apply template only when there are no inner blocks (avoid restoring removed blocks)
    useEffect(() => {
        if (!hasSelectedPattern || !selectedPattern || selectedPattern === 'blank' || !clientId) {
            return;
        }
        const hasInner = Array.isArray(innerBlocks) && innerBlocks.length > 0;
        if (hasInner) {
            return;
        }
        const template = getSelectedTemplate();
        if (template && template.length > 0) {
            // Use a small delay to ensure the component is fully rendered
            const timer = setTimeout(() => {
                try {
                    const blocks = createBlocksSafely(template);
                    if (blocks && blocks.length > 0) {
                        replaceInnerBlocks(clientId, blocks);
                    }
                } catch (error) {
                    // Don't replace inner blocks if creation fails
                }
            }, 50);
            return () => clearTimeout(timer);
        }
    }, [selectedPattern, hasSelectedPattern, clientId, replaceInnerBlocks, innerBlocks]);

    // Retry template only if no inner blocks yet and blocks become available
    useEffect(() => {
        if (!hasSelectedPattern || !selectedPattern || selectedPattern === 'blank' || !clientId) {
            return;
        }
        const hasInner = Array.isArray(innerBlocks) && innerBlocks.length > 0;
        if (hasInner) {
            return;
        }
        const template = getSelectedTemplate();
        if (template && template.length > 0 && !areBlocksAvailable()) {
            const retryTimer = setTimeout(() => {
                if (areBlocksAvailable()) {
                    try {
                        const blocks = createBlocksSafely(template);
                        if (blocks && blocks.length > 0) {
                            replaceInnerBlocks(clientId, blocks);
                        }
                    } catch (error) {
                        // Silent fail
                    }
                }
            }, 500);
            return () => clearTimeout(retryTimer);
        }
    }, [selectedPattern, hasSelectedPattern, clientId, replaceInnerBlocks, innerBlocks]);

    // Get template based on selected pattern
    const getSelectedTemplate = () => {
        switch (selectedPattern) {
            case 'layout-1':
                return LAYOUT_1_TEMPLATE;
            case 'layout-2':
                return LAYOUT_2_TEMPLATE;
            case 'layout-3':
                return LAYOUT_3_TEMPLATE;
            case 'blank':
            case 'custom':
            default:
                return [];
        }
    };

    // Get template based on pattern name
    const getTemplateByPattern = (patternName) => {
        switch (patternName) {
            case 'layout-1':
                return LAYOUT_1_TEMPLATE;
            case 'layout-2':
                return LAYOUT_2_TEMPLATE;
            case 'layout-3':
                return LAYOUT_3_TEMPLATE;
            case 'blank':
            case 'custom':
            default:
                return [];
        }
    };

    // Get current user info for permissions
    const currentUserId = window.wpufUserDirectory?.current_user_id || null;
    const canEdit = user && (
        currentUserId === user.id ||
        window.wpufUserDirectory?.current_user_can_manage_options || false
    );

    // Update attributes to provide context to inner blocks
    useEffect(() => {
        if (user) {
            setAttributes({
                userId: user.id,
                userObject: user,
                canEdit: canEdit
            });
        }
    }, [user, canEdit, setAttributes]);

    // Automatically set hasSelectedPattern to true if inner blocks exist but no pattern was selected
    useEffect(() => {
        const hasInnerBlocks = innerBlocks && innerBlocks.length > 0;
        if (hasInnerBlocks && !hasSelectedPattern) {
            setAttributes({
                hasSelectedPattern: true,
                selectedPattern: 'custom' // Mark as custom layout
            });
        }
    }, [innerBlocks, hasSelectedPattern, setAttributes]);

    // Set up block props
    const blockProps = useBlockProps({
        className: 'wpuf-user-profile',
        style: {
            '--wpuf-component-spacing': `${componentSpacing}px`
        }
    });

    // Set up inner blocks props
    const innerBlocksProps = useInnerBlocksProps(
        {
            className: 'wpuf-inner-blocks-container'
        },
        {
            allowedBlocks: getAvailableBlocks(),
            templateLock: false, // Allow users to modify structure
            renderAppender: (selectedPattern === 'blank' || selectedPattern === 'custom') ?
                            InnerBlocks.DefaultBlockAppender : false, // Show appender for blank and custom templates
            __experimentalCaptureToolbars: true
        }
    );

    // Render error state
    const renderError = () => {
        return (
            <Notice status="error" isDismissible={false}>
                <p>{error || __('User not found', 'wpuf-pro')}</p>
            </Notice>
        );
    };

    // Show loading state
    if (loading) {
        return (
            <div {...blockProps}>
                <div className="wpuf-user-profile__loading">
                    <div className="wpuf-loading-content">
                        <Spinner />
                        <p>{__('Loading user profile...', 'wpuf-pro')}</p>
                    </div>
                </div>
            </div>
        );
    }

    // Show error state
    if (error || !user) {
        return (
            <div {...blockProps}>
                {renderError()}
            </div>
        );
    }

    // Show pattern selection if no pattern is selected AND no inner blocks exist
    const hasInnerBlocks = innerBlocks && innerBlocks.length > 0;
    if (!hasSelectedPattern && !hasInnerBlocks && !isSwitchingLayout) {
        return <PatternSelection onSelectPattern={handlePatternSelection} />;
    }

    // Show pattern selection with back button if user clicked "Choose Different Layout"
    if (!hasSelectedPattern && (hasInnerBlocks || isSwitchingLayout)) {
        return <PatternSelection onSelectPattern={handlePatternSelection} onBack={handleBackToCurrentLayout} />;
    }

    return (
        <Fragment>
            <InspectorControls>
                <PanelBody
                    title={__('Layout Settings', 'wpuf-pro')}
                    initialOpen={true}
                >
                    <Button
                        variant="secondary"
                        onClick={() => {
                            // Capture the complete current state before making any changes
                            const currentState = captureCurrentState(
                                clientId,
                                innerBlocks,
                                selectedPattern,
                                attributes
                            );

                            // Store the previous state before making changes
                            storePreviousState(currentState);

                            // Store the current pattern before clearing
                            if (hasSelectedPattern && selectedPattern) {
                                setPreviousPattern(selectedPattern);
                            }

                            // Check if there are existing inner blocks that would be cleared
                            const hasExistingBlocks = innerBlocks && innerBlocks.length > 0;

                            if (hasExistingBlocks) {
                                // Show confirmation modal for clearing blocks
                                setPendingPattern('clear');
                                setPendingTemplate(null);
                                setShowConfirmation(true);
                            } else {
                                // No existing blocks, proceed immediately
                                setAttributes({ hasSelectedPattern: false });
                                replaceInnerBlocks(clientId, []);
                                setIsSwitchingLayout(true); // Set flag to show back button
                            }
                        }}
                        style={{ marginTop: '10px' }}
                    >
                        {__('Choose Different Layout', 'wpuf-pro')}
                    </Button>
                </PanelBody>

            </InspectorControls>

            <div {...blockProps}>
                {/* Dependency warning */}
                {!hasDirectoryBlock && (
                    <Notice status="warning" isDismissible={false}>
                        {__('The User Profile block requires the User Directory block to be present on the same page. Please add the User Directory block to enable full functionality.', 'wpuf-pro')}
                    </Notice>
                )}

                {/* Navigation buttons at the top */}
                {/* <NavigationButtons user={user} canEdit={canEdit} /> */}

                {selectedPattern === 'blank' ? (
                    <div className="wpuf-blank-profile-container">
                        <div className="wpuf-blank-profile-notice">
                            <p>{__('Add blocks from the WPUF category to build your profile layout.', 'wpuf-pro')}</p>
                        </div>
                        <BlockContextProvider value={{
                            'wpuf-ud/userId': user?.id,
                            'wpuf-ud/userObject': user,
                            'wpuf-ud/canEdit': canEdit,
                            'wpuf-ud/containerLayout': selectedPattern || 'default'
                        }}>
                            <div {...innerBlocksProps} />
                        </BlockContextProvider>
                    </div>
                ) : (
                    <BlockContextProvider value={{
                        'wpuf-ud/userId': user?.id,
                        'wpuf-ud/userObject': user,
                        'wpuf-ud/canEdit': canEdit,
                        'wpuf-ud/containerLayout': selectedPattern || 'default'
                    }}>
                        <div {...innerBlocksProps} key={`pattern-${selectedPattern || 'none'}`} />
                    </BlockContextProvider>
                )}
            </div>

            {/* Confirmation Modal */}
            <ConfirmationModal
                isOpen={showConfirmation}
                onConfirm={handleConfirmPatternChange}
                onCancel={handleCancelPatternChange}
                title={__('Switch Layout', 'wpuf-pro')}
                                message={
                    __('Switching the layout may overwrite some of your current customization. Are you sure you want to continue?', 'wpuf-pro')
                }
                confirmText={__('Continue', 'wpuf-pro')}
                cancelText={__('Cancel', 'wpuf-pro')}
            />
        </Fragment>
    );
};

export default Edit;
