import { __, sprintf } from '@wordpress/i18n';

// Helper per normalizzare la struttura width
function normalizeWidth(width) {
    if (typeof width === 'object' && width !== null && 'value' in width && 'unit' in width) {
        return width;
    }
    if (typeof width === 'number') {
        return { value: width, unit: '%' };
    }
    return { value: 100, unit: '%' };
}

import { registerBlockType } from '@wordpress/blocks';
import {
    InspectorControls,
    MediaUpload,
    MediaUploadCheck,
    useBlockProps,
    PanelColorSettings,
    RichText,
    AlignmentToolbar,
    useBlockEditContext,
    BlockControls
} from '@wordpress/block-editor';
import {
    Button,
    PanelBody,
    PanelRow,
    RangeControl,
    TextControl,
    SelectControl,
    Notice,
    __experimentalBoxControl as BoxControl,
    __experimentalToolsPanel as ToolsPanel,
    __experimentalToolsPanelItem as ToolsPanelItem,
    __experimentalUnitControl as UnitControl,
    Flex,
    FlexItem,
    RadioControl,
    ToolbarGroup,
    ToolbarButton
} from '@wordpress/components';
import { useState, useEffect, useRef } from '@wordpress/element';
import { useSelect, useDispatch } from '@wordpress/data';
import { ColorPalette, BaseControl } from '@wordpress/components';
import { TextControls } from './text-controls';
import { updateLayer, removeLayer, addLayer, addTextLayer } from './layer-manager';
import { FreeFitLayer } from './free-fit-layer';
import { FreeFitControls } from './free-fit-controls';
import { FreeFitTextLayer } from './free-fit-text-layer';

const INITIAL_OFFSET = 20;
const RESPONSIVE_THRESHOLD = 520;

const getLayerDefaultLabel = (layer, index) =>
    layer.type === 'text'
        ? sprintf(__('Text Layer %d', 'multilayer-image-and-text-block'), index + 1)
        : sprintf(__('Image Layer %d', 'multilayer-image-and-text-block'), index + 1);

const getLayerDisplayLabel = (layer, index) => {
    const customLabel = (layer.label || '').trim();
    if (customLabel) {
        return customLabel;
    }
    return getLayerDefaultLabel(layer, index);
};

const SAMPLE_IMAGE_PLACEHOLDER = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(
    `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1200 800">
        <defs>
            <linearGradient id="mlitb-demo-gradient" x1="0" y1="0" x2="1" y2="1">
                <stop offset="0%" stop-color="#084887" />
                <stop offset="100%" stop-color="#2a9d8f" />
            </linearGradient>
            <radialGradient id="mlitb-highlight" cx="0.8" cy="0.3" r="0.6">
                <stop offset="0%" stop-color="rgba(255,255,255,0.35)" />
                <stop offset="100%" stop-color="rgba(255,255,255,0)" />
            </radialGradient>
        </defs>
        <rect width="1200" height="800" fill="url(#mlitb-demo-gradient)" />
        <circle cx="960" cy="240" r="180" fill="url(#mlitb-highlight)" />
        <circle cx="1020" cy="560" r="140" fill="rgba(255,255,255,0.10)" />
        <text x="720" y="320" font-family="'Segoe UI', Arial, sans-serif" font-size="84" fill="rgba(255,255,255,0.18)" font-weight="700">Layered</text>
        <text x="760" y="420" font-family="'Segoe UI', Arial, sans-serif" font-size="84" fill="rgba(255,255,255,0.18)" font-weight="700">Design</text>
    </svg>`
)} `;

// Componente wrapper per i layer di testo
const TextLayerWrapper = ({ layer, index, onUpdate, onSelect, isSelected, blockSelected, showRealOrder = false }) => {
    const layerIsSelected = blockSelected && isSelected;
    const selectionBoost = layerIsSelected && !showRealOrder ? 100 : 0;
    const displayLabel = getLayerDisplayLabel(layer, index);
    const textBorderColor = layerIsSelected
        ? 'rgba(26, 115, 232, 0.7)'
        : 'rgba(26, 115, 232, 0.35)';

    const layerClassNames = [
        'multi-layer-block__layer',
        'multi-layer-block__text-layer',
        layerIsSelected ? 'is-selected' : '',
        layer.customClassName || ''
    ].filter(Boolean).join(' ');

    const handlePointerDown = (event) => {
        event.stopPropagation();
        onSelect(index, event);
    };

    return (
        <div
            className={layerClassNames}
            data-fit-mode={layer.fitMode}
            onMouseDown={handlePointerDown}
            onTouchStart={handlePointerDown}
            style={{
                position: 'absolute',
                width: (() => {
                    const w = normalizeWidth(layer.size?.width);
                    return `${w.value}${w.unit}`;
                })(),
                ...(layer.fitMode !== 'free' && {
                    top: `${layer.position?.y?.value || 0}${layer.position?.y?.unit || '%'}`,
                    left: `${layer.position?.x?.value || 0}${layer.position?.x?.unit || '%'}`,
                }),
                zIndex: (layer.zIndex || 0) + selectionBoost,
                opacity: (layer.opacity || 100) / 100,
                height: 'auto',
                boxSizing: 'border-box',
                cursor: 'text'
            }}
        >
            {layerIsSelected && (
                <span className="mlitb-layer-badge mlitb-layer-badge--text">{displayLabel}</span>
            )}
            <div
                className="mlitb-text-content"
                style={{
                    backgroundColor: layer.color?.background || 'transparent',
                    padding: `${layer.padding?.top ?? 0}px ${layer.padding?.right ?? 0}px ${layer.padding?.bottom ?? 0}px ${layer.padding?.left ?? 0}px`,
                    boxSizing: 'border-box',
                    width: '100%',
                    border: `1px dashed ${textBorderColor}`
                }}
            >
                <FreeFitTextLayer
                    key={layer.id}
                    layerIndex={index}
                    content={layer.content}
                    position={layer.position}
                    size={layer.size}
                    typography={layer.typography}
                    color={layer.color}
                    onUpdate={(updates) => onUpdate(index, updates)}
                    isSelected={layerIsSelected}
                />
            </div>
        </div>
    );
};

// Componente wrapper per i layer immagine
const ImageLayerWrapper = ({ layer, index, onUpdate, onSelect, isSelected, blockSelected, showRealOrder = false }) => {
    const layerIsSelected = blockSelected && isSelected;
    const selectionBoost = layerIsSelected && !showRealOrder ? 100 : 0;
    const handleClick = (event) => {
        event.stopPropagation();
        onSelect(index, event);
    };

    return (
        <div
            className={`image-layer-wrapper${layerIsSelected ? ' is-selected' : ''}`}
            data-layer-id={layer.id}
            data-fit-mode={layer.objectFit === 'free' ? 'free' : undefined}
            onMouseDown={handleClick}
            onTouchStart={handleClick}
            onKeyDown={(event) => {
                if (event.key === 'Enter' || event.key === ' ') {
                    event.preventDefault();
                    onSelect(index, event);
                }
            }}
            role="presentation"
            style={{
                position: 'absolute',
                width: `${layer.size?.width?.value || 100}${layer.size?.width?.unit || '%'}`,
                height: `${layer.size?.height?.value || 100}${layer.size?.height?.unit || '%'}`,
                top: layer.objectFit === 'free' ? undefined : `${layer.position?.y?.value || 0}${layer.position?.y?.unit || '%'}`,
                left: layer.objectFit === 'free' ? undefined : `${layer.position?.x?.value || 0}${layer.position?.x?.unit || '%'}`,
                zIndex: (layer.zIndex || 0) + selectionBoost,
                opacity: (layer.opacity || 100) / 100,
                cursor: 'pointer'
            }}
            tabIndex={0}
        >
            {layer.objectFit === 'free' ? (
                <FreeFitLayer
                    key={layer.id}
                    imageUrl={layer.imageUrl}
                    layerIndex={index}
                    position={layer.position}
                    size={layer.size}
                    onUpdate={(updates) => onUpdate(index, updates)}
                    isSelected={layerIsSelected}
                />
            ) : (
                <div
                    className="image-layer-wrapper__content"
                    style={{
                        width: '100%',
                        height: '100%',
                        overflow: 'hidden',
                        position: 'relative'
                    }}
                >
                    <img
                        src={layer.imageUrl}
                        alt={layer.imageAlt || ''}
                        draggable={false}
                        style={{
                            width: '100%',
                            height: '100%',
                            objectFit: layer.objectFit || 'cover',
                            objectPosition: 'center',
                            display: 'block',
                            pointerEvents: 'none'
                        }}
                    />
                    <span className="image-layer-wrapper__overlay" aria-hidden="true"></span>
                </div>
            )}
        </div>
    );
};

const iconLayers = () => (
    <svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" width="24" height="24">
        <path d="M12 2L2 7l10 5 10-5-10-5zM2 17l10 5 10-5M2 12l10 5 10-5" fill="none" stroke="currentColor" strokeWidth="2"/>
    </svg>
);

registerBlockType('nick-digital-plugins/multilayer-image-and-text-block', {
    title: __('MultiLayer Image and Text', 'multilayer-image-and-text-block'),
    description: __('Create beautiful layered compositions with images and text. Perfect for hero sections, banners, and creative layouts.', 'multilayer-image-and-text-block'),
    icon: iconLayers,
    category: 'design',
    supports: {
        align: true,
        html: false,
        color: {
            background: true,
            text: true,
            gradients: true
        }
    },
    attributes: {
        layers: {
            type: 'array',
            default: []
        },
        containerHeight: {
            type: 'number',
            default: 500
        },
        containerWidthMode: {
            type: 'string',
            default: 'full'
        },
        containerWidthPx: {
            type: 'number',
            default: 800
        },
        containerAlignment: {
            type: 'string',
            default: 'left'
        },
        style: {
            type: 'object',
            default: {
                color: {
                    background: '',
                    text: '',
                    gradient: ''
                },
                spacing: {
                    padding: {
                        top: '0',
                        right: '0',
                        bottom: '0',
                        left: '0'
                    },
                    margin: {
                        top: '0',
                        right: '0',
                        bottom: '0',
                        left: '0'
                    }
                }
            }
        },
        fixedBackgroundColor: {
            type: 'string',
            default: ''
        },
        currentPreset: {
            type: 'string',
            default: ''
        },
        isInitialLoad: {
            type: 'boolean',
            default: true
        }
    },

    edit: function (props) {
        const [forceUpdate, setForceUpdate] = useState(0); // Stato per forzare il re-render
        const [presetNotice, setPresetNotice] = useState(null);
        const [isQuickHelpOpen, setQuickHelpOpen] = useState(false);
        const presetNoticeTimer = useRef(null);
        const { attributes, setAttributes } = props;
        const { layers = [], containerHeight, containerWidthMode, containerWidthPx, containerAlignment, style, fixedBackgroundColor = '', currentPreset = '', isInitialLoad = true } = attributes;

        // Auto-load sample layout on first insert
        useEffect(() => {
            if (isInitialLoad && layers.length === 0) {
                const timestamp = Date.now();
                const sampleLayers = [
                    {
                        id: timestamp,
                        type: 'image',
                        imageUrl: window.mlitbAssets?.heroDemoUrl || '',
                        imageAlt: 'Stunning mountain landscape at sunset',
                        objectFit: 'cover',
                        position: { x: { value: 0, unit: '%' }, y: { value: 0, unit: '%' } },
                        size: { width: { value: 100, unit: '%' }, height: { value: 100, unit: '%' } },
                        zIndex: 0,
                        opacity: 100
                    },
                    {
                        id: timestamp + 1,
                        type: 'image',
                        imageUrl: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjQwMCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9ImciIHgxPSIwJSIgeTE9IjAlIiB4Mj0iMTAwJSIgeTI9IjEwMCUiPjxzdG9wIG9mZnNldD0iMCUiIHN0b3AtY29sb3I9IiNmZjZiNmIiIHN0b3Atb3BhY2l0eT0iMC40Ii8+PHN0b3Agb2Zmc2V0PSI1MCUiIHN0b3AtY29sb3I9IiNmZWNhNTciIHN0b3Atb3BhY2l0eT0iMC4yIi8+PHN0b3Agb2Zmc2V0PSIxMDAlIiBzdG9wLWNvbG9yPSIjNDhkYmZiIiBzdG9wLW9wYWNpdHk9IjAuMiIvPjwvbGluZWFyR3JhZGllbnQ+PC9kZWZzPjxjaXJjbGUgY3g9IjIwMCIgY3k9IjIwMCIgcj0iMTgwIiBmaWxsPSJ1cmwoI2cpIi8+PC9zdmc+',
                        imageAlt: 'Decorative gradient circle',
                        objectFit: 'contain',
                        position: { x: { value: 38, unit: '%' }, y: { value: 18, unit: '%' } },
                        size: { width: { value: 24, unit: '%' }, height: { value: 20, unit: '%' } },
                        zIndex: 1,
                        opacity: 80
                    },
                    {
                        id: timestamp + 2,
                        type: 'image',
                        imageUrl: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNDAwIiBoZWlnaHQ9IjQwMCIgdmlld0JveD0iMCAwIDQwMCA0MDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTgwIDIwMEM4MCAxMzEuOTcxIDEzMS45NzEgODAgMjAwIDgwQzI2OC4wMjkgODAgMzIwIDEzMS45NzEgMzIwIDIwMC4wMDFDMzIwIDI2OC4wMyAyNjguMDI5IDMyMCAyMDAgMzIwQzEzMS45NzEgMzIwIDgwIDI2OC4wMjkgODAgMjAwWiIgZmlsbD0idXJsKCNwYWludDBfcmFkaWFsXzEiLz48ZGVmcz48cmFkaWFsR3JhZGllbnQgaWQ9InBhaW50MF9yYWRpYWxfMSIgY3g9IjAiIGN5PSIwIiByPSIxIiBncmFkaWVudFVuaXRzPSJ1c2VyU3BhY2VPblVzZSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmOThCMCIgc3RvcC1vcGFjaXR5PSIwLjciLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiM2NzIwRkYiIHN0b3Atb3BhY2l0eT0iMC4zIi8+PC9yYWRpYWxHcmFkaWVudD48L2RlZnM+PC9zdmc+',
                        imageAlt: 'Glass orb accent',
                        objectFit: 'contain',
                        position: { x: { value: 2, unit: '%' }, y: { value: 55, unit: '%' } },
                        size: { width: { value: 22, unit: '%' }, height: { value: 22, unit: '%' } },
                        zIndex: 2,
                        opacity: 85
                    },
                    {
                        id: timestamp + 3,
                        type: 'image',
                        imageUrl: 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMzAwIiBoZWlnaHQ9IjMwMCIgdmlld0JveD0iMCAwIDMwMCAzMDAiIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+PHBhdGggZD0iTTE1MCAyMEMxODAgNjAgMjIwIDEwMCAyMjAgMTUwQzIyMCAyMDAgMTgwIDI2MCAxNTAgMjgwQzEyMCAyNjAgODAgMjAwIDgwIDE1MEM4MCAxMDAgMTIwIDYwIDE1MCAyMFoiIHN0cm9rZT0idXJsKCNwYWludDFfbGluZWFyXzEpIiBzdHJva2Utd2lkdGg9IjQiIGZpbGw9Im5vbmUiLz48ZGVmcz48bGluZWFyR3JhZGllbnQgaWQ9InBhaW50MV9saW5lYXJfMSIgeDE9IjAlIiB5MT0iMCUiIHgyPSIxMDAlIiB5Mj0iMTAwJSI+PHN0b3Agb2Zmc2V0PSIwJSIgc3RvcC1jb2xvcj0iI2ZmZmZmZiIgc3RvcC1vcGFjaXR5PSIwLjgiLz48c3RvcCBvZmZzZXQ9IjEwMCUiIHN0b3AtY29sb3I9IiNmZmZmZmYiIHN0b3Atb3BhY2l0eT0iMC4yIi8+PC9saW5lYXJHcmFkaWVudD48L2RlZnM+PC9zdmc+',
                        imageAlt: 'Leaf outline accent',
                        objectFit: 'contain',
                        position: { x: { value: 78, unit: '%' }, y: { value: 20, unit: '%' } },
                        size: { width: { value: 18, unit: '%' }, height: { value: 20, unit: '%' } },
                        zIndex: 3,
                        opacity: 70
                    },
                    {
                        id: timestamp + 4,
                        type: 'text',
                        content: 'Design Without Limits',
                        position: { x: { value: 10, unit: '%' }, y: { value: 28, unit: '%' } },
                        size: { width: { value: 80, unit: '%' }, height: { value: 15, unit: '%' } },
                        zIndex: 4,
                        typography: { fontSize: 'clamp(36px, 5vw, 64px)', fontWeight: 'bold', textAlign: 'center', lineHeight: '1.1', letterSpacing: '-0.02em', textTransform: 'none', fontFamily: '' },
                        color: { text: '#ffffff', background: '' },
                        padding: { top: 0, right: 0, bottom: 0, left: 0 },
                        opacity: 100
                    },
                    {
                        id: timestamp + 5,
                        type: 'text',
                        content: 'Stack images, text and shapes. Build stunning layered layouts in minutes.',
                        position: { x: { value: 15, unit: '%' }, y: { value: 48, unit: '%' } },
                        size: { width: { value: 70, unit: '%' }, height: { value: 12, unit: '%' } },
                        zIndex: 5,
                        typography: { fontSize: 'clamp(14px, 2vw, 20px)', textAlign: 'center', lineHeight: '1.6', letterSpacing: 'normal', textTransform: 'none', fontFamily: '' },
                        color: { text: '#ffffff', background: 'rgba(0,0,0,0.35)' },
                        padding: { top: 10, right: 20, bottom: 10, left: 20 },
                        opacity: 100
                    },
                    {
                        id: timestamp + 6,
                        type: 'text',
                        content: 'Start Creating →',
                        position: { x: { value: 30, unit: '%' }, y: { value: 66, unit: '%' } },
                        size: { width: { value: 40, unit: '%' }, height: { value: 10, unit: '%' } },
                        zIndex: 6,
                        typography: { fontSize: 'clamp(14px, 2vw, 17px)', fontWeight: '600', textAlign: 'center', lineHeight: '1.4', letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: '' },
                        color: { text: '#1a1a2e', background: '#ffffff' },
                        padding: { top: 14, right: 28, bottom: 14, left: 28 },
                        opacity: 100
                    }
                ];
                setAttributes({
                    layers: sampleLayers,
                    containerHeight: 520,
                    containerWidthMode: 'full',
                    containerAlignment: 'center',
                    isInitialLoad: false
                });
            }
        }, [isInitialLoad, layers.length, setAttributes]);

        // Applichiamo la larghezza/alignment direttamente all'involucro del blocco
        const blockStyle = {
            width: '100%',
            maxWidth: '100%',
            boxSizing: 'border-box'
        };

        if (style?.color?.background) {
            blockStyle['--general-background-color'] = style.color.background;
        }

        if (containerWidthMode === 'fixed' && fixedBackgroundColor) {
            blockStyle['--container-background-color'] = fixedBackgroundColor;
        }

        const blockProps = useBlockProps({
            style: blockStyle,
            'data-width-mode': containerWidthMode || 'full',
            'data-width-px': containerWidthMode === 'fixed' ? (containerWidthPx || '') : null,
            'data-alignment': containerAlignment || 'center'
        });

        // Funzione per gestire il cambio di altezza del contenitore
        const handleHeightChange = (newHeight) => {
            setAttributes({ containerHeight: newHeight });
        };

        const handleUpdateLayer = (index, updates) => {
            const newLayers = [...attributes.layers];

            // Normalizza la struttura della width se serve
            if (updates.size && typeof updates.size.width === 'number') {
                updates.size = {
                    ...updates.size,
                    width: { value: updates.size.width, unit: (newLayers[index].size?.width?.unit || '%') }
                };
            }

            // Aggiorniamo il layer con i nuovi valori
            newLayers[index] = {
                ...newLayers[index],
                ...updates
            };

            console.log('Updating layer', index, 'with', updates);
            console.log('Updated layer:', newLayers[index]);

            setAttributes({ layers: newLayers });
        };

        const handleRemoveLayer = (index) => {
            const newLayers = removeLayer(layers, index);
            setAttributes({ layers: newLayers });
        };

        const handleAddLayer = (type = 'image') => {
            const newLayers = addLayer(layers, type);
            const newIndex = newLayers.length - 1;
            setAttributes({ layers: newLayers });
            setSelectedLayerIndex(newIndex);
            setActivePanelIndex(newIndex);
            selectBlock(props.clientId);
        };

        const createDefaultLayer = (type) => {
            const defaults = addLayer([], type);
            return { ...defaults[defaults.length - 1] };
        };

        const handleLoadSampleLayout = () => {
            if (layers.length > 0) {
                const confirmReplace = window.confirm(
                    __('Loading the sample layout will replace existing layers. Continue?', 'multilayer-image-and-text-block')
                );
                if (!confirmReplace) {
                    return;
                }
            }

            const timestamp = Date.now();
            const baseImage = createDefaultLayer('image');
            const baseTextPrimary = createDefaultLayer('text');
            const baseTextSecondary = createDefaultLayer('text');

            const imageLayer = {
                ...baseImage,
                id: timestamp,
                imageUrl: SAMPLE_IMAGE_PLACEHOLDER,
                imageAlt: __('Sample background illustration', 'multilayer-image-and-text-block'),
                objectFit: 'cover',
                position: {
                    x: { value: 0, unit: '%' },
                    y: { value: 0, unit: '%' }
                },
                size: {
                    width: { value: 100, unit: '%' },
                    height: { value: 100, unit: '%' }
                },
                zIndex: 0,
                opacity: 100
            };

            const headingLayer = {
                ...baseTextPrimary,
                id: timestamp + 1,
                content: __('Layer your story with style', 'multilayer-image-and-text-block'),
                customClassName: 'mlitb-demo-heading',
                position: {
                    x: { value: 8, unit: '%' },
                    y: { value: 22, unit: '%' }
                },
                size: {
                    width: { value: 40, unit: '%' },
                    height: baseTextPrimary.size?.height || { value: 100, unit: '%' }
                },
                typography: {
                    ...baseTextPrimary.typography,
                    fontSize: 'clamp(28px, 3.5vw, 36px)',
                    fontWeight: '700',
                    lineHeight: '1.15',
                    textAlign: 'left'
                },
                color: {
                    ...baseTextPrimary.color,
                    text: '#ffffff',
                    background: 'rgba(8, 24, 46, 0.75)'
                },
                padding: {
                    top: 24,
                    right: 28,
                    bottom: 24,
                    left: 28
                },
                zIndex: 1,
                opacity: 100
            };

            const bodyLayer = {
                ...baseTextSecondary,
                id: timestamp + 2,
                content: __('Stack imagery, text, and CTAs to craft high-impact hero sections in minutes. Adjust each layer freely to fit your brand.', 'multilayer-image-and-text-block'),
                customClassName: 'mlitb-demo-body',
                position: {
                    x: { value: 8, unit: '%' },
                    y: { value: 44, unit: '%' }
                },
                size: {
                    width: { value: 36, unit: '%' },
                    height: baseTextSecondary.size?.height || { value: 100, unit: '%' }
                },
                typography: {
                    ...baseTextSecondary.typography,
                    fontSize: 'clamp(15px, 2.2vw, 17px)',
                    lineHeight: '1.6',
                    textAlign: 'left'
                },
                color: {
                    ...baseTextSecondary.color,
                    text: '#ffffff',
                    background: 'rgba(8, 24, 46, 0.55)'
                },
                padding: {
                    top: 16,
                    right: 22,
                    bottom: 16,
                    left: 22
                },
                zIndex: 2,
                opacity: 100
            };

            const ctaLayer = {
                ...baseTextSecondary,
                id: timestamp + 3,
                content: __('Explore layouts →', 'multilayer-image-and-text-block'),
                customClassName: 'mlitb-demo-cta',
                position: {
                    x: { value: 8, unit: '%' },
                    y: { value: 66, unit: '%' }
                },
                size: {
                    width: { value: 24, unit: '%' },
                    height: baseTextSecondary.size?.height || { value: 100, unit: '%' }
                },
                typography: {
                    ...baseTextSecondary.typography,
                    fontSize: 'clamp(13px, 2vw, 15px)',
                    fontWeight: '600',
                    textAlign: 'center',
                    textTransform: 'uppercase',
                    letterSpacing: '0.08em'
                },
                color: {
                    ...baseTextSecondary.color,
                    text: '#08182e',
                    background: 'rgba(255,255,255,0.95)'
                },
                padding: {
                    top: 12,
                    right: 26,
                    bottom: 12,
                    left: 26
                },
                zIndex: 3,
                opacity: 100,
                align: 'center'
            };

            setAttributes({
                layers: [imageLayer, headingLayer, bodyLayer, ctaLayer],
                containerHeight: 520,
                containerWidthMode: 'full',
                currentPreset: 'hero'
            });

            showPresetNotice('hero');
        };

        const handleLoadCompactLayout = () => {
            if (layers.length > 0) {
                const confirmReplace = window.confirm(
                    __('Loading the compact demo will replace existing layers. Continue?', 'multilayer-image-and-text-block')
                );
                if (!confirmReplace) {
                    return;
                }
            }

            const timestamp = Date.now();
            const baseImage = createDefaultLayer('image');
            const baseTextPrimary = createDefaultLayer('text');
            const baseTextSecondary = createDefaultLayer('text');

            const imageLayer = {
                ...baseImage,
                id: timestamp,
                imageUrl: SAMPLE_IMAGE_PLACEHOLDER,
                imageAlt: __('Sample background illustration', 'multilayer-image-and-text-block'),
                objectFit: 'cover',
                position: {
                    x: { value: 0, unit: '%' },
                    y: { value: 0, unit: '%' }
                },
                size: {
                    width: { value: 100, unit: '%' },
                    height: { value: 100, unit: '%' }
                },
                zIndex: 0,
                opacity: 100
            };

            const headingLayer = {
                ...baseTextPrimary,
                id: timestamp + 1,
                content: __('Bring ideas to life faster', 'multilayer-image-and-text-block'),
                customClassName: 'mlitb-demo-heading mlitb-demo-heading--compact',
                position: {
                    x: { value: 6, unit: '%' },
                    y: { value: 18, unit: '%' }
                },
                size: {
                    width: { value: 72, unit: '%' },
                    height: baseTextPrimary.size?.height || { value: 100, unit: '%' }
                },
                typography: {
                    ...baseTextPrimary.typography,
                    fontSize: 'clamp(22px, 4vw, 32px)',
                    fontWeight: '700',
                    lineHeight: '1.25',
                    textAlign: 'center'
                },
                color: {
                    ...baseTextPrimary.color,
                    text: '#ffffff',
                    background: 'rgba(8, 24, 46, 0.75)'
                },
                padding: {
                    top: 18,
                    right: 22,
                    bottom: 18,
                    left: 22
                },
                zIndex: 1,
                opacity: 100,
                align: 'center'
            };

            const bodyLayer = {
                ...baseTextSecondary,
                id: timestamp + 2,
                content: __('Perfect for columns and sidebars: stack image, text, and CTAs with pixel-perfect control.', 'multilayer-image-and-text-block'),
                customClassName: 'mlitb-demo-body mlitb-demo-body--compact',
                position: {
                    x: { value: 8, unit: '%' },
                    y: { value: 44, unit: '%' }
                },
                size: {
                    width: { value: 84, unit: '%' },
                    height: baseTextSecondary.size?.height || { value: 100, unit: '%' }
                },
                typography: {
                    ...baseTextSecondary.typography,
                    fontSize: 'clamp(14px, 2.6vw, 16px)',
                    lineHeight: '1.6',
                    textAlign: 'center'
                },
                color: {
                    ...baseTextSecondary.color,
                    text: '#ffffff',
                    background: 'rgba(8, 24, 46, 0.65)'
                },
                padding: {
                    top: 16,
                    right: 20,
                    bottom: 16,
                    left: 20
                },
                zIndex: 2,
                opacity: 100,
                align: 'center'
            };

            const ctaLayer = {
                ...baseTextSecondary,
                id: timestamp + 3,
                content: __('See compact presets →', 'multilayer-image-and-text-block'),
                customClassName: 'mlitb-demo-cta mlitb-demo-cta--compact',
                position: {
                    x: { value: 20, unit: '%' },
                    y: { value: 68, unit: '%' }
                },
                size: {
                    width: { value: 60, unit: '%' },
                    height: baseTextSecondary.size?.height || { value: 100, unit: '%' }
                },
                typography: {
                    ...baseTextSecondary.typography,
                    fontSize: 'clamp(13px, 2.4vw, 15px)',
                    fontWeight: '600',
                    textAlign: 'center',
                    textTransform: 'uppercase',
                    letterSpacing: '0.08em'
                },
                color: {
                    ...baseTextSecondary.color,
                    text: '#08182e',
                    background: 'rgba(255,255,255,0.95)'
                },
                padding: {
                    top: 12,
                    right: 18,
                    bottom: 12,
                    left: 18
                },
                zIndex: 3,
                opacity: 100,
                align: 'center'
            };

            setAttributes({
                layers: [imageLayer, headingLayer, bodyLayer, ctaLayer],
                containerHeight: 520,
                containerWidthMode: 'full',
                currentPreset: 'compact'
            });

            showPresetNotice('compact');
        };

        const showPresetNotice = (presetKey) => {
            if (presetNoticeTimer.current) {
                clearTimeout(presetNoticeTimer.current);
            }

            const headline = presetKey === 'compact'
                ? __('Compact preset loaded', 'multilayer-image-and-text-block')
                : __('Hero preset loaded', 'multilayer-image-and-text-block');

            const copy = __('Customize layers to make it yours.', 'multilayer-image-and-text-block');

            setPresetNotice({ preset: presetKey, headline, copy });

            presetNoticeTimer.current = setTimeout(() => {
                setPresetNotice(null);
            }, 2600);
        };

        useEffect(() => {
            return () => {
                if (presetNoticeTimer.current) {
                    clearTimeout(presetNoticeTimer.current);
                }
            };
        }, []);

        const handleAddTextLayer = () => {
            const newLayers = addLayer(layers, 'text');
            const newIndex = newLayers.length - 1;
            setAttributes({ layers: newLayers });
            setSelectedLayerIndex(newIndex);
            setActivePanelIndex(newIndex);
            selectBlock(props.clientId);
        };

        const [selectedLayerIndex, setSelectedLayerIndex] = useState(null);
        const [activePanelIndex, setActivePanelIndex] = useState(null);
        const [showRealOrder, setShowRealOrder] = useState(false);
        const normalizedLayers = Array.isArray(layers) ? layers : [];
        const blockSelected = useSelect(
            (select) => select('core/block-editor').isBlockSelected(props.clientId),
            [props.clientId]
        );
        const { selectBlock } = useDispatch('core/block-editor');
        const wasBlockSelected = useRef(blockSelected);
        const panelRefs = useRef([]);

        const reorderLayersArray = (list, from, to) => {
            const updated = [...list];
            const [moved] = updated.splice(from, 1);
            updated.splice(to, 0, moved);
            return updated;
        };

        const handleTogglePanel = (index, nextOpen) => {
            setActivePanelIndex(nextOpen ? index : null);
            if (nextOpen) {
                setSelectedLayerIndex(index);
                selectBlock(props.clientId);
            }
        };

        const handleMoveLayer = (index, direction) => {
            if (!Array.isArray(normalizedLayers) || normalizedLayers.length < 2) {
                return;
            }

            const lastIndex = normalizedLayers.length - 1;
            const targetIndex = direction === 'forward'
                ? Math.min(lastIndex, index + 1)
                : Math.max(0, index - 1);

            if (targetIndex === index) {
                return;
            }

            const reordered = reorderLayersArray(normalizedLayers, index, targetIndex).map((layer, position) => ({
                ...layer,
                zIndex: position
            }));

            let nextActivePanel = activePanelIndex;

            if (activePanelIndex !== null) {
                if (activePanelIndex === index) {
                    nextActivePanel = targetIndex;
                } else if (direction === 'forward') {
                    if (activePanelIndex > index && activePanelIndex <= targetIndex) {
                        nextActivePanel = activePanelIndex - 1;
                    }
                } else if (direction === 'backward') {
                    if (activePanelIndex < index && activePanelIndex >= targetIndex) {
                        nextActivePanel = activePanelIndex + 1;
                    }
                }
            }

            setAttributes({ layers: reordered });
            setSelectedLayerIndex(targetIndex);
            setActivePanelIndex(nextActivePanel);
            selectBlock(props.clientId);
        };

        const handleSelectLayer = (index, event, { openPanel = false } = {}) => {
            event?.stopPropagation?.();
            setSelectedLayerIndex(index);
            if (openPanel) {
                setActivePanelIndex(index);
            }
            selectBlock(props.clientId);
        };

        useEffect(() => {
            if (!blockSelected && wasBlockSelected.current) {
                setSelectedLayerIndex(null);
                setActivePanelIndex(null);
            }
            wasBlockSelected.current = blockSelected;
        }, [blockSelected]);

        useEffect(() => {
            if (normalizedLayers.length < panelRefs.current.length) {
                panelRefs.current = panelRefs.current.slice(0, normalizedLayers.length);
            }
        }, [normalizedLayers.length]);

        useEffect(() => {
            if (activePanelIndex !== null) {
                const targetPanel = panelRefs.current[activePanelIndex];
                if (targetPanel && typeof targetPanel.scrollIntoView === 'function') {
                    targetPanel.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
                }
            }
        }, [activePanelIndex]);

        const handleRenameLayer = (index, value) => {
            const newLayers = updateLayer(normalizedLayers, index, { label: value });
            setAttributes({ layers: newLayers });
        };

        const selectedLayer = selectedLayerIndex !== null ? normalizedLayers[selectedLayerIndex] : null;
        const selectedLayerLabel = selectedLayer
            ? getLayerDisplayLabel(selectedLayer, selectedLayerIndex)
            : '';
        const editingMessage = __('Editing focus only (layer order unchanged)', 'multilayer-image-and-text-block');
        const fitHelperMessage = (() => {
            if (!selectedLayer || selectedLayer.type !== 'image') {
                return '';
            }
            if (selectedLayer.objectFit === 'free') {
                return __('Free fit preserves exact size and position across editor and front-end.', 'multilayer-image-and-text-block');
            }
            return __('Cover / contain adapts to the container size. Use Free fit for pixel-perfect placement.', 'multilayer-image-and-text-block');
        })();
        const toastBodyMessage = (() => {
            const parts = [];
            if (!showRealOrder && editingMessage) {
                parts.push(editingMessage);
            }
            if (fitHelperMessage) {
                parts.push(fitHelperMessage);
            }
            return parts.join(' · ');
        })();

        const handleObjectFitChange = (index, newFit) => {
            const layer = attributes.layers[index];
            const updates = { objectFit: newFit };

            const getDefaultPosition = (fit) =>
                fit === 'free'
                    ? {
                        x: { value: 0, unit: 'px' },
                        y: { value: 0, unit: 'px' }
                    }
                    : {
                        x: { value: 0, unit: '%' },
                        y: { value: 0, unit: '%' }
                    };

            console.log('handleObjectFitChange - layer:', layer);
            console.log('handleObjectFitChange - newFit:', newFit);

            if (newFit === 'free') {
                if (layer.naturalSize) {
                    console.log('Reset free fit to natural size:', layer.naturalSize);
                    updates.size = {
                        width: { value: layer.naturalSize.width, unit: 'px' },
                        height: { value: layer.naturalSize.height, unit: 'px' }
                    };
                } else {
                    console.log('Reset free fit to default size (800x400)');
                    updates.size = {
                        width: { value: 800, unit: 'px' },
                        height: { value: 400, unit: 'px' }
                    };
                }

                // Forziamo anche la posizione di partenza
                updates.position = getDefaultPosition('free');
            } else {
                // Se stiamo uscendo da free, salviamo le dimensioni correnti per ripristinarle in futuro
                if (layer.objectFit === 'free') {
                    updates.freeFitSize = { ...layer.size };
                    console.log('Stored free fit size snapshot:', updates.freeFitSize);
                }

                // Tutti gli altri fit lavorano con dimensioni percentuali e posizione centrata
                updates.size = {
                    width: { value: 100, unit: '%' },
                    height: { value: 100, unit: '%' }
                };
                updates.position = getDefaultPosition(newFit);
            }

            console.log('Object fit change - applied size:', updates.size);
            console.log('Object fit change - applied position:', updates.position);

            const newLayers = updateLayer(layers, index, updates);
            setAttributes({ layers: newLayers });
        };

        const handleMediaSelect = (media, index) => {
            console.log('Selected media:', media);

            // Verifichiamo se è un SVG
            const isSvg = media.url && media.url.toLowerCase().endsWith('.svg');

            // Se è un SVG, avvisiamo l'utente che non è supportato
            if (isSvg) {
                window.alert('Attenzione: gli SVG non sono supportati nella versione attuale.\n\nUtilizzare un\'immagine in formato JPG o PNG.');
                return; // Non procediamo con l'aggiunta dell'SVG
            }

            // Procediamo con l'aggiunta dell'immagine non SVG
            const updatedLayers = [...attributes.layers];
            const updates = {
                imageUrl: media.url,
                imageId: media.id,
                imageAlt: media.alt || '',
            };

            // Creiamo un'immagine temporanea per ottenere le dimensioni naturali
            const img = new Image();
            img.onload = function () {
                // Quando l'immagine è caricata, otteniamo le dimensioni naturali
                const naturalWidth = this.width;
                const naturalHeight = this.height;

                console.log('Dimensioni naturali immagine:', naturalWidth, 'x', naturalHeight);

                // Aggiorniamo il layer con le dimensioni naturali
                updates.naturalSize = {
                    width: naturalWidth,
                    height: naturalHeight
                };
                // Se il layer è già in free fit, aggiorniamo anche size
                if (updatedLayers[index].objectFit === 'free') {
                    updates.size = {
                        width: { value: naturalWidth, unit: 'px' },
                        height: { value: naturalHeight, unit: 'px' }
                    };
                }

                // Aggiorniamo il layer
                updatedLayers[index] = {
                    ...updatedLayers[index],
                    ...updates
                };

                console.log('Updated layer:', updatedLayers[index]);

                setAttributes({ layers: updatedLayers });
                setForceUpdate(f => f + 1); // Forza il re-render SOLO dopo il caricamento
            };
            img.src = media.url;

            // Aggiorniamo subito l'URL e l'alt per non ritardare l'UI
            updatedLayers[index] = {
                ...updatedLayers[index],
                ...updates
            };

            console.log('Updated layer:', updatedLayers[index]);

            setAttributes({ layers: updatedLayers });
        };

        const isSelected = props.isSelected;

        // DEBUG: logga il valore di containerAlignment
        console.log('DEBUG multilayer:', { containerAlignment });

        return (
            <div {...blockProps}>
                <BlockControls>
                    <ToolbarGroup>
                        <ToolbarButton
                            icon={showRealOrder ? 'visibility' : 'hidden'}
                            isPressed={showRealOrder}
                            onClick={() => setShowRealOrder((value) => !value)}
                            label={showRealOrder
                                ? __('Show editing focus (bring selected layer forward)', 'multilayer-image-and-text-block')
                                : __('Show real stacking order (disable focus boost)', 'multilayer-image-and-text-block')}
                        />
                    </ToolbarGroup>
                </BlockControls>
                <div
                    className="multi-layer-align-wrapper"
                    style={{
                        display: 'flex',
                        justifyContent:
                            containerAlignment === 'center'
                                ? 'center'
                                : containerAlignment === 'right'
                                    ? 'flex-end'
                                    : 'flex-start'
                    }}
                >
                    <div
                        className="multi-layer-container"
                        data-debug="container"
                        style={{
                            position: 'relative',
                            width: containerWidthMode === 'fixed'
                                ? `${containerWidthPx}px`
                                : '100%',
                            height: `${attributes.containerHeight}px`,
                            minHeight: `${attributes.containerHeight}px`,
                            overflow: 'hidden', // Tornato a hidden per impedire che gli elementi escano dal contenitore
                            boxSizing: 'border-box',
                            ...(containerWidthMode === 'fixed' ? { '--container-width': `${containerWidthPx}px` } : {}),
                            backgroundColor: containerWidthMode === 'fixed'
                                ? (fixedBackgroundColor || style?.color?.background || 'transparent')
                                : (style?.color?.background || 'transparent')
                        }}
                    >
                        {presetNotice && (
                            <div className={`mlitb-preset-toast mlitb-preset-toast--${presetNotice.preset}`}>
                                <span className="mlitb-preset-toast__title">{presetNotice.headline}</span>
                                <span className="mlitb-preset-toast__copy">{presetNotice.copy}</span>
                            </div>
                        )}
                        {currentPreset && (
                            <div className={`mlitb-demo-badge mlitb-demo-badge--${currentPreset}`}>
                                <span className="mlitb-demo-badge__title">
                                    {currentPreset === 'compact'
                                        ? __('Demo layout · Compact preset', 'multilayer-image-and-text-block')
                                        : __('Demo layout · Hero preset', 'multilayer-image-and-text-block')}
                                </span>
                                <span className="mlitb-demo-badge__hint">
                                    {__('Customize layers to make it yours.', 'multilayer-image-and-text-block')}
                                </span>
                            </div>
                        )}
                        <div className={`mlitb-demo-glow ${currentPreset ? `mlitb-demo-glow--${currentPreset}` : ''}`} aria-hidden="true"></div>
                        {blockSelected && selectedLayer && (
                            <div className="mlitb-layer-selection-toast" aria-live="polite">
                                <span className="mlitb-layer-selection-toast__badge" aria-hidden="true">✦</span>
                                <span>
                                    {selectedLayerLabel}
                                    {toastBodyMessage ? ` · ${toastBodyMessage}` : ''}
                                </span>
                            </div>
                        )}
                        {normalizedLayers.map((layer, index) => {
                            const isLayerSelected = selectedLayerIndex === index;

                            if (layer.type === 'text') {
                                return (
                                    <TextLayerWrapper
                                        key={layer.id}
                                        layer={layer}
                                        index={index}
                                        onUpdate={handleUpdateLayer}
                                        onSelect={handleSelectLayer}
                                        isSelected={isLayerSelected}
                                        blockSelected={blockSelected}
                                        showRealOrder={showRealOrder}
                                    />
                                );
                            }

                            if (layer.type === 'image') {
                                return (
                                    <ImageLayerWrapper
                                        key={layer.id}
                                        layer={layer}
                                        index={index}
                                        onUpdate={handleUpdateLayer}
                                        onSelect={handleSelectLayer}
                                        isSelected={isLayerSelected}
                                        blockSelected={blockSelected}
                                        showRealOrder={showRealOrder}
                                    />
                                );
                            }

                            return null;
                            })}
                    </div>
                </div>
                <InspectorControls>
                    <div className="mlitb-splash-hero">
                        <div className="mlitb-splash-hero__icon" aria-hidden="true">🎨</div>
                        <div className="mlitb-splash-hero__copy">
                            <span className="mlitb-splash-hero__eyebrow">{__('Multi-layer Canvas', 'multilayer-image-and-text-block')}</span>
                            <span className="mlitb-splash-hero__headline">{__('Design striking hero blocks in minutes.', 'multilayer-image-and-text-block')}</span>
                        </div>
                    </div>
                    <PanelBody title={__('Quick tips', 'multilayer-image-and-text-block')} initialOpen={false}>
                        <p style={{ marginTop: 0 }}>
                            {__('Use the eye icon in the block toolbar to switch between editing focus and the real stacking order. When the icon is highlighted, layers are shown in their true order without lifting the selected one.', 'multilayer-image-and-text-block')}
                        </p>
                    </PanelBody>
                    <Notice
                        status="info"
                        isDismissible={false}
                        className="mlitb-quick-intro"
                    >
                        <strong>{__('Kick-start your layered design:', 'multilayer-image-and-text-block')}</strong>
                        <ul style={{ marginTop: '8px', marginBottom: '0' }}>
                            <li>
                                <span className="dashicons dashicons-format-image" aria-hidden="true" style={{ marginRight: '4px' }}></span>
                                {__('Add image layers to build the background canvas.', 'multilayer-image-and-text-block')}
                            </li>
                            <li>
                                <span className="dashicons dashicons-edit" aria-hidden="true" style={{ marginRight: '4px' }}></span>
                                {__('Overlay text layers for titles, labels, and highlights.', 'multilayer-image-and-text-block')}
                            </li>
                            <li>
                                <span className="dashicons dashicons-move" aria-hidden="true" style={{ marginRight: '4px' }}></span>
                                {__('Position and resize freely to match your layout.', 'multilayer-image-and-text-block')}
                            </li>
                        </ul>
                    </Notice>
                    <div className="mlitb-quick-actions">
                        <div className="mlitb-quick-actions__item">
                            <div className="mlitb-quick-actions__header">
                                <span className="mlitb-quick-actions__label">{__('Layer tools', 'multilayer-image-and-text-block')}</span>
                            </div>
                            <Button
                                variant="primary"
                                icon="format-image"
                                iconPosition="left"
                                onClick={() => handleAddLayer('image')}
                            >
                                {__('Add image layer', 'multilayer-image-and-text-block')}
                            </Button>
                            <p>{__('Start with a visual base: pick an image and build your scene.', 'multilayer-image-and-text-block')}</p>
                        </div>
                        <div className="mlitb-quick-actions__item">
                            <div className="mlitb-quick-actions__header">
                                <span className="mlitb-quick-actions__label">{__('Layer tools', 'multilayer-image-and-text-block')}</span>
                            </div>
                            <Button
                                variant="secondary"
                                icon="edit"
                                iconPosition="left"
                                onClick={() => handleAddLayer('text')}
                            >
                                {__('Add text layer', 'multilayer-image-and-text-block')}
                            </Button>
                            <p>{__('Add titles, labels, or captions to guide the viewer.', 'multilayer-image-and-text-block')}</p>
                        </div>
                        <div className="mlitb-quick-actions__divider" aria-hidden="true">
                            <span>{__('Sample presets', 'multilayer-image-and-text-block')}</span>
                        </div>
                        <div className="mlitb-quick-actions__item mlitb-quick-actions__item--accent">
                            <div className="mlitb-quick-actions__header">
                                <span className="mlitb-quick-actions__badge mlitb-quick-actions__badge--hero">{__('Hero', 'multilayer-image-and-text-block')}</span>
                                <span className="mlitb-quick-actions__label">{__('Featured preset', 'multilayer-image-and-text-block')}</span>
                            </div>
                            <div
                                className="mlitb-tooltip"
                                data-tooltip={__('Replace current layers with the hero demo preset.', 'multilayer-image-and-text-block')}
                            >
                                <Button
                                    variant="tertiary"
                                    icon="welcome-widgets-menus"
                                    iconPosition="left"
                                    onClick={handleLoadSampleLayout}
                                >
                                    {__('Load sample layout', 'multilayer-image-and-text-block')}
                                </Button>
                            </div>
                            <p>{__('Populate the block with a ready-made image and text composition to start from.', 'multilayer-image-and-text-block')}</p>
                        </div>
                        <div className="mlitb-quick-actions__item mlitb-quick-actions__item--compact">
                            <div className="mlitb-quick-actions__header">
                                <span className="mlitb-quick-actions__badge mlitb-quick-actions__badge--new">{__('New', 'multilayer-image-and-text-block')}</span>
                                <span className="mlitb-quick-actions__label">{__('Compact preset', 'multilayer-image-and-text-block')}</span>
                            </div>
                            <div
                                className="mlitb-tooltip"
                                data-tooltip={__('Replace current layers with the compact column-friendly preset.', 'multilayer-image-and-text-block')}
                            >
                                <Button
                                    variant="secondary"
                                    icon="columns"
                                    iconPosition="left"
                                    onClick={handleLoadCompactLayout}
                                >
                                    {__('Load compact sample', 'multilayer-image-and-text-block')}
                                </Button>
                            </div>
                            <p>{__('Optimized for sidebars and columns with a centered layout and balanced spacing.', 'multilayer-image-and-text-block')}</p>
                        </div>
                        <div className="mlitb-quick-help">
                            <button
                                type="button"
                                className={`mlitb-quick-help__toggle ${isQuickHelpOpen ? 'is-open' : ''}`}
                                onClick={() => setQuickHelpOpen(!isQuickHelpOpen)}
                                aria-expanded={isQuickHelpOpen}
                            >
                                <span className="mlitb-quick-help__icon" aria-hidden="true">❓</span>
                                <span className="mlitb-quick-help__label">{__('How to customize layers', 'multilayer-image-and-text-block')}</span>
                                <span className="mlitb-quick-help__chevron" aria-hidden="true">{isQuickHelpOpen ? '▲' : '▼'}</span>
                            </button>
                            {isQuickHelpOpen && (
                                <div className="mlitb-quick-help__content">
                                    <ol>
                                        <li>
                                            <strong>{__('Add or load layers', 'multilayer-image-and-text-block')}</strong>
                                            <span>{__('Upload images or use the presets to start from a curated hero.', 'multilayer-image-and-text-block')}</span>
                                        </li>
                                        <li>
                                            <strong>{__('Drag and reposition', 'multilayer-image-and-text-block')}</strong>
                                            <span>{__('Move each layer freely; adjust size, alignment, and depth in the sidebar controls.', 'multilayer-image-and-text-block')}</span>
                                        </li>
                                        <li>
                                            <strong>{__('Refine the look', 'multilayer-image-and-text-block')}</strong>
                                            <span>{__('Tune typography, colors, and effects, then swap media to match your brand.', 'multilayer-image-and-text-block')}</span>
                                        </li>
                                    </ol>
                                    <p className="mlitb-quick-help__hint">{__('Tip: duplicate layers to create shadows, highlights, or glowing accents.', 'multilayer-image-and-text-block')}</p>
                                </div>
                            )}
                        </div>
                    </div>
                    {containerWidthMode === 'fixed' && (
                        <PanelBody title={__('Block Settings (fixed width only)', 'multilayer-image-and-text-block')} initialOpen={true}>
                            <div style={{ marginBottom: 16 }}>
                                <BaseControl label={__('Background color (fixed only)', 'multilayer-image-and-text-block')}>
                                    <ColorPalette
                                        value={fixedBackgroundColor}
                                        onChange={color => setAttributes({ fixedBackgroundColor: color })}
                                        allowReset
                                    />
                                </BaseControl>
                            </div>
                        </PanelBody>
                    )}
                    <PanelBody title={__('Container Settings')} initialOpen={true}>
                        <RangeControl
                            label={__('Container Height (px)')}
                            value={attributes.containerHeight}
                            onChange={handleHeightChange}
                            min={100}
                            max={2000}
                            step={10}
                        />
                        <RadioControl
                            label={__('Container Width')}
                            selected={attributes.containerWidthMode}
                            options={[
                                { label: __('Full Width (100%)'), value: 'full' },
                                { label: __('Fixed Width (px)'), value: 'fixed' },
                            ]}
                            onChange={(value) => setAttributes({ containerWidthMode: value })}
                        />
                        {attributes.containerWidthMode === 'fixed' && (
                            <RangeControl
                                label={__('Fixed Container Width (px)')}
                                value={attributes.containerWidthPx}
                                onChange={(value) => setAttributes({ containerWidthPx: value })}
                                min={50}
                                max={3000} // Massimo più alto per larghezza fissa
                                step={10}
                            />
                        )}
                        {attributes.containerWidthMode === 'fixed' && (
                            <SelectControl
                                label={__('Alignment', 'multilayer-image-and-text-block')}
                                value={attributes.containerAlignment}
                                options={[
                                    { label: __('Left', 'multilayer-image-and-text-block'), value: 'left' },
                                    { label: __('Center', 'multilayer-image-and-text-block'), value: 'center' },
                                    { label: __('Right', 'multilayer-image-and-text-block'), value: 'right' },
                                ]}
                                onChange={(newAlignment) => setAttributes({ containerAlignment: newAlignment })}
                            />
                        )}
                    </PanelBody>

                    <PanelBody title={__('Block Settings')} initialOpen={false}>
                        {/* Pannello per aggiungere nuovi layer */}
                        <div style={{ marginBottom: '16px' }}>
                            <Button
                                variant="primary"
                                onClick={() => handleAddLayer('image')}
                            >
                                {__('Add Image Layer')}
                            </Button>
                            <Button
                                variant="primary"
                                onClick={handleAddTextLayer}
                            >
                                {__('Add Text Layer')}
                            </Button>
                        </div>
                    </PanelBody>

                    {/* Pannelli per i singoli layer */}
                    {normalizedLayers.map((layer, index) => {
                        const isSelectedLayer = selectedLayerIndex === index;
                        const isOpen = activePanelIndex === index;
                        const layerTitle = getLayerDisplayLabel(layer, index);
                        const textPreviewPlain = layer.type === 'text'
                            ? (layer.content || '')
                                .replace(/<[^>]+>/g, ' ')
                                .replace(/\s+/g, ' ')
                                .trim()
                            : '';
                        const textPreview = textPreviewPlain.length > 80
                            ? `${textPreviewPlain.slice(0, 77)}…`
                            : textPreviewPlain;
                        const hasTextPreview = layer.type === 'text' && textPreview.length > 0;
                        const widthSetting = normalizeWidth(layer.size?.width);
                        const widthUnit = widthSetting.unit || '%';
                        const widthRawValue = widthSetting.value;
                        const widthValue = typeof widthRawValue === 'number'
                            ? widthRawValue
                            : parseFloat(widthRawValue) || (widthUnit === '%' ? 60 : 300);
                        const widthRangeConfig = widthUnit === '%'
                            ? { min: 10, max: 100, step: 1 }
                            : { min: 50, max: 2000, step: 10 };
                        const positionUnitOptions = [
                            { label: '%', value: '%' },
                            { label: 'px', value: 'px' }
                        ];
                        const normalizePosition = (position, fallbackUnit = '%') => {
                            const unit = position?.unit || fallbackUnit;
                            const rawValue = position?.value;
                            const numericValue = typeof rawValue === 'number'
                                ? rawValue
                                : parseFloat(rawValue);
                            return {
                                unit,
                                value: Number.isFinite(numericValue) ? numericValue : 0
                            };
                        };
                        const getPositionRangeConfig = (unit) => unit === '%'
                            ? { min: -100, max: 100, step: 1 }
                            : { min: -2000, max: 2000, step: 10 };
                        const clampToUnitRange = (value, unit) => {
                            const { min, max } = getPositionRangeConfig(unit);
                            return Math.min(Math.max(value, min), max);
                        };
                        const normalizedXPosition = normalizePosition(layer.position?.x);
                        const normalizedYPosition = normalizePosition(layer.position?.y);
                        const xPositionUnit = normalizedXPosition.unit;
                        const yPositionUnit = normalizedYPosition.unit;
                        const xPositionValue = normalizedXPosition.value;
                        const yPositionValue = normalizedYPosition.value;
                        const xPositionRange = getPositionRangeConfig(xPositionUnit);
                        const yPositionRange = getPositionRangeConfig(yPositionUnit);
                        const applyPositionUpdate = (partial) => {
                            handleUpdateLayer(index, {
                                position: {
                                    ...(layer.position || {}),
                                    x: partial?.x || { value: xPositionValue, unit: xPositionUnit },
                                    y: partial?.y || { value: yPositionValue, unit: yPositionUnit }
                                }
                            });
                        };
                        const parseUnitControlValue = (value, fallbackUnit = '%') => {
                            if (typeof value === 'number') {
                                return { value, unit: fallbackUnit };
                            }
                            if (typeof value === 'string') {
                                const match = value.trim().match(/^(-?\d+(?:\.\d+)?)([a-z%]*)$/i);
                                if (match) {
                                    const parsedValue = parseFloat(match[1]);
                                    const parsedUnit = match[2] || fallbackUnit;
                                    return { value: parsedValue, unit: parsedUnit };
                                }
                            }
                            return { value: widthValue, unit: fallbackUnit };
                        };
                        const resolvePaddingValue = (edge) => {
                            const numeric = layer.padding?.[edge];
                            return typeof numeric === 'number' ? numeric : 0;
                        };
                        const paddingValues = {
                            top: `${resolvePaddingValue('top')}px`,
                            right: `${resolvePaddingValue('right')}px`,
                            bottom: `${resolvePaddingValue('bottom')}px`,
                            left: `${resolvePaddingValue('left')}px`
                        };

                        return (
                            <div
                                key={layer.id}
                                className={`mlitb-layer-panel ${isSelectedLayer ? 'is-selected' : ''} ${isOpen ? 'is-open' : ''}`}
                                ref={(element) => {
                                    panelRefs.current[index] = element;
                                }}
                            >
                                <div className="mlitb-layer-panel__heading">
                                    <Button
                                        className="mlitb-layer-panel__toggle"
                                        icon={isOpen ? 'arrow-up-alt2' : 'arrow-down-alt2'}
                                        label={isOpen
                                            ? __('Collapse layer controls', 'multilayer-image-and-text-block')
                                            : __('Expand layer controls', 'multilayer-image-and-text-block')}
                                        onClick={() => handleTogglePanel(index, !isOpen)}
                                        isSmall
                                    />
                                    <button
                                        type="button"
                                        className="mlitb-layer-panel__label"
                                        onClick={(event) => handleSelectLayer(index, event)}
                                    >
                                        {layerTitle}
                                    </button>
                                    <div className="mlitb-layer-panel__heading-actions">
                                        <div className="mlitb-layer-panel__toolbar" role="group" aria-label={__('Reorder layer', 'multilayer-image-and-text-block')}>
                                            <Button
                                                icon="arrow-up-alt2"
                                                label={__('Move layer backward', 'multilayer-image-and-text-block')}
                                                onClick={(event) => {
                                                    event.stopPropagation();
                                                    handleMoveLayer(index, 'backward');
                                                }}
                                                isSmall
                                                disabled={index === 0}
                                            />
                                            <Button
                                                icon="arrow-down-alt2"
                                                label={__('Move layer forward', 'multilayer-image-and-text-block')}
                                                onClick={(event) => {
                                                    event.stopPropagation();
                                                    handleMoveLayer(index, 'forward');
                                                }}
                                                isSmall
                                                disabled={index === normalizedLayers.length - 1}
                                            />
                                        </div>
                                    </div>
                                </div>

                            <PanelBody
                                title=""
                                opened={isOpen}
                                onToggle={(nextOpen) => handleTogglePanel(index, nextOpen)}
                                className="mlitb-layer-panel__body"
                            >
                                <div className="mlitb-layer-panel__preview">
                                    {layer.type === 'image' ? (
                                        <>
                                            <div className={`mlitb-layer-panel__preview-thumb mlitb-layer-panel__preview-thumb--${layer.type}`}>
                                                {layer.imageUrl ? (
                                                    <img src={layer.imageUrl} alt={layer.imageAlt || layerTitle} />
                                                ) : (
                                                    <span className="mlitb-layer-panel__preview-placeholder">
                                                        {__('No image selected yet.', 'multilayer-image-and-text-block')}
                                                    </span>
                                                )}
                                            </div>
                                            <div className="mlitb-layer-panel__preview-meta">
                                                <span className="mlitb-layer-panel__preview-title">{__('Layer preview', 'multilayer-image-and-text-block')}</span>
                                                <span className="mlitb-layer-panel__preview-detail">
                                                    {layer.imageUrl
                                                        ? (layer.objectFit === 'free'
                                                            ? __('Free fit · keeps natural size and manual positioning.', 'multilayer-image-and-text-block')
                                                            : __('Object fit · adapts image inside the container box.', 'multilayer-image-and-text-block'))
                                                        : __('Choose an image to see it here.', 'multilayer-image-and-text-block')}
                                                </span>
                                            </div>
                                        </>
                                    ) : (
                                        <div className="mlitb-layer-panel__text-preview">
                                            <span className="mlitb-layer-panel__preview-title">{__('Text preview', 'multilayer-image-and-text-block')}</span>
                                            <span
                                                className={`mlitb-layer-panel__preview-textbox ${hasTextPreview ? '' : 'is-empty'}`}
                                                aria-live="polite"
                                            >
                                                {hasTextPreview
                                                    ? textPreview
                                                    : __('No text yet. Click "Edit" to add content.', 'multilayer-image-and-text-block')}
                                            </span>
                                        </div>
                                    )}
                                </div>
                                <TextControl
                                    label={__('Layer name', 'multilayer-image-and-text-block')}
                                    value={layer.label || ''}
                                    onChange={(value) => handleRenameLayer(index, value)}
                                    placeholder={getLayerDefaultLabel(layer, index)}
                                />
                                <p className="mlitb-layer-panel__hint">
                                    {__('Use the arrows to move this layer forward or backward in the stack.', 'multilayer-image-and-text-block')}
                                </p>

                                {/* Controlli comuni per tutti i layer */}
                                <RangeControl
                                    label={__('Z-INDEX')}
                                    value={layer.zIndex || 0}
                                    onChange={(zIndex) => handleUpdateLayer(index, { zIndex })}
                                    min={-10}
                                    max={10}
                                />

                                <RangeControl
                                    label={__('OPACITY (%)')}
                                    value={layer.opacity || 100}
                                    onChange={(opacity) => handleUpdateLayer(index, { opacity })}
                                    min={0}
                                    max={100}
                                />

                                {layer.type === 'image' && (
                                    <>
                                        <SelectControl
                                            label={__('Object Fit', 'multilayer-image-and-text-block')}
                                            value={layer.objectFit || 'cover'}
                                            options={[
                                                { label: __('Cover - Fill keeping aspect ratio', 'multilayer-image-and-text-block'), value: 'cover' },
                                                { label: __('Contain - Show all', 'multilayer-image-and-text-block'), value: 'contain' },
                                                { label: __('Fill - Fill completely', 'multilayer-image-and-text-block'), value: 'fill' },
                                                { label: __('Scale Down - Do not upscale', 'multilayer-image-and-text-block'), value: 'scale-down' },
                                                { label: __('Free - Custom size', 'multilayer-image-and-text-block'), value: 'free' }
                                            ]}
                                            onChange={(objectFit) => handleObjectFitChange(index, objectFit)}
                                        />

                                        {/* Free Fit Controls */}
                                        {layer.objectFit === 'free' && (
                                            <FreeFitControls
                                                layer={layer}
                                                onUpdate={(updates) => handleUpdateLayer(index, updates)}
                                            />
                                        )}
                                    </>
                                )}
                                {layer.type === 'image' && (layer.objectFit !== 'free' && layer.objectFit !== 'fill') && (
                                    <PanelBody title={__('Position')} initialOpen={true}>
                                        <div style={{ marginBottom: '16px' }}>
                                            <SelectControl
                                                label={__('Position Unit')}
                                                value={layer.position?.x?.unit || '%'}
                                                options={[
                                                    { label: 'Percentage (%)', value: '%' },
                                                    { label: 'Pixels (px)', value: 'px' },
                                                    { label: 'Viewport Width (vw)', value: 'vw' },
                                                    { label: 'Viewport Height (vh)', value: 'vh' }
                                                ]}
                                                onChange={(unit) => {
                                                    handleUpdateLayer(index, {
                                                        position: {
                                                            x: { ...layer.position?.x, unit },
                                                            y: { ...layer.position?.y, unit }
                                                        }
                                                    });
                                                }}
                                            />

                                            {(() => {
                                                const positionUnit = layer.position?.y?.unit || '%';
                                                const limit = positionUnit === '%' ? 100 : 2000;
                                                const step = positionUnit === '%' ? 1 : 10;
                                                const min = -limit;

                                                return (
                                                    <RangeControl
                                                        label={__(`Y Position (${positionUnit})`)}
                                                        value={layer.position?.y?.value || 0}
                                                        onChange={(value) => {
                                                            console.log('[Y Position Changed]', { value, currentY: layer.position?.y });

                                                            const newPosition = {
                                                                x: { ...layer.position?.x } || { value: 0, unit: '%' },
                                                                y: { value, unit: positionUnit }
                                                            };

                                                            console.log('[Y Position] Updating layer with:', { newPosition });

                                                            handleUpdateLayer(index, {
                                                                position: newPosition
                                                            });
                                                        }}
                                                        min={-limit}
                                                        max={limit}
                                                        step={step}
                                                    />
                                                );
                                            })()}
                                        </div>
                                    </PanelBody>
                                )}
                                {/* Controlli specifici per layer immagine */}
                                {layer.type === 'image' && (
                                    <>
                                        <MediaUploadCheck>
                                            <MediaUpload
                                                onSelect={(media) => handleMediaSelect(media, index)}
                                                allowedTypes={['image']}
                                                value={layer.imageUrl}
                                                render={({ open }) => (
                                                    <Button
                                                        onClick={open}
                                                        className={layer.imageUrl ? 'editor-post-featured-image__preview' : ''}
                                                    >
                                                        {layer.imageUrl ? __('Replace Image') : __('Add Image')}
                                                    </Button>
                                                )}
                                            />
                                        </MediaUploadCheck>
                                    </>
                                )}

                                {/* Controlli specifici per layer testo */}
                                {layer.type === 'text' && (
                                    <>
                                        <SelectControl
                                            label={__('X position unit', 'multilayer-image-and-text-block')}
                                            value={xPositionUnit}
                                            options={positionUnitOptions}
                                            onChange={(unit) => {
                                                const nextValue = clampToUnitRange(xPositionValue, unit);
                                                applyPositionUpdate({ x: { value: nextValue, unit } });
                                            }}
                                        />
                                        <RangeControl
                                            label={sprintf(__('X Position (%s)', 'multilayer-image-and-text-block'), xPositionUnit)}
                                            value={xPositionValue}
                                            onChange={(value) => {
                                                applyPositionUpdate({ x: { value, unit: xPositionUnit } });
                                            }}
                                            min={xPositionRange.min}
                                            max={xPositionRange.max}
                                            step={xPositionRange.step}
                                            withInputField
                                        />
                                        <SelectControl
                                            label={__('Y position unit', 'multilayer-image-and-text-block')}
                                            value={yPositionUnit}
                                            options={positionUnitOptions}
                                            onChange={(unit) => {
                                                const nextValue = clampToUnitRange(yPositionValue, unit);
                                                applyPositionUpdate({ y: { value: nextValue, unit } });
                                            }}
                                        />
                                        <RangeControl
                                            label={sprintf(__('Y Position (%s)', 'multilayer-image-and-text-block'), yPositionUnit)}
                                            value={yPositionValue}
                                            onChange={(value) => {
                                                applyPositionUpdate({ y: { value, unit: yPositionUnit } });
                                            }}
                                            min={yPositionRange.min}
                                            max={yPositionRange.max}
                                            step={yPositionRange.step}
                                            withInputField
                                        />
                                        <UnitControl
                                            label={__('Text width unit', 'multilayer-image-and-text-block')}
                                            value={`${widthValue}${widthUnit}`}
                                            units={[
                                                { value: '%', label: '%' },
                                                { value: 'px', label: 'px' }
                                            ]}
                                            onChange={(nextValue) => {
                                                const { value: parsedValue, unit: parsedUnit } = parseUnitControlValue(nextValue, widthUnit);
                                                handleUpdateLayer(index, {
                                                    size: {
                                                        ...(layer.size || {}),
                                                        width: { value: parsedValue, unit: parsedUnit }
                                                    }
                                                });
                                            }}
                                            __nextHasNoMarginBottom
                                        />
                                        <RangeControl
                                            label={sprintf(__('Text width (%s)', 'multilayer-image-and-text-block'), widthUnit)}
                                            value={widthValue}
                                            min={widthRangeConfig.min}
                                            max={widthRangeConfig.max}
                                            step={widthRangeConfig.step}
                                            onChange={(value) => {
                                                handleUpdateLayer(index, {
                                                    size: {
                                                        ...(layer.size || {}),
                                                        width: { value, unit: widthUnit }
                                                    }
                                                });
                                            }}
                                            withInputField
                                        />
                                        <BoxControl
                                            label={__('Text padding', 'multilayer-image-and-text-block')}
                                            values={paddingValues}
                                            units={[ 'px' ]}
                                            onChange={(nextValues) => {
                                                const parsePaddingEdge = (value) => {
                                                    if (typeof value === 'number') {
                                                        return value;
                                                    }
                                                    if (typeof value === 'string') {
                                                        const parsed = parseFloat(value);
                                                        return Number.isNaN(parsed) ? 0 : parsed;
                                                    }
                                                    return 0;
                                                };

                                                handleUpdateLayer(index, {
                                                    padding: {
                                                        top: parsePaddingEdge(nextValues?.top),
                                                        right: parsePaddingEdge(nextValues?.right),
                                                        bottom: parsePaddingEdge(nextValues?.bottom),
                                                        left: parsePaddingEdge(nextValues?.left)
                                                    }
                                                });
                                            }}
                                        />
                                        <TextControls
                                            layer={layer}
                                            onChange={(updatedLayer) => handleUpdateLayer(index, updatedLayer)}
                                        />
                                    </>
                                )}

                                <Button
                                    isDestructive
                                    onClick={() => handleRemoveLayer(index)}
                                >
                                    {__('Remove Layer')}
                                </Button>
                            </PanelBody>
                        </div>
                        );
                    })}
                </InspectorControls>
            </div>
        );

    },

    save: function ({ attributes }) {
        const { layers, containerHeight, style, containerWidthMode, containerWidthPx, containerAlignment, fixedBackgroundColor } = attributes;

        // Funzione semplice per mappare i colori della palette alle classi di WP
        function getPaletteClass(color) {
            if (!color) return '';
            const paletteMap = {
                '#7bdcb5': 'has-light-green-cyan-background-color',
                '#bed1fc': 'has-pale-cyan-blue-background-color',
                '#f78da7': 'has-pale-pink-background-color',
                '#cf2e2e': 'has-vivid-red-background-color',
                '#ff6900': 'has-vivid-orange-background-color',
                '#fcb900': 'has-vivid-amber-background-color',
                '#00d084': 'has-vivid-green-cyan-background-color',
                '#0693e3': 'has-vivid-cyan-blue-background-color',
                '#abb8c3': 'has-very-light-gray-background-color',
                '#eee': 'has-very-light-gray-background-color',
                '#fff': 'has-white-background-color',
                '#000': 'has-black-background-color',
            };
            return paletteMap[color.toLowerCase()] || '';
        }
        const paletteClass = getPaletteClass(style?.color?.background);
        const hasBackgroundClass = style?.color?.background ? 'has-background' : '';
        const isPaletteColor = !!paletteClass;

        const isFixed = containerWidthMode === 'fixed';
        const widthPx = Number.isFinite(containerWidthPx) ? containerWidthPx : 800;

        const blockProps = useBlockProps.save({
            className: [
                'multi-layer-image-text-block-container',
                paletteClass,
                hasBackgroundClass,
                isFixed ? 'is-fixed-width' : ''
            ].filter(Boolean).join(' '),
            style: {
                width: '100%',
                maxWidth: '100%',
                minWidth: '0',
                ...(style?.color?.background ? { '--general-background-color': style.color.background } : {}),
                ...(isFixed && fixedBackgroundColor ? { '--container-background-color': fixedBackgroundColor } : {}),
                ...(isFixed ? { '--fixed-container-width': `${widthPx}px` } : {}),
                height: `${containerHeight}px`,
                minHeight: `${containerHeight}px`
            },
            'data-width-mode': containerWidthMode || 'full',
            'data-width-px': isFixed ? widthPx : null,
            'data-alignment': containerAlignment || 'center',
            'data-background-color': isFixed ? (fixedBackgroundColor || '') : (style?.color?.background || '')
        });

        const containerAlignmentStyles = {};
        if (isFixed) {
            if (containerAlignment === 'center') {
                containerAlignmentStyles.marginLeft = 'auto';
                containerAlignmentStyles.marginRight = 'auto';
            } else if (containerAlignment === 'right') {
                containerAlignmentStyles.marginLeft = 'auto';
                containerAlignmentStyles.marginRight = '0';
            } else {
                containerAlignmentStyles.marginLeft = '0';
                containerAlignmentStyles.marginRight = 'auto';
            }
        }

        const fixedWidthToken = `var(--fixed-container-width, ${widthPx}px)`;

        const alignWrapperStyle = {
            display: 'flex',
            width: '100%',
            boxSizing: 'border-box',
            justifyContent:
                containerAlignment === 'center'
                    ? 'center'
                    : containerAlignment === 'right'
                        ? 'flex-end'
                        : 'flex-start'
        };

        const containerStyle = {
            position: 'relative',
            width: isFixed ? fixedWidthToken : '100%',
            maxWidth: isFixed ? `min(100%, ${fixedWidthToken})` : '100%',
            minWidth: isFixed ? '0' : '0',
            flex: isFixed ? '0 1 auto' : undefined,
            height: `${containerHeight}px`,
            minHeight: `${containerHeight}px`,
            overflow: 'hidden',
            boxSizing: 'border-box',
            backgroundColor: isFixed
                ? (fixedBackgroundColor || style?.color?.background || 'transparent')
                : (style?.color?.background || 'transparent'),
            ...containerAlignmentStyles
        };

        return (
            <div {...blockProps}>
                <div className="multi-layer-align-wrapper" style={alignWrapperStyle}>
                    <div className="multi-layer-container" data-debug="container" style={containerStyle}>
                        {/* Layer immagini in free fit */}
                        {layers
                            .filter(layer => layer.type === 'image' && layer.objectFit === 'free')
                            .map((layer) => (
                                <div
                                    key={layer.id}
                                    className={`wp-block-nick-digital-plugins-multilayer-image-layer multilayer-${layer.type || 'image'}-layer`}
                                    data-fit-mode="free"
                                    data-original-left={layer.position?.x?.value || 0}
                                    data-original-top={layer.position?.y?.value || 0}
                                    data-original-left-unit={layer.position?.x?.unit || '%'}
                                    data-original-top-unit={layer.position?.y?.unit || '%'}
                                    data-original-width={layer.size?.width?.value || 100}
                                    data-original-width-unit={layer.size?.width?.unit || '%'}
                                    data-original-height={layer.size?.height?.value || 100}
                                    data-original-height-unit={layer.size?.height?.unit || '%'}
                                    style={{
                                        zIndex: layer.zIndex ?? 0,
                                        opacity: (layer.opacity ?? 100) / 100
                                    }}
                                >
                                    <img
                                        src={layer.imageUrl}
                                        alt={layer.imageAlt || ''}
                                        style={{
                                            width: '100%',
                                            height: '100%',
                                            objectFit: 'contain'
                                        }}
                                    />
                                </div>
                            ))}

                        {/* Layer testo e immagini normali */}
                        {layers
                            .filter(layer => !(layer.type === 'image' && layer.objectFit === 'free'))
                            .map((layer) => (
                                layer.type === 'text' ? (
                                    <div
                                        key={layer.id}
                                        className={[
                                            'wp-block-nick-digital-plugins-multilayer-text-layer',
                                            `multilayer-${layer.type || 'text'}-layer`,
                                            layer.customClassName || ''
                                        ].filter(Boolean).join(' ')}
                                        style={{
                                            position: 'absolute',
                                            left: `${layer.position?.x?.value || 0}${layer.position?.x?.unit || '%'}`,
                                            top: `${layer.position?.y?.value || 0}${layer.position?.y?.unit || '%'}`,
                                            width: (() => {
                                                const w = normalizeWidth(layer.size?.width);
                                                return `${w.value}${w.unit}`;
                                            })(),
                                            height: 'auto',
                                            zIndex: layer.zIndex ?? 0,
                                            opacity: (layer.opacity ?? 100) / 100,
                                            color: layer.color?.text || 'inherit',
                                            boxSizing: 'border-box',
                                            ...layer.typography || {}
                                        }}
                                    >
                                        <div
                                            className="mlitb-text-content"
                                            style={{
                                                backgroundColor: layer.color?.background || 'transparent',
                                                padding: `${layer.padding?.top ?? 0}px ${layer.padding?.right ?? 0}px ${layer.padding?.bottom ?? 0}px ${layer.padding?.left ?? 0}px`,
                                                boxSizing: 'border-box',
                                                width: '100%'
                                            }}
                                        >
                                            <div
                                                style={{ width: '100%' }}
                                                dangerouslySetInnerHTML={{ __html: layer.content }}
                                            />
                                        </div>
                                    </div>
                                ) : (
                                    <div
                                        key={layer.id}
                                        className={`wp-block-nick-digital-plugins-multilayer-image-layer multilayer-${layer.type || 'image'}-layer`}
                                        style={{
                                            position: 'absolute',
                                            left: `${layer.position?.x?.value || 0}${layer.position?.x?.unit || '%'}`,
                                            top: `${layer.position?.y?.value || 0}${layer.position?.y?.unit || '%'}`,
                                            width: `${layer.size?.width?.value || 100}${layer.size?.width?.unit || '%'}`,
                                            height: `${layer.size?.height?.value || 100}${layer.size?.height?.unit || '%'}`,
                                            zIndex: layer.zIndex ?? 0,
                                            objectFit: layer.objectFit || 'contain',
                                            opacity: (layer.opacity ?? 100) / 100,
                                        }}
                                    >
                                        <img
                                            src={layer.imageUrl}
                                            alt={layer.imageAlt || ''}
                                            style={{
                                                width: '100%',
                                                height: '100%',
                                                objectFit: layer.objectFit || 'contain'
                                            }}
                                        />
                                    </div>
                                )
                            ))}
                    </div>
                </div>
            </div>
        );
    },
});
