Write the full complete code dont skip anything, write the full code with the new edits you did just write the full complete code,fix the layers right now its ugly and doesnt' look how adobe illustoator does it all make the icon not use font awesome anymore make them use ui icons instead, fix the toggle code editor make it fit better, also make the graident editor have more graident and more customizable, also make the ui look similar to our current ui theme: <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Enhanced Notion-like Canvas</title>
    <!-- Include Font Awesome for Icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha384-Piv4xVNRyMGpqk95vgO69tpI5bfUzsjrF3KYce1mlzUHp868f1fJD0fPaHlSqtvV" crossorigin="anonymous">
    <style>
        /* General Styles */
        body, html {
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen,
            Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
            color: #37352f;
            background-color: #f5f5f5;
        }
        .container {
            display: flex;
            height: 100%;
        }
        .toolbar {
            width: 60px;
            background-color: #fbfbfa;
            border-right: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding-top: 20px;
            position: relative;
            z-index: 2;
        }
        .tool-button {
            width: 40px;
            height: 40px;
            border: none;
            background-color: transparent;
            cursor: pointer;
            margin-bottom: 10px;
            border-radius: 5px;
            display: flex;
            justify-content: center;
            align-items: center;
            transition: background-color 0.3s ease;
            color: #37352f;
            position: relative;
            font-size: 20px;
        }
        .tool-button:hover {
            background-color: #f1f1ef;
        }
        .tool-button i {
            pointer-events: none;
        }
        .tool-button .tooltip {
            visibility: hidden;
            background-color: #37352f;
            color: #fff;
            text-align: center;
            border-radius: 5px;
            padding: 5px;
            position: absolute;
            left: 45px;
            z-index: 1;
            font-size: 12px;
            white-space: nowrap;
        }
        .tool-button:hover .tooltip {
            visibility: visible;
        }
        .tool-dropdown {
            position: relative;
        }
        .shape-menu {
            display: none;
            position: absolute;
            top: 50px;
            left: 0;
            background-color: #fbfbfa;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            z-index: 1000;
            padding: 5px;
            flex-direction: column;
        }
        .shape-menu .tool-button {
            margin: 5px;
        }
        .shape-menu .tool-button:hover .tooltip {
            visibility: hidden;
        }
        .canvas-area {
            flex: 1;
            background-color: #f7f6f3;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            padding: 20px;
            position: relative;
            overflow: auto;
        }
        .canvas-controls {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            position: relative;
            z-index: 1;
        }
        .canvas-controls button,
        .canvas-controls input[type="color"] {
            background-color: #e0e0e0;
            color: #37352f;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
            margin-right: 10px;
            display: flex;
            align-items: center;
        }
        .canvas-controls button:hover,
        .canvas-controls input[type="color"]:hover {
            background-color: #d0d0d0;
        }
        .canvas-container {
            position: relative;
            width: 800px;
            height: 600px;
            background-color: #fff;
            border: 1px solid #e0e0e0;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            cursor: default;
        }
        .canvas {
            width: 100%;
            height: 100%;
            position: relative;
            overflow: hidden;
            background-color: #ffffff;
        }
        .grid {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-image: linear-gradient(to right, #f0f0f0 1px, transparent 1px),
            linear-gradient(to bottom, #f0f0f0 1px, transparent 1px);
            background-size: 20px 20px;
            pointer-events: none;
            display: none;
        }
        .chat-area {
            width: 350px;
            background-color: #fbfbfa;
            border-left: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
            z-index: 1;
        }
        .chat-header {
            padding: 16px;
            font-size: 16px;
            font-weight: 600;
            border-bottom: 1px solid #e0e0e0;
            background-color: #f7f6f3;
        }
        .chat-messages {
            flex: 1;
            overflow-y: auto;
            padding: 16px;
        }
        .message {
            margin-bottom: 12px;
            padding: 8px 12px;
            background-color: #f1f1ef;
            border-radius: 8px;
            font-size: 14px;
        }
        .chat-input {
            border-top: 1px solid #e0e0e0;
            padding: 16px;
            background-color: #f7f6f3;
        }
        .chat-input form {
            display: flex;
            align-items: center;
        }
        .chat-input input {
            flex: 1;
            padding: 10px 12px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            font-size: 14px;
            background-color: #ffffff;
        }
        .chat-input button {
            margin-left: 8px;
            padding: 10px 16px;
            background-color: #e0e0e0;
            color: #37352f;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
        }
        .chat-input button:hover {
            background-color: #d0d0d0;
        }
        .canvas-text, .canvas-media, .canvas-shape {
            position: absolute;
            cursor: move;
            user-select: none;
            padding: 5px;
            min-width: 50px;
            min-height: 20px;
        }
        .canvas-text {
            background-color: transparent;
            overflow: auto;
        }
        .canvas-media img {
            max-width: 100%;
            max-height: 100%;
            display: block;
        }
        .canvas-media {
            padding: 0;
            overflow: hidden;
        }
        .canvas-shape {
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .text-controls, .media-controls, .shape-controls {
            position: absolute;
            background-color: #ffffff;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            padding: 5px;
            display: none;
            z-index: 1000;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            flex-wrap: nowrap;
            white-space: nowrap;
            gap: 5px;
            align-items: center;
        }
        .text-controls input[type="color"],
        .media-controls input[type="color"],
        .shape-controls input[type="color"] {
            width: 30px;
            height: 30px;
            border: none;
            border-radius: 50%;
            overflow: hidden;
            cursor: pointer;
            padding: 0;
            background-color: transparent;
        }
        .text-controls input[type="number"],
        .media-controls input[type="number"],
        .shape-controls input[type="number"] {
            width: 50px;
            padding: 5px;
            border: 1px solid #e0e0e0;
            border-radius: 3px;
        }
        .text-controls select,
        .media-controls select,
        .shape-controls select {
            height: 30px;
            padding: 5px;
            border: 1px solid #e0e0e0;
            border-radius: 3px;
        }
        .text-controls button,
        .media-controls button,
        .shape-controls button {
            padding: 5px;
            background-color: #f1f1ef;
            border: 1px solid #e0e0e0;
            border-radius: 3px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            display: flex;
            align-items: center;
        }
        .text-controls button:hover,
        .media-controls button:hover,
        .shape-controls button:hover {
            background-color: #e0e0e0;
        }
        .opacity-slider {
            width: 100px;
        }
        .opacity-slider::-webkit-slider-thumb {
            -webkit-appearance: none;
            appearance: none;
            width: 14px;
            height: 14px;
            border-radius: 50%;
            background: #37352f;
            cursor: pointer;
        }
        .canvas-outline {
            position: absolute;
            top: -20px;
            left: -20px;
            right: -20px;
            bottom: -20px;
            border: 2px solid #a020f0; /* Purple color */
            pointer-events: none;
        }
        /* Shape Specific Styles */
        .shape-rectangle {
            background-color: #3498db;
            border-radius: 0;
        }
        .shape-ellipse {
            background-color: #e74c3c;
            border-radius: 50%;
        }
        .shape-star {
            width: 100px;
            height: 100px;
            background: transparent;
            position: absolute;
            clip-path: polygon(
                50% 0%, 
                61% 35%, 
                98% 35%, 
                68% 57%, 
                79% 91%, 
                50% 70%, 
                21% 91%, 
                32% 57%, 
                2% 35%, 
                39% 35%
            );
            background-color: #f1c40f;
        }
        .shape-triangle {
            width: 0;
            height: 0;
            border-left: 50px solid transparent;
            border-right: 50px solid transparent;
            border-bottom: 100px solid #2ecc71;
            background: none;
        }
        /* Additional Shapes */
        .shape-pentagon {
            width: 100px;
            height: 100px;
            clip-path: polygon(50% 0%, 95% 35%, 75% 90%, 25% 90%, 5% 35%);
            background-color: #8e44ad;
        }
        .shape-hexagon {
            width: 100px;
            height: 100px;
            clip-path: polygon(25% 0%, 75% 0%, 100% 50%, 75% 100%, 25% 100%, 0% 50%);
            background-color: #e67e22;
        }
        .shape-octagon {
            width: 100px;
            height: 100px;
            clip-path: polygon(30% 0%, 70% 0%, 100% 30%, 100% 70%, 70% 100%, 30% 100%, 0% 70%, 0% 30%);
            background-color: #2c3e50;
        }
        /* Gradient Tool */
        .gradient-tool {
            position: absolute;
            top: 60px;
            left: 70px;
            background-color: #ffffff;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
            padding: 10px;
            display: none;
            flex-direction: column;
            gap: 10px;
            z-index: 1000;
        }
        .gradient-option {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .gradient-preview {
            width: 30px;
            height: 30px;
            border: 1px solid #e0e0e0;
            border-radius: 3px;
        }
        /* Resize Handles */
        .resize-handle {
            position: absolute;
            width: 10px;
            height: 10px;
            background-color: #fff;
            border: 1px solid #000;
            z-index: 10;
            cursor: pointer;
        }
        .resize-handle.top-left {
            left: -5px;
            top: -5px;
            cursor: nwse-resize;
        }
        .resize-handle.top-right {
            right: -5px;
            top: -5px;
            cursor: nesw-resize;
        }
        .resize-handle.bottom-left {
            left: -5px;
            bottom: -5px;
            cursor: nesw-resize;
        }
        .resize-handle.bottom-right {
            right: -5px;
            bottom: -5px;
            cursor: nwse-resize;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="toolbar">
            <button class="tool-button" onclick="addText()" title="Add Text">
                <i class="fas fa-font"></i>
                <span class="tooltip">Add Text</span>
            </button>
            <button class="tool-button" onclick="addMedia()" title="Add Media">
                <i class="fas fa-image"></i>
                <span class="tooltip">Add Media</span>
            </button>
            <button class="tool-button" onclick="copyElements()" title="Copy">
                <i class="fas fa-copy"></i>
                <span class="tooltip">Copy (Ctrl+C)</span>
            </button>
            <button class="tool-button" onclick="pasteElements()" title="Paste">
                <i class="fas fa-paste"></i>
                <span class="tooltip">Paste (Ctrl+V)</span>
            </button>
            <div class="tool-dropdown">
                <button class="tool-button shape-tool-button" onclick="toggleShapeMenu(event)" title="Add Shape">
                    <i class="fas fa-shapes"></i>
                    <span class="tooltip">Add Shape</span>
                </button>
                <div class="shape-menu" id="shapeMenu">
                    <button class="tool-button" onclick="selectShape('rectangle')" title="Rectangle">
                        <i class="fas fa-square"></i>
                    </button>
                    <button class="tool-button" onclick="selectShape('ellipse')" title="Ellipse">
                        <i class="fas fa-circle"></i>
                    </button>
                    <button class="tool-button" onclick="selectShape('star')" title="Star">
                        <i class="fas fa-star"></i>
                    </button>
                    <button class="tool-button" onclick="selectShape('triangle')" title="Triangle">
                        <i class="fas fa-exclamation-triangle"></i>
                    </button>
                    <!-- New Shapes -->
                    <button class="tool-button" onclick="selectShape('pentagon')" title="Pentagon">
                        <i class="fas fa-draw-polygon"></i>
                    </button>
                    <button class="tool-button" onclick="selectShape('hexagon')" title="Hexagon">
                        <i class="fas fa-hexagon"></i>
                    </button>
                    <button class="tool-button" onclick="selectShape('octagon')" title="Octagon">
                        <i class="fas fa-stop"></i>
                    </button>
                </div>
            </div>
            <button class="tool-button" onclick="toggleGradientTool()" title="Gradient Tool">
                <i class="fas fa-paint-brush"></i>
                <span class="tooltip">Gradient Tool</span>
            </button>
            <button class="tool-button" onclick="deleteElement()" title="Delete">
                <i class="fas fa-trash"></i>
                <span class="tooltip">Delete (Delete)</span>
            </button>
            <button class="tool-button" onclick="undo()" title="Undo">
                <i class="fas fa-undo"></i>
                <span class="tooltip">Undo (Ctrl+Z)</span>
            </button>
            <button class="tool-button" onclick="redo()" title="Redo">
                <i class="fas fa-redo"></i>
                <span class="tooltip">Redo (Ctrl+Y)</span>
            </button>
        </div>
        <div class="canvas-area">
            <div class="canvas-controls">
                <button class="toggle-grid" onclick="toggleGrid()">
                    Toggle Grid
                </button>
                <input type="color" id="canvasColorPicker" oninput="changeCanvasColor(this.value)" title="Canvas Color">
                <button class="toggle-code" onclick="toggleCode()">
                    Toggle Code
                </button>
            </div>
            <div class="canvas-container" id="canvasContainer">
                <div class="canvas" id="canvas">
                    <div class="grid" id="grid"></div>
                </div>
                <div class="canvas-outline"></div>
            </div>
            <div class="gradient-tool" id="gradientTool">
                <div class="gradient-option">
                    <span>Gradient:</span>
                    <select id="gradientType" onchange="applyGradient()">
                        <option value="linear">Linear</option>
                        <option value="radial">Radial</option>
                    </select>
                </div>
                <div class="gradient-option">
                    <span>Color 1:</span>
                    <input type="color" id="gradientColor1" value="#ff0000" onchange="applyGradient()">
                </div>
                <div class="gradient-option">
                    <span>Color 2:</span>
                    <input type="color" id="gradientColor2" value="#0000ff" onchange="applyGradient()">
                </div>
                <button onclick="applyGradient()">Apply Gradient</button>
            </div>
            <div class="layer-panel" id="layerPanel">
                <div class="layer-panel-header" id="layerPanelHeader">Layers</div>
                <ul class="layer-list" id="layerList"></ul>
            </div>
        </div>
        <div class="code-area" id="codeArea">
            <pre id="code"></pre>
        </div>
        <div class="chat-area">
            <div class="chat-header">
                Chat
            </div>
            <div class="chat-messages">
                <div class="message">Hello! How can I help you with your design?</div>
                <div class="message">You can use the canvas on the left to create your poster.</div>
            </div>
            <div class="chat-input">
                <form>
                    <input type="text" placeholder="Type a message...">
                    <button type="submit">Send</button>
                </form>
            </div>
        </div>
        <div id="text-controls-wrapper"></div>
        <div id="media-controls-wrapper"></div>
        <div id="shape-controls-wrapper"></div>
    </div>

    <script>
        let currentShape = null;
        let copiedElement = null;
        let codeArea = document.getElementById('codeArea');
        let codeElement = document.getElementById('code');
        let gradientTool = document.getElementById('gradientTool');
        let undoStack = [];
        let redoStack = [];

        function toggleGrid() {
            const grid = document.getElementById('grid');
            grid.style.display = grid.style.display === 'none' ? 'block' : 'none';
        }

        function changeCanvasColor(color) {
            const canvas = document.getElementById('canvas');
            canvas.style.backgroundColor = color;
            updateCode(); // Update code when background color changes
            saveState();
        }

        function addText() {
            const canvas = document.getElementById('canvas');
            const text = document.createElement('div');
            text.className = 'canvas-text';
            text.id = 'text-' + Date.now();
            const textContent = document.createElement('div');
            textContent.contentEditable = true;
            textContent.textContent = 'Double click to edit';
            text.appendChild(textContent);
            text.style.left = '50px';
            text.style.top = '50px';
            text.style.width = '200px';
            text.style.height = '50px';
            text.style.fontSize = '16px';
            text.style.color = '#000000';
            text.style.opacity = 1;

            canvas.appendChild(text);
            makeDraggable(text);
            makeSelectable(text);
            addTextControls(text);
            text.addEventListener('dblclick', function() {
                textContent.focus();
                document.execCommand('selectAll', false, null);
            });
            text.addEventListener('input', function() {
                updateLayerPanel();
                updateCode();
                saveState();
            });
            updateLayerPanel();
            updateCode();
            saveState();
        }

        function addMedia() {
            const input = document.createElement('input');
            input.type = 'file';
            input.accept = 'image/*';
            input.onchange = function(event) {
                const file = event.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = function(e) {
                        const canvas = document.getElementById('canvas');
                        const media = document.createElement('div');
                        media.className = 'canvas-media';
                        media.id = 'media-' + Date.now();
                        const img = document.createElement('img');
                        img.src = e.target.result;
                        img.dataset.scale = 1;
                        img.style.transformOrigin = 'center center';
                        img.onwheel = (e) => {
                            e.preventDefault();
                            zoomMedia(img, e);
                        };
                        img.ondragstart = () => false;
                        media.appendChild(img);

                        img.onload = function() {
                            let scale = 1;
                            if (img.naturalWidth > 400 || img.naturalHeight > 300) {
                                // Scale down if image is too big
                                scale = Math.min(400 / img.naturalWidth, 300 / img.naturalHeight);
                            }
                            media.style.width = img.naturalWidth * scale + 'px';
                            media.style.height = img.naturalHeight * scale + 'px';
                            media.style.left = '50px';
                            media.style.top = '50px';
                            media.style.opacity = 1;
                            img.style.width = '100%';
                            img.style.height = '100%';
                        };

                        canvas.appendChild(media);
                        makeDraggable(media);
                        makeSelectable(media);
                        addMediaControls(media);
                        updateLayerPanel();
                        updateCode();
                        saveState();
                    };
                    reader.readAsDataURL(file);
                }
            };
            input.click();
        }

        function toggleShapeMenu(event) {
            event.stopPropagation(); // Prevent event from bubbling up
            const menu = document.getElementById('shapeMenu');
            menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
        }

        document.addEventListener('click', function(e) {
            const menu = document.getElementById('shapeMenu');
            const button = document.querySelector('.tool-dropdown .tool-button');
            if (menu.style.display === 'block' && !menu.contains(e.target) && !button.contains(e.target)) {
                menu.style.display = 'none';
            }
        });

        function selectShape(shapeType) {
            currentShape = shapeType;
            const menu = document.getElementById('shapeMenu');
            menu.style.display = 'none';
        }

        document.getElementById('canvas').addEventListener('click', function(event) {
            if (currentShape) {
                const canvas = document.getElementById('canvas');
                const rect = canvas.getBoundingClientRect();
                const x = event.clientX - rect.left;
                const y = event.clientY - rect.top;
                addShape(currentShape, x, y);
                currentShape = null;
                updateCode();
                saveState();
            } else {
                clearSelection();
            }
        });

        function addShape(shapeType, x, y) {
            const canvas = document.getElementById('canvas');
            const shape = document.createElement('div');
            shape.className = `canvas-shape shape-${shapeType}`;
            shape.id = `${shapeType}-${Date.now()}`;
            shape.style.left = `${x}px`;
            shape.style.top = `${y}px`;
            shape.dataset.scale = 1;
            shape.style.opacity = 1;

            if (shapeType === 'triangle') {
                shape.style.width = '0';
                shape.style.height = '0';
            } else if (shapeType === 'star' || shapeType === 'pentagon' || shapeType === 'hexagon' || shapeType === 'octagon') {
                shape.style.width = '100px';
                shape.style.height = '100px';
            } else {
                shape.style.width = '100px';
                shape.style.height = '100px';
            }

            canvas.appendChild(shape);
            makeDraggable(shape);
            makeSelectable(shape);
            addShapeControls(shape, shapeType);
            shape.onwheel = (e) => {
                e.preventDefault();
                zoomShape(shape, e);
            };
            updateLayerPanel();
            updateCode();
            saveState();
        }

        function makeDraggable(element) {
            let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            const canvas = document.getElementById('canvas');
            let isResizing = false;
            let currentHandle;

            if (element.classList.contains('canvas-text') || element.classList.contains('canvas-media') || element.classList.contains('canvas-shape')) {
                addResizeHandles(element);
            }

            element.onmousedown = dragMouseDown;

            function dragMouseDown(e) {
                if (e.target.classList.contains('resize-handle')) {
                    isResizing = true;
                    currentHandle = e.target;
                    e.stopPropagation();
                    document.onmouseup = closeDragElement;
                    document.onmousemove = elementResize;
                } else {
                    e = e || window.event;
                    e.preventDefault();
                    e.stopPropagation();
                    pos3 = e.clientX;
                    pos4 = e.clientY;
                    document.onmouseup = closeDragElement;
                    document.onmousemove = elementDrag;
                    clearSelection();
                    element.classList.add('selected');
                    showElementControls(element);
                }
            }

            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;

                let newTop = element.offsetTop - pos2;
                let newLeft = element.offsetLeft - pos1;

                // Constraints so that the element does not leave the canvas
                let maxTop = canvas.offsetHeight - element.offsetHeight;
                let maxLeft = canvas.offsetWidth - element.offsetWidth;

                if (newTop < 0) newTop = 0;
                if (newLeft < 0) newLeft = 0;
                if (newTop > maxTop) newTop = maxTop;
                if (newLeft > maxLeft) newLeft = maxLeft;

                element.style.top = newTop + "px";
                element.style.left = newLeft + "px";

                // Update controls position if visible
                const controls = document.querySelector(`.shape-controls[data-shape-id="${element.id}"]`) ||
                                 document.querySelector(`.text-controls[data-text-id="${element.id}"]`) ||
                                 document.querySelector(`.media-controls[data-media-id="${element.id}"]`);
                if (controls && controls.style.display === 'flex') {
                    controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                    controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
                }
            }

            function elementResize(e) {
                e.preventDefault();
                const rect = element.getBoundingClientRect();
                let width, height;
                if (currentHandle.classList.contains('bottom-right')) {
                    width = e.clientX - rect.left;
                    height = e.clientY - rect.top;
                } else if (currentHandle.classList.contains('bottom-left')) {
                    width = rect.right - e.clientX;
                    height = e.clientY - rect.top;
                    element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
                } else if (currentHandle.classList.contains('top-right')) {
                    width = e.clientX - rect.left;
                    height = rect.bottom - e.clientY;
                    element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
                } else if (currentHandle.classList.contains('top-left')) {
                    width = rect.right - e.clientX;
                    height = rect.bottom - e.clientY;
                    element.style.left = element.offsetLeft + (e.clientX - rect.left) + 'px';
                    element.style.top = element.offsetTop + (e.clientY - rect.top) + 'px';
                }
                if (width > 20 && height > 20) {
                    element.style.width = width + 'px';
                    element.style.height = height + 'px';

                    // For images, adjust the img size
                    if (element.classList.contains('canvas-media')) {
                        const img = element.querySelector('img');
                        img.style.width = '100%';
                        img.style.height = '100%';
                    }
                }
                updateCode();
                saveState();
            }

            function closeDragElement() {
                document.onmouseup = null;
                document.onmousemove = null;
                isResizing = false;
                currentHandle = null;
                updateCode(); // Update code after dragging completes
                saveState();
            }
        }

        function addResizeHandles(element) {
            const handles = ['top-left', 'top-right', 'bottom-left', 'bottom-right'];
            handles.forEach(handle => {
                const div = document.createElement('div');
                div.className = 'resize-handle ' + handle;
                element.appendChild(div);
            });
        }

        function makeSelectable(element) {
            element.addEventListener('click', function(e) {
                e.stopPropagation(); // prevent event bubbling
                clearSelection(); // Deselect others
                element.classList.add('selected'); // apply selected class
                showElementControls(element);
            });
        }

        function clearSelection() {
            document.querySelectorAll('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected').forEach(el => {
                el.classList.remove('selected');
            });
            hideAllControls();
        }

        function showElementControls(element) {
            hideAllControls();
            if (element.classList.contains('canvas-text')) {
                const controls = document.querySelector(`.text-controls[data-text-id="${element.id}"]`);
                controls.style.display = 'flex';
                controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
            } else if (element.classList.contains('canvas-media')) {
                const controls = document.querySelector(`.media-controls[data-media-id="${element.id}"]`);
                controls.style.display = 'flex';
                controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
            } else if (element.classList.contains('canvas-shape')) {
                const controls = document.querySelector(`.shape-controls[data-shape-id="${element.id}"]`);
                controls.style.display = 'flex';
                controls.style.top = `${element.offsetTop - controls.offsetHeight - 10}px`;
                controls.style.left = `${element.offsetLeft + (element.offsetWidth / 2) - (controls.offsetWidth / 2)}px`;
            }
        }

        function hideAllControls() {
            document.querySelectorAll('.text-controls, .media-controls, .shape-controls').forEach(control => {
                control.style.display = 'none';
            });
            gradientTool.style.display = 'none';
        }

        function addTextControls(textElement) {
            const wrapper = document.getElementById('text-controls-wrapper');
            const controls = document.createElement('div');
            controls.className = 'text-controls';
            controls.setAttribute('data-text-id', textElement.id);
            controls.style.display = 'none';
            controls.innerHTML = `
                <button onclick="toggleBold(this, '${textElement.id}')" title="Bold"><i class="fas fa-bold"></i></button>
                <button onclick="toggleItalic(this, '${textElement.id}')" title="Italic"><i class="fas fa-italic"></i></button>
                <button onclick="toggleUnderline(this, '${textElement.id}')" title="Underline"><i class="fas fa-underline"></i></button>
                <input type="color" onchange="changeTextColor(this.value, '${textElement.id}')" title="Text Color">
                <input type="number" min="1" max="100" value="16" onchange="changeFontSize(this.value, '${textElement.id}')" title="Font Size">
                <select onchange="changeFontFamily(this.value, '${textElement.id}')" title="Font Family">
                    <option value="Arial">Arial</option>
                    <option value="Helvetica">Helvetica</option>
                    <option value="Times New Roman">Times New Roman</option>
                    <option value="Courier New">Courier New</option>
                    <option value="Verdana">Verdana</option>
                    <option value="Georgia">Georgia</option>
                    <option value="Palatino">Palatino</option>
                    <option value="Garamond">Garamond</option>
                    <option value="Bookman">Bookman</option>
                    <option value="Comic Sans MS">Comic Sans MS</option>
                    <option value="Trebuchet MS">Trebuchet MS</option>
                    <option value="Arial Black">Arial Black</option>
                </select>
                <input type="range" min="0" max="100" value="100" onchange="changeTextOpacity(this.value, '${textElement.id}')" title="Opacity" class="opacity-slider">
            `;

            wrapper.appendChild(controls);
        }

        function addMediaControls(mediaElement) {
            const wrapper = document.getElementById('media-controls-wrapper');
            const controls = document.createElement('div');
            controls.className = 'media-controls';
            controls.setAttribute('data-media-id', mediaElement.id);
            controls.style.display = 'none';
            controls.innerHTML = `
                <button onclick="removeMedia('${mediaElement.id}')" title="Remove"><i class="fas fa-trash"></i></button>
                <button onclick="resetZoom('${mediaElement.id}')" title="Reset Zoom"><i class="fas fa-search-minus"></i></button>
                <input type="range" min="0" max="100" value="100" onchange="changeMediaOpacity(this.value, '${mediaElement.id}')" title="Opacity" class="opacity-slider">
            `;

            wrapper.appendChild(controls);
        }

        function addShapeControls(shapeElement, shapeType) {
            const wrapper = document.getElementById('shape-controls-wrapper');
            const controls = document.createElement('div');
            controls.className = 'shape-controls';
            controls.setAttribute('data-shape-id', shapeElement.id);
            controls.style.display = 'none';
            controls.innerHTML = `
                <input type="color" oninput="changeShapeColor(this.value, '${shapeElement.id}', this)" title="Fill Color">
                <input type="range" min="0" max="100" value="100" onchange="changeShapeOpacity(this.value, '${shapeElement.id}')" title="Opacity" class="opacity-slider">
                <button onclick="removeShape('${shapeElement.id}')" title="Remove"><i class="fas fa-trash"></i></button>
            `;

            wrapper.appendChild(controls);
        }

        // Text Control Functions
        function changeTextColor(color, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            textContent.style.color = color;
            updateCode();
            saveState();
        }

        function changeFontSize(size, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            textContent.style.fontSize = size + 'px';
            updateCode();
            saveState();
        }

        function changeFontFamily(family, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            textContent.style.fontFamily = family;
            updateCode();
            saveState();
        }

        function toggleBold(button, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            const isBold = textContent.style.fontWeight === 'bold';
            textContent.style.fontWeight = isBold ? 'normal' : 'bold';
            button.style.backgroundColor = isBold ? '' : '#e0e0e0';
            updateCode();
            saveState();
        }

        function toggleItalic(button, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            const isItalic = textContent.style.fontStyle === 'italic';
            textContent.style.fontStyle = isItalic ? 'normal' : 'italic';
            button.style.backgroundColor = isItalic ? '' : '#e0e0e0';
            updateCode();
            saveState();
        }

        function toggleUnderline(button, textId) {
            const textElement = document.getElementById(textId);
            const textContent = textElement.querySelector('div');
            const isUnderline = textContent.style.textDecoration === 'underline';
            textContent.style.textDecoration = isUnderline ? 'none' : 'underline';
            button.style.backgroundColor = isUnderline ? '' : '#e0e0e0';
            updateCode();
            saveState();
        }

        function changeTextOpacity(value, textId) {
            const textElement = document.getElementById(textId);
            textElement.style.opacity = value / 100;
            updateCode();
            saveState();
        }

        // Media Control Functions
        function removeMedia(mediaId) {
            const mediaElement = document.getElementById(mediaId);
            mediaElement.remove();
            const mediaControls = document.querySelector(`.media-controls[data-media-id="${mediaId}"]`);
            if (mediaControls) {
                mediaControls.style.display = 'none';
            }
            updateLayerPanel();
            updateCode();
            saveState();
        }

        function resetZoom(mediaId) {
            const mediaElement = document.getElementById(mediaId);
            const img = mediaElement.querySelector('img');
            img.style.transform = 'scale(1)';
            img.dataset.scale = 1;
            // Adjust the container size
            mediaElement.style.width = img.naturalWidth + 'px';
            mediaElement.style.height = img.naturalHeight + 'px';
            updateCode();
            saveState();
        }

        function zoomMedia(img, e) {
            e.preventDefault();

            const delta = e.deltaY;

            const zoomFactor = 0.05; // Smaller zoom factor for smoother zooming

            // Get current scale
            let scale = img.dataset.scale ? parseFloat(img.dataset.scale) : 1;
            // Update scale
            scale *= delta > 0 ? (1 - zoomFactor) : (1 + zoomFactor);
            // Limit scale
            scale = Math.min(Math.max(0.1, scale), 10);
            img.dataset.scale = scale;

            // Apply scale transform
            img.style.transform = `scale(${scale})`;

            // Adjust the container size based on the scaled image size
            const mediaElement = img.parentElement;
            mediaElement.style.width = img.naturalWidth * scale + 'px';
            mediaElement.style.height = img.naturalHeight * scale + 'px';

            updateCode();
            saveState();
        }

        function changeMediaOpacity(value, mediaId) {
            const mediaElement = document.getElementById(mediaId);
            mediaElement.style.opacity = value / 100;
            updateCode();
            saveState();
        }

        // Shape Control Functions
        function changeShapeColor(color, shapeId, inputElement) {
            const shapeElement = document.getElementById(shapeId);
            if (shapeElement.classList.contains('shape-triangle')) {
                shapeElement.style.borderBottomColor = color;
            } else if (shapeElement.classList.contains('shape-star') || shapeElement.classList.contains('shape-pentagon') || shapeElement.classList.contains('shape-hexagon') || shapeElement.classList.contains('shape-octagon')) {
                shapeElement.style.backgroundColor = color;
            } else {
                shapeElement.style.backgroundColor = color;
            }
            // Update the color picker swatch color
            inputElement.value = color;
            updateCode();
            saveState();
        }

        function changeShapeOpacity(value, shapeId) {
            const shapeElement = document.getElementById(shapeId);
            shapeElement.style.opacity = value / 100;
            updateCode();
            saveState();
        }

        function removeShape(shapeId) {
            const shapeElement = document.getElementById(shapeId);
            shapeElement.remove();
            const shapeControls = document.querySelector(`.shape-controls[data-shape-id="${shapeId}"]`);
            if (shapeControls) {
                shapeControls.style.display = 'none';
            }
            updateLayerPanel();
            updateCode();
            saveState();
        }

        function zoomShape(shape, e) {
            e.preventDefault();

            const delta = e.deltaY;

            const zoomFactor = 0.05; // Adjust the zoom factor as desired

            // Get current scale
            let scale = shape.dataset.scale ? parseFloat(shape.dataset.scale) : 1;
            // Update scale
            scale *= delta > 0 ? (1 - zoomFactor) : (1 + zoomFactor);
            // Limit scale
            scale = Math.min(Math.max(0.1, scale), 10);
            shape.dataset.scale = scale;

            // Apply scale transform
            shape.style.transform = `scale(${scale})`;

            // Adjust controls position
            const controls = document.querySelector(`.shape-controls[data-shape-id="${shape.id}"]`);
            if (controls && controls.style.display === 'flex') {
                controls.style.top = `${shape.offsetTop - controls.offsetHeight - 10}px`;
                controls.style.left = `${shape.offsetLeft + (shape.offsetWidth * scale) / 2 - (controls.offsetWidth / 2)}px`;
            }

            updateCode();
            saveState();
        }

        function copyElements() {
            const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
            if (selectedElement) {
                copiedElement = selectedElement.outerHTML;
            }
        }

        function pasteElements() {
            const canvas = document.getElementById('canvas');
            if (copiedElement) {
                const tempDiv = document.createElement('div');
                tempDiv.innerHTML = copiedElement;
                const element = tempDiv.firstChild;
                // Adjust element ID to make it unique
                element.id = element.id + '-' + Date.now();

                // Keep the element at the same position
                element.style.top = parseInt(element.style.top) + 10 + 'px';
                element.style.left = parseInt(element.style.left) + 10 + 'px';

                canvas.appendChild(element);
                makeDraggable(element);
                makeSelectable(element);
                if (element.classList.contains('canvas-text')) {
                    addTextControls(element);
                    addResizeHandles(element);
                } else if (element.classList.contains('canvas-media')) {
                    addMediaControls(element);
                } else if (element.classList.contains('canvas-shape')) {
                    let shapeType;
                    if (element.classList.contains('shape-rectangle')) {
                        shapeType = 'rectangle';
                    } else if (element.classList.contains('shape-ellipse')) {
                        shapeType = 'ellipse';
                    } else if (element.classList.contains('shape-star')) {
                        shapeType = 'star';
                    } else if (element.classList.contains('shape-triangle')) {
                        shapeType = 'triangle';
                    } else if (element.classList.contains('shape-pentagon')) {
                        shapeType = 'pentagon';
                    } else if (element.classList.contains('shape-hexagon')) {
                        shapeType = 'hexagon';
                    } else if (element.classList.contains('shape-octagon')) {
                        shapeType = 'octagon';
                    }
                    addShapeControls(element, shapeType);
                    element.onwheel = (e) => {
                        e.preventDefault();
                        zoomShape(element, e);
                    };
                }
                updateLayerPanel();
                updateCode();
                saveState();
            }
        }

        function deleteElement() {
            const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
            if (selectedElement) {
                selectedElement.remove();
                updateLayerPanel();
                updateCode();
                saveState();
            }
        }

        function toggleCode() {
            updateCode();
            codeArea.style.display = codeArea.style.display === 'block' ? 'none' : 'block';
        }

        function makeElementDraggable(elmnt) {
            var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
            elmnt.onmousedown = dragMouseDown;

            function dragMouseDown(e) {
                e = e || window.event;
                e.preventDefault();
                // get the mouse cursor position at startup:
                pos3 = e.clientX;
                pos4 = e.clientY;
                document.onmouseup = closeDragElement;
                // call a function whenever the cursor moves:
                document.onmousemove = elementDrag;
            }

            function elementDrag(e) {
                e = e || window.event;
                e.preventDefault();
                // calculate the new cursor position:
                pos1 = pos3 - e.clientX;
                pos2 = pos4 - e.clientY;
                pos3 = e.clientX;
                pos4 = e.clientY;
                // set the element's new position:
                elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
                elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
            }

            function closeDragElement() {
                // stop moving when mouse button is released:
                document.onmouseup = null;
                document.onmousemove = null;
            }
        }

        makeElementDraggable(codeArea);
        makeElementDraggable(document.getElementById('layerPanel'));
        makeElementDraggable(document.getElementById('layerPanelHeader'));

        function updateCode() {
            const canvas = document.getElementById('canvas');
            const canvasStyle = getComputedStyle(canvas);
            const backgroundColor = canvasStyle.backgroundColor;

            const elements = canvas.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
            const elementsArray = Array.prototype.map.call(elements, function(element) {
                // Clone the element to avoid modifying the original
                let clone = element.cloneNode(true);

                // Adjust image src attribute
                if (clone.classList.contains('canvas-media')) {
                    let img = clone.querySelector('img');
                    if (img) {
                        let src = img.src;
                        let fileExtension = '';
                        if (src.startsWith('data:image/')) {
                            let match = src.match(/^data:image\/(png|jpeg|jpg);/);
                            let ext = match ? match[1] : 'png';
                            if (ext === 'jpeg') ext = 'jpg'; // use jpg instead of jpeg
                            // Generate 10-digit random number
                            let randomNumber = Math.floor(1000000000 + Math.random() * 9000000000);
                            let fileName = randomNumber + '.' + ext;
                            img.src = fileName;
                        }
                    }
                }

                // Remove selected class and inline styles related to selection
                clone.classList.remove('selected');
                clone.style.outline = '';

                // Remove resize handles
                if (clone.classList.contains('canvas-text') || clone.classList.contains('canvas-media') || clone.classList.contains('canvas-shape')) {
                    const handles = clone.querySelectorAll('.resize-handle');
                    handles.forEach(handle => handle.remove());
                }

                // Include transform styles
                const computedStyle = window.getComputedStyle(element);
                if (computedStyle.transform !== 'none') {
                    clone.style.transform = computedStyle.transform;
                }

                // Return the outerHTML of the cloned element
                return clone.outerHTML;
            });

            // Include styles in the code
            const styles = document.querySelector('style').outerHTML;

            // Build the complete HTML code
            let html = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Canvas Export</title>${styles}
</head>
<body>
<div id="canvas" style="background-color:${backgroundColor}; position: relative; width: 800px; height: 600px;">${elementsArray.join('\n')}
</div>
</body>
</html>`;

            codeElement.textContent = html;
        }

        // Keyboard shortcuts
        document.addEventListener('keydown', function(e) {
            const activeElement = document.activeElement;
            if (activeElement && (
                activeElement.tagName === 'INPUT' ||
                activeElement.tagName === 'TEXTAREA' ||
                activeElement.isContentEditable
            )) {
                // Don't interfere with typing in input fields or editable divs
                return;
            }

            if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
                e.preventDefault();
                copyElements();
            } else if (e.ctrlKey && (e.key === 'v' || e.key === 'V')) {
                e.preventDefault();
                pasteElements();
            } else if (e.key === 'Delete' || e.key === 'Backspace') {
                e.preventDefault();
                deleteElement();
            } else if (e.ctrlKey && (e.key === 'z' || e.key === 'Z')) {
                e.preventDefault();
                undo();
            } else if (e.ctrlKey && (e.key === 'y' || e.key === 'Y')) {
                e.preventDefault();
                redo();
            }
        });

        // Undo/Redo functionality
        function saveState() {
            const canvas = document.getElementById('canvas');
            const state = canvas.innerHTML;
            undoStack.push(state);
            redoStack = []; // Clear redo stack
        }

        function undo() {
            if (undoStack.length > 1) {
                redoStack.push(undoStack.pop());
                const lastState = undoStack[undoStack.length - 1];
                const canvas = document.getElementById('canvas');
                canvas.innerHTML = lastState;
                reinitializeCanvasElements();
                updateLayerPanel();
                updateCode();
            }
        }

        function redo() {
            if (redoStack.length > 0) {
                const state = redoStack.pop();
                undoStack.push(state);
                const canvas = document.getElementById('canvas');
                canvas.innerHTML = state;
                reinitializeCanvasElements();
                updateLayerPanel();
                updateCode();
            }
        }

        function reinitializeCanvasElements() {
            const elements = document.querySelectorAll('.canvas-text, .canvas-media, .canvas-shape');
            elements.forEach(element => {
                makeDraggable(element);
                makeSelectable(element);
                if (element.classList.contains('canvas-text')) {
                    addTextControls(element);
                    addResizeHandles(element);
                } else if (element.classList.contains('canvas-media')) {
                    addMediaControls(element);
                    addResizeHandles(element);
                } else if (element.classList.contains('canvas-shape')) {
                    let shapeType;
                    if (element.classList.contains('shape-rectangle')) {
                        shapeType = 'rectangle';
                    } else if (element.classList.contains('shape-ellipse')) {
                        shapeType = 'ellipse';
                    } else if (element.classList.contains('shape-star')) {
                        shapeType = 'star';
                    } else if (element.classList.contains('shape-triangle')) {
                        shapeType = 'triangle';
                    } else if (element.classList.contains('shape-pentagon')) {
                        shapeType = 'pentagon';
                    } else if (element.classList.contains('shape-hexagon')) {
                        shapeType = 'hexagon';
                    } else if (element.classList.contains('shape-octagon')) {
                        shapeType = 'octagon';
                    }
                    addShapeControls(element, shapeType);
                    addResizeHandles(element);
                    element.onwheel = (e) => {
                        e.preventDefault();
                        zoomShape(element, e);
                    };
                }
            });
        }

        // Layer Panel
        function updateLayerPanel() {
            const layerList = document.getElementById('layerList');
            layerList.innerHTML = '';
            const canvas = document.getElementById('canvas');
            const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
            elements.reverse().forEach((element, index) => {
                const listItem = document.createElement('li');
                listItem.className = 'layer-list-item';
                listItem.setAttribute('data-element-id', element.id);

                const thumbnailContainer = document.createElement('div');
                thumbnailContainer.className = 'layer-thumbnail';

                const thumbnail = document.createElement('canvas');
                thumbnail.width = 30;
                thumbnail.height = 30;
                const ctx = thumbnail.getContext('2d');

                if (element.classList.contains('canvas-text')) {
                    ctx.font = '14px Arial';
                    ctx.fillStyle = window.getComputedStyle(element).color;
                    ctx.fillText(element.textContent.trim(), 0, 20);
                } else if (element.classList.contains('canvas-media')) {
                    const img = element.querySelector('img');
                    ctx.drawImage(img, 0, 0, 30, 30);
                } else if (element.classList.contains('canvas-shape')) {
                    ctx.fillStyle = window.getComputedStyle(element).backgroundColor;
                    ctx.fillRect(0, 0, 30, 30);
                }

                thumbnailContainer.appendChild(thumbnail);

                const name = document.createElement('span');
                name.className = 'layer-name';
                name.textContent = element.id;
                const visibility = document.createElement('span');
                visibility.className = 'layer-visible';
                visibility.innerHTML = '<i class="fas fa-eye"></i>';
                visibility.addEventListener('click', function(e) {
                    e.stopPropagation();
                    toggleVisibility(element.id, visibility);
                });

                listItem.appendChild(thumbnailContainer);
                listItem.appendChild(name);
                listItem.appendChild(visibility);
                layerList.appendChild(listItem);
            });
            makeLayerListDraggable();
        }

        function makeLayerListDraggable() {
            const layerList = document.getElementById('layerList');
            const listItems = layerList.querySelectorAll('.layer-list-item');
            listItems.forEach(item => {
                item.draggable = true;
                item.addEventListener('dragstart', dragStart);
                item.addEventListener('dragover', dragOver);
                item.addEventListener('drop', drop);
            });
        }

        let dragSrcEl = null;

        function dragStart(e) {
            dragSrcEl = this;
            e.dataTransfer.effectAllowed = 'move';
        }

        function dragOver(e) {
            e.preventDefault();
            e.dataTransfer.dropEffect = 'move';
            return false;
        }

        function drop(e) {
            e.stopPropagation();
            if (dragSrcEl !== this) {
                const layerList = document.getElementById('layerList');
                const nodes = Array.from(layerList.children);
                const srcIndex = nodes.indexOf(dragSrcEl);
                const destIndex = nodes.indexOf(this);

                if (srcIndex > destIndex) {
                    layerList.insertBefore(dragSrcEl, this);
                } else {
                    layerList.insertBefore(dragSrcEl, this.nextSibling);
                }

                updateCanvasLayerOrder();
            }
            return false;
        }

        function updateCanvasLayerOrder() {
            const layerList = document.getElementById('layerList');
            const layerItems = Array.from(layerList.children);
            const canvas = document.getElementById('canvas');
            const elements = Array.from(canvas.children).filter(el => el.classList.contains('canvas-text') || el.classList.contains('canvas-media') || el.classList.contains('canvas-shape'));
            elements.forEach(el => {
                canvas.removeChild(el);
            });
            layerItems.reverse().forEach(item => {
                const elementId = item.getAttribute('data-element-id');
                const element = document.getElementById(elementId);
                canvas.appendChild(element);
            });
            updateCode();
            saveState();
        }

        function toggleVisibility(elementId, visibilityIcon) {
            const element = document.getElementById(elementId);
            if (element.style.display === 'none') {
                element.style.display = '';
                visibilityIcon.innerHTML = '<i class="fas fa-eye"></i>';
            } else {
                element.style.display = 'none';
                visibilityIcon.innerHTML = '<i class="fas fa-eye-slash"></i>';
            }
            updateCode();
            saveState();
        }

        // Gradient Tool Functions
        function toggleGradientTool() {
            gradientTool.style.display = gradientTool.style.display === 'none' ? 'flex' : 'none';
        }

        function applyGradient() {
            const selectedElement = document.querySelector('.canvas-shape.selected');
            if (selectedElement) {
                const gradientType = document.getElementById('gradientType').value;
                const color1 = document.getElementById('gradientColor1').value;
                const color2 = document.getElementById('gradientColor2').value;

                if (gradientType === 'linear') {
                    selectedElement.style.background = `linear-gradient(${color1}, ${color2})`;
                } else {
                    selectedElement.style.background = `radial-gradient(${color1}, ${color2})`;
                }
                updateCode();
                saveState();
            } else {
                alert('Please select a shape to apply gradient');
            }
        }

        // Initial save state
        saveState();
    </script>
</body>
</html>