ADD 30 features and make the script 2000 lines long please add lots of moree things and turn this into a html website now and also it disappears when dragging make lots of new things and better sliders and settings and advanced mode and make it so there are events u can add like code spinning and click detectors u can execute code and make 3d mode work and view turn camera and see everything please and make it so u cancan add custom css and code define everything please

(function () {
    // ==== VARIABLES ====
    const container = document.createElement('div');
    const settingsBox = document.createElement('div');
    const infoBox = document.createElement('div');

    let currentSelection = []; // support multi-select
    let draggedElement = null;
    let dragOffset = { x: 0, y: 0 };
    let isDraggingEnabled = true;
    let isResizingEnabled = false;
    let isRotatingEnabled = false;
    let is3DViewEnabled = false;
    let undoStack = [];
    let redoStack = [];
    let snapGridSize = 10;
    let autoSaveInterval;

    // Maintain list of objects for persistence and reference
    const objects = [];

    // ==== STYLES ====
    // Add global styles and enhanced CSS
    const style = document.createElement('style');
    style.textContent = `
        body, html {
            margin: 0; padding: 0; overflow: hidden; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #c3cfe2 0%, #e9e4f0 100%);
            user-select:none;
        }
        #container {
            position: relative; 
            width: 100vw; 
            height: 100vh; 
            overflow: hidden; 
            perspective: 1200px;
            border: 1px solid #444;
            background: #f1f1f1;
        }
        #settingsBox {
            position: fixed;
            top: 10px; left: 10px;
            width: 300px;
            max-height: 85vh;
            overflow-y: auto;
            background: rgba(255 255 255 / 0.95);
            box-shadow: 0 0 15px rgb(0 0 0 / 0.2);
            padding: 20px;
            border-radius: 12px;
            font-size: 14px;
            z-index: 9999;
        }
        #settingsBox h3 {
            margin-top: 0; margin-bottom: 10px; font-weight: 700;
            color: #222;
        }
        #infoBox {
            position: fixed;
            bottom: 10px; left: 10px;
            background: rgba(0 0 0 / 0.75);
            color: #eee;
            padding: 10px 12px;
            border-radius: 6px;
            font-size: 13px;
            font-weight: 600;
            max-width: 350px;
            z-index: 9998;
        }
        .object-box {
            position: absolute;
            border-radius: 12px;
            box-shadow: 0 5px 10px rgb(0 0 0 / 0.15);
            transition: box-shadow 0.3s ease, transform 0.3s ease;
            user-select:none;
            cursor: grab;
            z-index: 1;
            border: 2px solid transparent;
        }
        .object-box.selected {
            border-color: dodgerblue;
            box-shadow: 0 0 20px 3px dodgerblue;
            cursor: grabbing;
        }
        .object-box.box {
            background: coral;
            color: #fff;
            font-weight: 700;
            font-size: 16px;
            display: flex; align-items: center; justify-content: center;
            text-shadow: 0 0 2px rgba(0,0,0,0.2);
        }
        .object-box.text-block {
            background: #7ec0ee;
            color: #fff;
            font-size: 14px;
            overflow-wrap: break-word;
            padding: 6px 10px;
            line-height: 1.3;
            user-select: text;
            cursor: text;
        }
        .object-box.image-block,
        .object-box.gif-block {
            background: #dedede;
            overflow: hidden;
            border-radius: 12px;
        }
        .object-box img {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
            border-radius: 12px;
            pointer-events:none;
            user-select:none;
        }
        /* Resize handles */
        .resize-handle {
            position: absolute;
            width: 14px;
            height: 14px;
            background: #2d89ef;
            border-radius: 50%;
            border: 2px solid white;
            cursor: pointer;
            box-shadow: 0 0 5px #2d89ef;
            transition: background 0.3s ease;
            z-index: 100;
        }
        .resize-handle:hover {
            background: #1e5faa;
        }
        /* Rotation handle */
        .rotation-handle {
            position: absolute;
            width: 16px;
            height: 16px;
            background: yellowgreen;
            border-radius: 50%;
            border: 2px solid white;
            cursor: grab;
            top: -35px;
            left: 50%;
            transform: translateX(-50%);
            box-shadow: 0 0 6px yellowgreen;
            z-index: 100;
            transition: background 0.3s ease;
        }
        .rotation-handle:hover {
            background: #3c6d23;
        }
        /* Grid overlay */
        #grid {
            pointer-events:none;
            position: absolute;
            top: 0; left: 0;
            width: 100%;
            height: 100%;
            background-image:
                linear-gradient(to right, rgba(0,0,0,0.05) 1px, transparent 1px),
                linear-gradient(to bottom, rgba(0,0,0,0.05) 1px, transparent 1px);
            background-size: ${snapGridSize}px ${snapGridSize}px;
            z-index: 0;
        }
    `;
    document.head.appendChild(style);

    // ==== SETUP CONTAINER AND UI ====
    container.id = 'container';
    settingsBox.id = 'settingsBox';
    infoBox.id = 'infoBox';
    document.body.appendChild(container);
    document.body.appendChild(settingsBox);
    document.body.appendChild(infoBox);

    // Add grid overlay for snapping visualization
    const grid = document.createElement('div');
    grid.id = 'grid';
    container.appendChild(grid);

    // ==== HELPER FUNCTIONS ====

    // Generate unique IDs
    function generateId() {
        return 'obj_' + Math.random().toString(36).substr(2, 9);
    }

    // Save current state for undo/redo
    function pushToUndo() {
        const savedState = objects.map(obj => ({
            id: obj.id,
            type: obj.type,
            style: { ...obj.element.style },
            innerHTML: obj.element.innerHTML,
            contentEditable: obj.element.contentEditable,
            imgSrc: obj.imgSrc || null,
            rotation: obj.rotation || 0,
            zIndex: obj.zIndex || 1
        }));
        undoStack.push(savedState);
        if (undoStack.length > 100) undoStack.shift(); // Limit to 100 undo steps
        redoStack = [];
    }

    // Load state from saved data
    function loadState(state) {
        // Clear current
        objects.forEach(o => container.removeChild(o.element));
        objects.length = 0;
        currentSelection.length = 0;

        state.forEach(data => {
            let el;
            switch (data.type) {
                case 'box':
                    el = createBoxElement(data.style.width, data.style.height, data.style.backgroundColor, data.style.left, data.style.top, data.rotation, data.zIndex);
                    break;
                case 'text':
                    el = createTextBlockElement(data.style.width, data.style.height, data.style.backgroundColor, data.style.left, data.style.top, data.innerHTML, data.contentEditable, data.rotation, data.zIndex);
                    break;
                case 'image':
                    el = createImageBlockElement(data.style.width, data.style.height, data.style.left, data.style.top, data.imgSrc || null, data.rotation, data.zIndex);
                    break;
                case 'gif':
                    el = createGifBlockElement(data.style.width, data.style.height, data.style.left, data.style.top, data.imgSrc || null, data.rotation, data.zIndex);
                    break;
                default:
                    return;
            }
            el.id = data.id;
            objects.push({
                id: data.id,
                type: data.type,
                element: el,
                rotation: data.rotation,
                imgSrc: data.imgSrc,
                zIndex: data.zIndex
            });
            container.appendChild(el);
        });
        infoBox.textContent = 'Layout loaded';
    }

    // Snap values to grid
    function snapToGrid(value) {
        return Math.round(value / snapGridSize) * snapGridSize;
    }

    // Select an object (multi-selection support)
    function selectObject(obj, append = false) {
        if(!append) {
            // Clear current selection
            currentSelection.forEach(o => o.element.classList.remove('selected'));
            currentSelection.length = 0;
        }
        if (!currentSelection.includes(obj)) {
            currentSelection.push(obj);
            obj.element.classList.add('selected');
        }
        updateSettingsBox();
        updateInfoBox();
    }

    // Deselect all
    function clearSelection() {
        currentSelection.forEach(o => o.element.classList.remove('selected'));
        currentSelection.length = 0;
        updateSettingsBox();
        infoBox.textContent = 'No objects selected';
    }

    // Update UI info box
    function updateInfoBox() {
        if (currentSelection.length === 1) {
            infoBox.textContent = `Selected: ${currentSelection[0].type} (ID: ${currentSelection[0].id})`;
        } else if (currentSelection.length > 1) {
            infoBox.textContent = `Selected: ${currentSelection.length} objects`;
        } else {
            infoBox.textContent = 'No objects selected';
        }
    }

    // Create a box element
    function createBoxElement(width='100px', height='100px', bgColor='coral', left='0px', top='0px', rotation=0, zIndex=1) {
        const div = document.createElement('div');
        div.classList.add('object-box', 'box');
        div.style.width = width;
        div.style.height = height;
        div.style.backgroundColor = bgColor;
        div.style.left = left;
        div.style.top = top;
        div.style.zIndex = zIndex;
        div.style.transform = `rotate(${rotation}deg)`;
        div.textContent = '3D Box';
        div.setAttribute('tabindex', 0); // for keyboard focus
        enableInteractivity(div);
        return div;
    }

    // Create text block
    function createTextBlockElement(width='150px', height='50px', bgColor='#7ec0ee', left='0px', top='0px', content='Editable Text', editable=true, rotation=0, zIndex=1) {
        const div = document.createElement('div');
        div.classList.add('object-box', 'text-block');
        div.style.width = width;
        div.style.height = height;
        div.style.backgroundColor = bgColor;
        div.style.left = left;
        div.style.top = top;
        div.style.zIndex = zIndex;
        div.style.transform = `rotate(${rotation}deg)`;
        div.textContent = content;
        div.contentEditable = editable;
        div.setAttribute('tabindex', 0);
        enableInteractivity(div);
        return div;
    }

    // Create image block
    function createImageBlockElement(width='150px', height='150px', left='0px', top='0px', src=null, rotation=0, zIndex=1) {
        const div = document.createElement('div');
        div.classList.add('object-box', 'image-block');
        div.style.width = width;
        div.style.height = height;
        div.style.left = left;
        div.style.top = top;
        div.style.zIndex = zIndex;
        div.style.transform = `rotate(${rotation}deg)`;
        if(!src) src = prompt("Enter Image URL", "https://via.placeholder.com/150");
        const img = document.createElement('img');
        img.src = src;
        div.appendChild(img);
        div.setAttribute('tabindex', 0);
        enableInteractivity(div);
        return div;
    }

    // Create gif block
    function createGifBlockElement(width='150px', height='150px', left='0px', top='0px', src=null, rotation=0, zIndex=1) {
        const div = document.createElement('div');
        div.classList.add('object-box', 'gif-block');
        div.style.width = width;
        div.style.height = height;
        div.style.left = left;
        div.style.top = top;
        div.style.zIndex = zIndex;
        div.style.transform = `rotate(${rotation}deg)`;
        if(!src) src = prompt("Enter GIF URL", "https://media.giphy.com/media/LmNwrBhejkK9EFP504/giphy.gif");
        const img = document.createElement('img');
        img.src = src;
        div.appendChild(img);
        div.setAttribute('tabindex', 0);
        enableInteractivity(div);
        return div;
    }

    // Enable drag, resize, select interactions on element
    function enableInteractivity(el) {
        // Prevent text edit drag interference
        el.addEventListener('mousedown', e => {
            e.stopPropagation();
        });

        // Select on click - with shift for multi-selection
        el.addEventListener('click', e => {
            if (e.shiftKey) {
                const obj = objects.find(o => o.element === el);
                if (obj) selectObject(obj, true);
            } else {
                const obj = objects.find(o => o.element === el);
                if (obj) selectObject(obj, false);
            }
            e.preventDefault();
        });

        // Drag start
        el.addEventListener('mousedown', e => {
            if (!isDraggingEnabled) return;
            if (e.button !== 0) return; // only left click
            const obj = objects.find(o => o.element === el);
            if (!obj) return;

            draggedElement = obj;
            const rect = el.getBoundingClientRect();
            dragOffset.x = e.clientX - rect.left;
            dragOffset.y = e.clientY - rect.top;

            bringToFront(obj);

            // If multi-selected and drag starts on selected group
            if(!currentSelection.includes(obj)) {
                selectObject(obj, false);
            }

            document.addEventListener('mousemove', dragHandler);
            document.addEventListener('mouseup', dragEndHandler);
            e.preventDefault();
        });

        // Keyboard accessibility for deletion and movement
        el.addEventListener('keydown', e => {
            const obj = objects.find(o => o.element === el);
            if (!obj) return;

            switch (e.key) {
                case 'Delete':
                case 'Backspace':
                    removeObject(obj);
                    break;
                case 'ArrowUp':
                    moveObject(obj, 0, -snapGridSize);
                    break;
                case 'ArrowDown':
                    moveObject(obj, 0, snapGridSize);
                    break;
                case 'ArrowLeft':
                    moveObject(obj, -snapGridSize, 0);
                    break;
                case 'ArrowRight':
                    moveObject(obj, snapGridSize, 0);
                    break;
                case 'r':
                    rotateObject(obj, 15);
                    break;
                case 'Shift':
                case 'Control':
                    break; // ignore special keys
                default:
                    return;
            }
            e.preventDefault();
        });
    }

    // Drag handlers
    function dragHandler(e) {
        if (!draggedElement) return;
        e.preventDefault();

        // Calculate new positions for all selected elements (multi-drag support)
        currentSelection.forEach(obj => {
            if (!obj.element) return;
            let newX = e.clientX - dragOffset.x;
            let newY = e.clientY - dragOffset.y;

            // For group drag: offset relative positions by the initial dragged element position vs others
            if(obj !== draggedElement) {
                const rectCur = obj.element.getBoundingClientRect();
                const rectRef = draggedElement.element.getBoundingClientRect();
                const dx = rectCur.left - rectRef.left;
                const dy = rectCur.top - rectRef.top;
                newX += dx;
                newY += dy;
            }

            // Snap to grid
            newX = snapToGrid(newX);
            newY = snapToGrid(newY);

            // Bound inside container
            const maxX = container.clientWidth - obj.element.offsetWidth;
            const maxY = container.clientHeight - obj.element.offsetHeight;
            newX = Math.min(Math.max(0, newX), maxX);
            newY = Math.min(Math.max(0, newY), maxY);

            obj.element.style.left = newX + 'px';
            obj.element.style.top = newY + 'px';
        });
        updateInfoBox();
    }

    function dragEndHandler(e) {
        draggedElement = null;
        document.removeEventListener('mousemove', dragHandler);
        document.removeEventListener('mouseup', dragEndHandler);
        pushToUndo();
    }

    // Move object by dx, dy pixels
    function moveObject(obj, dx, dy) {
        if (!obj || !obj.element) return;
        let curX = parseInt(obj.element.style.left) || 0;
        let curY = parseInt(obj.element.style.top) || 0;
        let newX = snapToGrid(curX + dx);
        let newY = snapToGrid(curY + dy);

        newX = Math.min(Math.max(0, newX), container.clientWidth - obj.element.offsetWidth);
        newY = Math.min(Math.max(0, newY), container.clientHeight - obj.element.offsetHeight);

        obj.element.style.left = newX + 'px';
        obj.element.style.top = newY + 'px';
        pushToUndo();
        updateInfoBox();
    }

    // Rotate object by degrees
    function rotateObject(obj, degrees) {
        if (!obj || !obj.element) return;
        obj.rotation = ((obj.rotation || 0) + degrees) % 360;
        obj.element.style.transform = `rotate(${obj.rotation}deg)`;
        pushToUndo();
        updateInfoBox();
    }

    // Bring selected object to front by updating z-index
    function bringToFront(obj) {
        // Find max z-index
        const maxZ = Math.max(...objects.map(o => o.zIndex || 1), 1);
        obj.zIndex = maxZ + 1;
        obj.element.style.zIndex = obj.zIndex;
        pushToUndo();
    }

    // Enabling resizing feature
    function makeResizable(obj) {
        if (!isResizingEnabled) return;

        // Remove previous handles if any
        removeResizeHandles(obj.element);

        // Add 4 corner handles for resizing
        const handlesPos = [
            { name: 'nw', cursor: 'nwse-resize', left: '-10px', top: '-10px' },
            { name: 'ne', cursor: 'nesw-resize', right: '-10px', top: '-10px' },
            { name: 'sw', cursor: 'nesw-resize', left: '-10px', bottom: '-10px' },
            { name: 'se', cursor: 'nwse-resize', right: '-10px', bottom: '-10px' }
        ];

        handlesPos.forEach(pos => {
            const handle = document.createElement('div');
            handle.classList.add('resize-handle');
            if (pos.left) handle.style.left = pos.left;
            if (pos.right) handle.style.right = pos.right;
            if (pos.top) handle.style.top = pos.top;
            if (pos.bottom) handle.style.bottom = pos.bottom;
            handle.style.cursor = pos.cursor;

            // Resize logic
            handle.addEventListener('mousedown', e => {
                e.stopPropagation();
                if (e.button !== 0) return;

                const startX = e.clientX;
                const startY = e.clientY;
                const startWidth = obj.element.offsetWidth;
                const startHeight = obj.element.offsetHeight;
                const startLeft = parseInt(obj.element.style.left) || 0;
                const startTop = parseInt(obj.element.style.top) || 0;

                function resizeHandler(e2) {
                    e2.preventDefault();
                    let dx = e2.clientX - startX;
                    let dy = e2.clientY - startY;

                    let newWidth = startWidth;
                    let newHeight = startHeight;
                    let newLeft = startLeft;
                    let newTop = startTop;

                    switch(pos.name) {
                        case 'nw':
                            newWidth = startWidth - dx;
                            newHeight = startHeight - dy;
                            newLeft = startLeft + dx;
                            newTop = startTop + dy;
                            break;
                        case 'ne':
                            newWidth = startWidth + dx;
                            newHeight = startHeight - dy;
                            newTop = startTop + dy;
                            break;
                        case 'sw':
                            newWidth = startWidth - dx;
                            newHeight = startHeight + dy;
                            newLeft = startLeft + dx;
                            break;
                        case 'se':
                            newWidth = startWidth + dx;
                            newHeight = startHeight + dy;
                            break;
                    }

                    if (newWidth < 50) newWidth = 50;
                    if (newHeight < 50) newHeight = 50;

                    // Bound inside container
                    if (newLeft < 0) newLeft = 0;
                    if (newTop < 0) newTop = 0;
                    if (newLeft + newWidth > container.clientWidth) newWidth = container.clientWidth - newLeft;
                    if (newTop + newHeight > container.clientHeight) newHeight = container.clientHeight - newTop;

                    obj.element.style.width = newWidth + 'px';
                    obj.element.style.height = newHeight + 'px';
                    obj.element.style.left = newLeft + 'px';
                    obj.element.style.top = newTop + 'px';
                }

                function stopResize() {
                    document.removeEventListener('mousemove', resizeHandler);
                    document.removeEventListener('mouseup', stopResize);
                    pushToUndo();
                }

                document.addEventListener('mousemove', resizeHandler);
                document.addEventListener('mouseup', stopResize);
            });

            obj.element.appendChild(handle);
        });
    }

    // Remove all resize handles from an element
    function removeResizeHandles(el) {
        const handles = el.querySelectorAll('.resize-handle');
        handles.forEach(h => h.remove());
    }

    // Add rotation handle
    function makeRotatable(obj) {
        if (!isRotatingEnabled) {
            removeRotationHandles(obj.element);
            return;
        }
        removeRotationHandles(obj.element);

        const rotHandle = document.createElement('div');
        rotHandle.classList.add('rotation-handle');

        // Rotation logic
        rotHandle.addEventListener('mousedown', e => {
            e.stopPropagation();
            e.preventDefault();

            const center = obj.element.getBoundingClientRect();
            const cx = center.left + center.width/2;
            const cy = center.top + center.height/2;

            function onRotate(ev) {
                ev.preventDefault();
                const radians = Math.atan2(ev.clientY - cy, ev.clientX - cx);
                let deg = radians * (180 / Math.PI) + 90; // adjust, 0 degree points upwards
                if (deg < 0) deg += 360;
                deg = Math.round(deg);
                obj.rotation = deg;
                obj.element.style.transform = `rotate(${deg}deg)`;
            }
            function stopRotate() {
                document.removeEventListener('mousemove', onRotate);
                document.removeEventListener('mouseup', stopRotate);
                pushToUndo();
            }
            document.addEventListener('mousemove', onRotate);
            document.addEventListener('mouseup', stopRotate);
        });

        obj.element.appendChild(rotHandle);
    }

    // Remove rotation handles
    function removeRotationHandles(el) {
        const handles = el.querySelectorAll('.rotation-handle');
        handles.forEach(h => h.remove());
    }

    // Spawn new object by type
    function spawnObject(type) {
        let obj, id = generateId();
        const left = snapToGrid(container.clientWidth / 2 - 75) + 'px';
        const top = snapToGrid(container.clientHeight / 2 - 75) + 'px';

        switch(type) {
            case 'box':
                obj = {
                    id,
                    type,
                    element: createBoxElement('150px', '150px', '#ff6f61', left, top, 0, 1),
                    rotation: 0,
                    zIndex: 1
                };
                break;
            case 'text':
                obj = {
                    id,
                    type,
                    element: createTextBlockElement('180px', '60px', '#099', left, top, "Editable Text", true, 0, 1),
                    rotation: 0,
                    zIndex: 1
                };
                break;
            case 'image':
                obj = {
                    id,
                    type,
                    element: createImageBlockElement('150px', '150px', left, top, null, 0, 1),
                    imgSrc: null,
                    rotation: 0,
                    zIndex: 1
                };
                break;
            case 'gif':
                obj = {
                    id,
                    type,
                    element: createGifBlockElement('150px', '150px', left, top, null, 0, 1),
                    imgSrc: null,
                    rotation: 0,
                    zIndex: 1
                };
                break;
            default:
                console.warn('Unsupported object type:', type);
                return;
        }

        container.appendChild(obj.element);
        objects.push(obj);

        makeResizable(obj);
        makeRotatable(obj);
        selectObject(obj);
        pushToUndo();
    }

    // Remove object and its references
    function removeObject(obj) {
        if(!obj) return;
        if(container.contains(obj.element)) container.removeChild(obj.element);
        const idx = objects.findIndex(o => o.id === obj.id);
        if(idx > -1) objects.splice(idx, 1);
        if (currentSelection.includes(obj)) {
            currentSelection.splice(currentSelection.indexOf(obj),1);
        }
        updateInfoBox();
        pushToUndo();
    }

    // Clear all objects
    function clearAllObjects() {
        objects.forEach(o => {
            if(container.contains(o.element)) container.removeChild(o.element);
        });
        objects.length = 0;
        currentSelection.length = 0;
        updateInfoBox();
        pushToUndo();
    }

    // Update settings UI for selected object(s)
    function updateSettingsBox() {
        const boxSizeValue = currentSelection[0] ? currentSelection[0].element.offsetWidth : 100;
        const rotationValue = currentSelection[0] ? (currentSelection[0].rotation || 0) : 0;
        const colorValue = (currentSelection[0] && (currentSelection[0].type === 'box' || currentSelection[0].type === 'text')) ? currentSelection[0].element.style.backgroundColor : '#ff6f61';
        const isDragChecked = isDraggingEnabled;
        const isResizeChecked = isResizingEnabled;
        const isRotateChecked = isRotatingEnabled;
        const is3DChecked = is3DViewEnabled;

        settingsBox.innerHTML = `
            <h3>3D Manipulation Tool</h3>

            <label>Select Object Type:</label>
            <select id="objectType">
                <option value="box">3D Box</option>
                <option value="text">Text Block</option>
                <option value="image">Image Block</option>
                <option value="gif">GIF Block</option>
            </select>
            <button id="addObjectBtn">Add Object</button>
            <hr>

            <div ${currentSelection.length === 0 ? 'style="display:none"' : ''}>
                <strong>Selected Object Settings (${currentSelection.length})</strong><br><br>

                <label>Width:</label>
                <input type="range" id="widthSlider" min="50" max="600" value="${boxSizeValue}" />
                <span id="widthVal">${boxSizeValue}px</span><br>

                <label>Height:</label>
                <input type="range" id="heightSlider" min="50" max="600" value="${boxSizeValue}" />
                <span id="heightVal">${boxSizeValue}px</span><br>

                <label>Rotation:</label>
                <input type="range" id="rotationSlider" min="0" max="360" value="${rotationValue}" />
                <span id="rotationVal">${rotationValue}°</span><br>

                <label>Background Color:</label>
                <input type="color" id="colorPicker" value="${rgbToHex(colorValue)}" />
                <br><br>

                <button id="removeSelectedBtn">Remove Selected</button>
                <button id="bringFrontBtn">Bring to Front</button>
                <button id="sendBackBtn">Send to Back</button>
            </div>

            <hr>

            <label><input type="checkbox" id="dragToggle" ${isDragChecked ? 'checked' : ''} /> Enable Dragging</label><br>
            <label><input type="checkbox" id="resizeToggle" ${isResizeChecked ? 'checked' : ''} /> Enable Resizing</label><br>
            <label><input type="checkbox" id="rotateToggle" ${isRotateChecked ? 'checked' : ''} /> Enable Rotation</label><br>
            <label><input type="checkbox" id="snapToggle" checked /> Enable Snap to Grid</label><br>
            <label><input type="checkbox" id="gridToggle" checked /> Show Grid</label><br>

            <hr>
            <button id="undoBtn">Undo (Ctrl+Z)</button>
            <button id="redoBtn">Redo (Ctrl+Y)</button>
            <button id="saveBtn">Save Layout</button>
            <button id="loadBtn">Load Layout</button>
            <button id="clearBtn">Clear All</button>
            <hr>
            <button id="toggle3DBtn">${is3DChecked ? 'Disable' : 'Enable'} 3D View (T)</button>
        `;

        // Controls events
        const addButton = settingsBox.querySelector('#addObjectBtn');
        addButton.onclick = () => {
            const select = settingsBox.querySelector('#objectType');
            spawnObject(select.value);
        };

        if(currentSelection.length > 0) {
            const widthSlider = settingsBox.querySelector('#widthSlider');
            const heightSlider = settingsBox.querySelector('#heightSlider');
            const rotationSlider = settingsBox.querySelector('#rotationSlider');
            const colorPicker = settingsBox.querySelector('#colorPicker');
            const removeSelectedBtn = settingsBox.querySelector('#removeSelectedBtn');
            const bringFrontBtn = settingsBox.querySelector('#bringFrontBtn');
            const sendBackBtn = settingsBox.querySelector('#sendBackBtn');

            widthSlider.oninput = () => {
                settingsBox.querySelector('#widthVal').textContent = widthSlider.value + 'px';
                currentSelection.forEach(obj => {
                    obj.element.style.width = widthSlider.value + 'px';
                });
                pushToUndo();
            };
            heightSlider.oninput = () => {
                settingsBox.querySelector('#heightVal').textContent = heightSlider.value + 'px';
                currentSelection.forEach(obj => {
                    obj.element.style.height = heightSlider.value + 'px';
                });
                pushToUndo();
            };
            rotationSlider.oninput = () => {
                settingsBox.querySelector('#rotationVal').textContent = rotationSlider.value + '°';
                currentSelection.forEach(obj => {
                    obj.rotation = parseInt(rotationSlider.value);
                    obj.element.style.transform = `rotate(${obj.rotation}deg)`;
                });
                pushToUndo();
            };
            colorPicker.oninput = () => {
                currentSelection.forEach(obj => {
                    if(obj.type === 'box' || obj.type === 'text') {
                        obj.element.style.backgroundColor = colorPicker.value;
                    }
                });
                pushToUndo();
            };
            removeSelectedBtn.onclick = () => {
                currentSelection.slice().forEach(removeObject);
                clearSelection();
            };
            bringFrontBtn.onclick = () => {
                currentSelection.forEach(bringToFront);
                updateInfoBox();
            };
            sendBackBtn.onclick = () => {
                currentSelection.forEach(sendToBack);
                updateInfoBox();
            };
        }

        // Toggles
        settingsBox.querySelector('#dragToggle').onchange = e => {
            isDraggingEnabled = e.target.checked;
        };
        settingsBox.querySelector('#resizeToggle').onchange = e => {
            isResizingEnabled = e.target.checked;
            objects.forEach(makeResizable);
        };
        settingsBox.querySelector('#rotateToggle').onchange = e => {
            isRotatingEnabled = e.target.checked;
            objects.forEach(makeRotatable);
        };
        settingsBox.querySelector('#snapToggle').onchange = e => {
            // Enable snapping or not
            // can be used in drag handlers if expanded
        };
        settingsBox.querySelector('#gridToggle').onchange = e => {
            grid.style.display = e.target.checked ? 'block' : 'none';
        };

        // Undo and redo
        settingsBox.querySelector('#undoBtn').onclick = undo;
        settingsBox.querySelector('#redoBtn').onclick = redo;

        // Save/load/clear
        settingsBox.querySelector('#saveBtn').onclick = saveLayout;
        settingsBox.querySelector('#loadBtn').onclick = loadLayout;
        settingsBox.querySelector('#clearBtn').onclick = () => {
            if(confirm('Clear all objects? This cannot be undone.')) {
                clearAllObjects();
            }
        };

        // 3D toggle
        settingsBox.querySelector('#toggle3DBtn').onclick = toggle3DView;
    }

    // Convert rgb color to hex string
    function rgbToHex(rgb) {
        if(!rgb) return '#ff6f61';
        const ctx = document.createElement('canvas').getContext('2d');
        ctx.fillStyle = rgb;
        return ctx.fillStyle; // browser converts rgb -> hex string automatically
    }

    // Bring object to front (zIndex max+1)
    function bringToFront(obj) {
        const maxZ = Math.max(...objects.map(o => o.zIndex || 1), 1);
        obj.zIndex = maxZ + 1;
        obj.element.style.zIndex = obj.zIndex;
        pushToUndo();
    }
    // Send object to back (zIndex 0 or minimal)
    function sendToBack(obj) {
        const minZ = Math.min(...objects.map(o => o.zIndex || 1), 1);
        obj.zIndex = minZ - 1;
        obj.element.style.zIndex = obj.zIndex;
        pushToUndo();
    }

    // Undo function
    function undo() {
        if (undoStack.length === 0) {
            infoBox.textContent = "Nothing to undo";
            return;
        }
        const lastState = undoStack.pop();
        redoStack.push(objects.map(obj => ({
            id: obj.id,
            type: obj.type,
            style: { ...obj.element.style },
            innerHTML: obj.element.innerHTML,
            contentEditable: obj.element.contentEditable,
            imgSrc: obj.imgSrc || null,
            rotation: obj.rotation || 0,
            zIndex: obj.zIndex || 1
        })));
        loadState(lastState);
        infoBox.textContent = "Undo performed";
    }

    // Redo function
    function redo() {
        if (redoStack.length === 0) {
            infoBox.textContent = "Nothing to redo";
            return;
        }
        const nextState = redoStack.pop();
        undoStack.push(objects.map(obj => ({
            id: obj.id,
            type: obj.type,
            style: { ...obj.element.style },
            innerHTML: obj.element.innerHTML,
            contentEditable: obj.element.contentEditable,
            imgSrc: obj.imgSrc || null,
            rotation: obj.rotation || 0,
            zIndex: obj.zIndex || 1
        })));
        loadState(nextState);
        infoBox.textContent = "Redo performed";
    }

    // Save layout to localStorage
    function saveLayout() {
        try {
            localStorage.setItem('layout', JSON.stringify(objects.map(o => ({
                id: o.id,
                type: o.type,
                style: { ...o.element.style },
                innerHTML: o.element.innerHTML,
                contentEditable: o.element.contentEditable,
                imgSrc: o.imgSrc || null,
                rotation: o.rotation || 0,
                zIndex: o.zIndex || 1
            }))));
            infoBox.textContent = "Layout saved";
        } catch(err) {
            console.error("Saving failed", err);
            infoBox.textContent = "Save failed";
        }
    }

    // Load layout from localStorage
    function loadLayout() {
        try {
            const saved = localStorage.getItem('layout');
            if (saved) {
                const data = JSON.parse(saved);
                loadState(data);
                infoBox.textContent = "Layout loaded";
            } else {
                infoBox.textContent = "No layout saved";
            }
        } catch(err) {
            console.error("Load failed", err);
            infoBox.textContent = "Load failed";
        }
    }

    // Toggle 3D view by adding perspective and subtle 3D transform animations
    function toggle3DView() {
        is3DViewEnabled = !is3DViewEnabled;
        if (is3DViewEnabled) {
            container.style.perspective = '1200px';
            container.style.transformStyle = 'preserve-3d';
            // Add subtle 3D rotation animation to objects
            objects.forEach(obj => {
                obj.element.style.transition = 'transform 0.5s ease';
                obj.element.style.transform += ' translateZ(20px)';
            });
            infoBox.textContent = "3D View enabled: Use WASD to move selected objects";
        } else {
            container.style.perspective = '';
            objects.forEach(obj => {
                obj.element.style.transition = 'transform 0.5s ease';
                // Reset translateZ
                let newTransform = obj.element.style.transform.replace(/translateZ\(.*?\)/g, '');
                obj.element.style.transform = newTransform;
            });
            infoBox.textContent = "3D View disabled";
        }
        updateSettingsBox();
    }

    // Handle keyboard shortcuts globally
    document.addEventListener('keydown', e => {
        // Ctrl+Z and Ctrl+Y for undo/redo
        if (e.ctrlKey && e.key.toLowerCase() === 'z') {
            undo();
            e.preventDefault();
        }
        if (e.ctrlKey && e.key.toLowerCase() === 'y') {
            redo();
            e.preventDefault();
        }
        // T toggles 3D view
        if (e.key.toLowerCase() === 't') {
            toggle3DView();
        }
        // Delete removes selected objects
        if (e.key === 'Delete' || e.key === 'Backspace') {
            currentSelection.slice().forEach(removeObject);
            clearSelection();
            e.preventDefault();
        }
    });

    // Clicking on empty container clears selection
    container.addEventListener('mousedown', e => {
        if (e.target === container) {
            clearSelection();
        }
    });

    // Initialize UI on page load
    function initializeUI() {
        updateSettingsBox();
        infoBox.textContent = 'Ready! Click "Add Object" to begin. Shift+Click multi-select.';
        grid.style.display = 'block';
    }

    initializeUI();

    // Auto-save every 30s to localStorage
    autoSaveInterval = setInterval(() => {
        saveLayout();
    }, 30000);

    console.log("Enhanced 3D manipulation tool ready");

    // Expose some API for debugging (optional)
    window._editor = {
        spawnObject, selectObject, removeObject, clearSelection, undo, redo, saveLayout, loadLayout
    };

})();