Write the full complete code dont skip anything, write the full code with the new edits you did just write the full complete code, DOn't change aything but the things I say so I like the design but the text is not tyable I cant type on it fix it, also why is text bar with bold and color not moving fix that, make the stroke tool have a normal one, also the stroke tool is kind of gltichy its not autocmailyl doing a live preview of the sttroke so make it automatically live preview if a thing is selected also the top bar toggle grid, toggle code, and opactiy make it match our current ui, also the code editor thingy when press toggle code make it match our current design, also make it so indlivual toolbox dont overlap with graident tools toolbox etc, fix that, also for stroke I want it to go around the circle but stroke effect not a box effect, make it so layers I can double tap to make it so the layer can move to other and overlap with other layer basically like adobe illustorator with the circle layer with text etc.<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Enhanced Notion-like Canvas</title>
    <!-- Include Material Icons for UI Icons -->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!-- Include Google Fonts -->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&family=Source+Sans+Pro:wght@400;700&display=swap" rel="stylesheet">
    <style>
        /* General Styles */
        body, html {
            margin: 0;
            padding: 0;
            height: 100vh;
            overflow: hidden;
            font-family: 'Source Sans Pro', 'Roboto', 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: 24px;
        }
        .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;
        }
        .canvas-area {
            flex: 1;
            background-color: #f7f6f3;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
            position: relative;
            overflow: hidden;
        }
        .canvas-controls {
            margin-bottom: 10px;
            display: flex;
            align-items: center;
            position: relative;
            z-index: 1;
            gap: 10px;
        }
        .canvas-controls button,
        .canvas-controls input[type="color"],
        .canvas-controls input[type="range"] {
            background-color: #e0e0e0;
            color: #37352f;
            border: none;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s ease;
            display: flex;
            align-items: center;
        }
        .canvas-controls button:hover,
        .canvas-controls input[type="color"]:hover {
            background-color: #d0d0d0;
        }
        .canvas-controls input[type="range"] {
            width: 100px;
            padding: 0;
            margin: 0;
            cursor: pointer;
            background-color: transparent;
        }
        .canvas-container {
            position: relative;
            flex: 1;
            width: 100%;
            max-width: 1200px;
            background-color: #fff;
            border: 1px solid #e0e0e0;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            cursor: default;
            overflow: hidden;
        }
        .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;
            min-width: 50px;
            min-height: 20px;
        }
        .canvas-text {
            background-color: rgba(255, 255, 255, 0.8);
            border: 1px solid #ccc;
            border-radius: 4px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            overflow: hidden;
        }
        .canvas-text div {
            padding: 5px;
            outline: none;
            width: 100%;
            height: 100%;
            font-family: 'Roboto', sans-serif;
            font-size: 16px;
            color: #333;
            text-align: left;
        }
        .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;
            background-color: #3498db;
            overflow: hidden;
        }
        .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;
        }
        .text-controls i.material-icons,
        .media-controls i.material-icons,
        .shape-controls i.material-icons {
            font-size: 18px;
        }
        .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,
        .gradient-stroke-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;
        }
        /* Layers Panel Styles */
        .layer-panel {
            position: absolute;
            top: 0;
            right: 0;
            width: 250px;
            height: 100%;
            background-color: #fbfbfa;
            color: #37352f;
            border-left: 1px solid #e0e0e0;
            display: flex;
            flex-direction: column;
            z-index: 1;
            overflow: hidden;
        }
        .layer-panel-header {
            padding: 10px;
            font-size: 16px;
            font-weight: bold;
            border-bottom: 1px solid #e0e0e0;
            background-color: #f7f6f3;
            cursor: move;
        }
        .layer-list {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
        }
        .layer-list-item {
            display: flex;
            align-items: center;
            padding: 5px;
            margin-bottom: 5px;
            border: 1px solid transparent;
            cursor: pointer;
            background-color: #fbfbfa;
        }
        .layer-list-item:hover {
            background-color: #f1f1ef;
            border-color: #e0e0e0;
        }
        .layer-thumbnail canvas {
            width: 40px;
            height: 40px;
            background-color: #fff;
            border: 1px solid #ccc;
        }
        .layer-name {
            flex: 1;
            margin-left: 10px;
            font-size: 14px;
        }
        .layer-controls {
            display: flex;
            align-items: center;
            gap: 5px;
        }
        .layer-controls .material-icons {
            cursor: pointer;
            color: #999;
            font-size: 20px;
        }
        .layer-controls .material-icons:hover {
            color: #37352f;
        }
        /* Code Area */
        .code-area {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            height: 200px;
            background-color: #1e1e1e;
            color: #dcdcdc;
            display: none;
            overflow: auto;
            padding: 10px;
            font-family: 'Courier New', Courier, monospace;
            font-size: 14px;
            z-index: 1000;
            resize: vertical;
        }
        .code-area pre {
            margin: 0;
        }
        /* Toggle Code Button */
        .toggle-code {
            position: absolute;
            bottom: 10px;
            right: 10px;
            background-color: #e0e0e0;
            border: none;
            padding: 6px 10px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            color: #37352f;
            transition: background-color 0.3s ease;
        }
        .toggle-code:hover {
            background-color: #d0d0d0;
        }
        /* Font Controls Styling */
        .text-controls input[type="number"],
        .text-controls select {
            border: 1px solid #ccc;
            background-color: #f9f9f9;
        }
        .text-controls button {
            background-color: #f9f9f9;
            border: 1px solid #ccc;
        }
        .text-controls button.active {
            background-color: #e0e0e0;
        }
        .text-controls {
            font-family: 'Source Sans Pro', sans-serif;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="toolbar">
            <button class="tool-button" onclick="addText()" title="Add Text">
                <i class="material-icons">text_fields</i>
                <span class="tooltip">Add Text</span>
            </button>
            <button class="tool-button" onclick="addMedia()" title="Add Media">
                <i class="material-icons">image</i>
                <span class="tooltip">Add Media</span>
            </button>
            <button class="tool-button" onclick="copyElements()" title="Copy">
                <i class="material-icons">content_copy</i>
                <span class="tooltip">Copy (Ctrl+C)</span>
            </button>
            <button class="tool-button" onclick="pasteElements()" title="Paste">
                <i class="material-icons">content_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="material-icons">category</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="material-icons">crop_square</i>
                    </button>
                    <button class="tool-button" onclick="selectShape('ellipse')" title="Ellipse">
                        <i class="material-icons">circle</i>
                    </button>
                    <button class="tool-button" onclick="selectShape('star')" title="Star">
                        <i class="material-icons">star</i>
                    </button>
                    <button class="tool-button" onclick="selectShape('triangle')" title="Triangle">
                        <i class="material-icons">change_history</i>
                    </button>
                    <!-- New Shapes -->
                    <button class="tool-button" onclick="selectShape('pentagon')" title="Pentagon">
                        <i class="material-icons">pentagon</i>
                    </button>
                    <button class="tool-button" onclick="selectShape('hexagon')" title="Hexagon">
                        <i class="material-icons">hexagon</i>
                    </button>
                    <button class="tool-button" onclick="selectShape('octagon')" title="Octagon">
                        <i class="material-icons">stop</i>
                    </button>
                </div>
            </div>
            <button class="tool-button" onclick="toggleGradientTool()" title="Gradient Fill">
                <i class="material-icons">gradient</i>
                <span class="tooltip">Gradient Fill</span>
            </button>
            <button class="tool-button" onclick="toggleGradientStrokeTool()" title="Gradient Stroke">
                <i class="material-icons">border_color</i>
                <span class="tooltip">Gradient Stroke</span>
            </button>
            <button class="tool-button" onclick="deleteElement()" title="Delete">
                <i class="material-icons">delete</i>
                <span class="tooltip">Delete (Delete)</span>
            </button>
            <button class="tool-button" onclick="undo()" title="Undo">
                <i class="material-icons">undo</i>
                <span class="tooltip">Undo (Ctrl+Z)</span>
            </button>
            <button class="tool-button" onclick="redo()" title="Redo">
                <i class="material-icons">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">
                <!-- Opacity Control -->
                <input type="range" min="0" max="100" value="100" id="globalOpacity" oninput="changeGlobalOpacity(this.value)" title="Opacity">
                <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 Type:</span>
                    <select id="gradientType" onchange="updateGradientPreview(); updateSelectedShapeGradient();">
                        <option value="linear">Linear</option>
                        <option value="radial">Radial</option>
                        <option value="conic">Conic</option>
                    </select>
                </div>
                <div class="gradient-option">
                    <span>Angle:</span>
                    <input type="number" id="gradientAngle" value="90" onchange="updateGradientPreview(); updateSelectedShapeGradient();">°
                </div>
                <div class="gradient-option">
                    <span>Colors:</span>
                    <div id="gradientColors"></div>
                    <button onclick="addGradientColor()">Add Color</button>
                </div>
                <div class="gradient-option">
                    <span>Preview:</span>
                    <div class="gradient-preview" id="gradientPreview"></div>
                </div>
            </div>
            <!-- Gradient Stroke Tool -->
            <div class="gradient-stroke-tool" id="gradientStrokeTool">
                <div class="gradient-option">
                    <span>Stroke Width:</span>
                    <input type="number" id="strokeWidth" value="2" onchange="updateGradientStrokePreview(); updateSelectedStroke();">px
                </div>
                <div class="gradient-option">
                    <span>Gradient Type:</span>
                    <select id="gradientStrokeType" onchange="updateGradientStrokePreview(); updateSelectedStroke();">
                        <option value="linear">Linear</option>
                        <option value="radial">Radial</option>
                        <option value="conic">Conic</option>
                    </select>
                </div>
                <div class="gradient-option">
                    <span>Angle:</span>
                    <input type="number" id="gradientStrokeAngle" value="90" onchange="updateGradientStrokePreview(); updateSelectedStroke();">°
                </div>
                <div class="gradient-option">
                    <span>Colors:</span>
                    <div id="gradientStrokeColors"></div>
                    <button onclick="addGradientStrokeColor()">Add Color</button>
                </div>
                <div class="gradient-option">
                    <span>Preview:</span>
                    <div class="gradient-preview" id="gradientStrokePreview"></div>
                </div>
            </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 gradientStrokeTool = document.getElementById('gradientStrokeTool');
        let undoStack = [];
        let redoStack = [];
        let gradientColors = ['#ff0000', '#0000ff'];
        let gradientStrokeColors = ['#ff0000', '#0000ff'];
        let isGradientToolActive = false;
        let isGradientStrokeToolActive = false;

        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';
            textContent.style.fontSize = '16px';
            textContent.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);
            });
            textContent.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 (element.dataset.locked === 'true') {
                    return;
                }
                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) {
                if (element.dataset.locked === 'true') {
                    return;
                }
                e.stopPropagation(); // prevent event bubbling
                clearSelection(); // Deselect others
                element.classList.add('selected'); // apply selected class
                showElementControls(element);
                // Update the global opacity slider
                const globalOpacity = document.getElementById('globalOpacity');
                globalOpacity.value = element.style.opacity * 100;
            });
        }

        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';
            isGradientToolActive = false;
            gradientStrokeTool.style.display = 'none';
            isGradientStrokeToolActive = false;
        }

        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="material-icons">format_bold</i></button>
                <button onclick="toggleItalic(this, '${textElement.id}')" title="Italic"><i class="material-icons">format_italic</i></button>
                <button onclick="toggleUnderline(this, '${textElement.id}')" title="Underline"><i class="material-icons">format_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="Roboto">Roboto</option>
                    <option value="'Source Sans Pro'">Source Sans Pro</option>
                    <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>
            `;

            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="material-icons">delete</i></button>
                <button onclick="resetZoom('${mediaElement.id}')" title="Reset Zoom"><i class="material-icons">zoom_out_map</i></button>
            `;

            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">
                <button onclick="removeShape('${shapeElement.id}')" title="Remove"><i class="material-icons">delete</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.classList.toggle('active', !isBold);
            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.classList.toggle('active', !isItalic);
            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.classList.toggle('active', !isUnderline);
            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();
        }

        // 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 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: ${canvas.offsetWidth}px; height: ${canvas.offsetHeight}px;">${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 layerControls = document.createElement('div');
                layerControls.className = 'layer-controls';

                const visibility = document.createElement('span');
                visibility.className = 'layer-visible';
                visibility.innerHTML = `<i class="material-icons">${element.style.display === 'none' ? 'visibility_off' : 'visibility'}</i>`;
                visibility.addEventListener('click', function(e) {
                    e.stopPropagation();
                    toggleVisibility(element.id, visibility);
                });

                const lock = document.createElement('span');
                lock.className = 'layer-lock';
                lock.innerHTML = `<i class="material-icons">${element.dataset.locked === 'true' ? 'lock' : 'lock_open'}</i>`;
                lock.addEventListener('click', function(e) {
                    e.stopPropagation();
                    toggleLock(element.id, lock);
                });

                layerControls.appendChild(visibility);
                layerControls.appendChild(lock);

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

                const thumbnail = document.createElement('canvas');
                thumbnail.width = 40;
                thumbnail.height = 40;
                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, 40, 40);
                } else if (element.classList.contains('canvas-shape')) {
                    // Handle gradient backgrounds
                    const bg = window.getComputedStyle(element).backgroundImage;
                    if (bg && bg !== 'none') {
                        ctx.fillStyle = bg;
                        ctx.fillRect(0, 0, 40, 40);
                    } else {
                        ctx.fillStyle = window.getComputedStyle(element).backgroundColor;
                        ctx.fillRect(0, 0, 40, 40);
                    }
                }

                thumbnailContainer.appendChild(thumbnail);

                const name = document.createElement('div');
                name.className = 'layer-name';
                name.textContent = element.id;

                listItem.appendChild(layerControls);
                listItem.appendChild(thumbnailContainer);
                listItem.appendChild(name);

                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="material-icons">visibility</i>';
            } else {
                element.style.display = 'none';
                visibilityIcon.innerHTML = '<i class="material-icons">visibility_off</i>';
            }
            updateCode();
            saveState();
        }

        function toggleLock(elementId, lockIcon) {
            const element = document.getElementById(elementId);
            if (element.dataset.locked === 'true') {
                element.dataset.locked = 'false';
                lockIcon.innerHTML = '<i class="material-icons">lock_open</i>';
                element.style.pointerEvents = 'auto';
            } else {
                element.dataset.locked = 'true';
                lockIcon.innerHTML = '<i class="material-icons">lock</i>';
                element.style.pointerEvents = 'none';
            }
            updateCode();
            saveState();
        }

        // Gradient Fill Tool Functions
        function toggleGradientTool() {
            if (gradientTool.style.display === 'none') {
                gradientTool.style.display = 'flex';
                updateGradientColors();
                updateGradientPreview();
                isGradientToolActive = true;
                updateSelectedShapeGradient();
            } else {
                gradientTool.style.display = 'none';
                isGradientToolActive = false;
            }
        }

        function addGradientColor() {
            gradientColors.push('#ffffff');
            updateGradientColors();
            updateGradientPreview();
            updateSelectedShapeGradient();
        }

        function updateGradientColors() {
            const gradientColorsDiv = document.getElementById('gradientColors');
            gradientColorsDiv.innerHTML = '';
            gradientColors.forEach((color, index) => {
                const colorInput = document.createElement('input');
                colorInput.type = 'color';
                colorInput.value = color;
                colorInput.oninput = function() {
                    gradientColors[index] = colorInput.value;
                    updateGradientPreview();
                    updateSelectedShapeGradient();
                };
                gradientColorsDiv.appendChild(colorInput);
            });
        }

        function updateGradientPreview() {
            const gradientType = document.getElementById('gradientType').value;
            const angle = document.getElementById('gradientAngle').value;
            const gradientPreview = document.getElementById('gradientPreview');
            let gradientString = '';
            if (gradientType === 'linear') {
                gradientString = `linear-gradient(${angle}deg, ${gradientColors.join(', ')})`;
            } else if (gradientType === 'radial') {
                gradientString = `radial-gradient(${gradientColors.join(', ')})`;
            } else if (gradientType === 'conic') {
                gradientString = `conic-gradient(${gradientColors.join(', ')})`;
            }
            gradientPreview.style.background = gradientString;
        }

        function updateSelectedShapeGradient() {
            const selectedElement = document.querySelector('.canvas-shape.selected, .canvas-text.selected');
            if (selectedElement) {
                const gradientType = document.getElementById('gradientType').value;
                const angle = document.getElementById('gradientAngle').value;
                let gradientString = '';
                if (gradientType === 'linear') {
                    gradientString = `linear-gradient(${angle}deg, ${gradientColors.join(', ')})`;
                } else if (gradientType === 'radial') {
                    gradientString = `radial-gradient(${gradientColors.join(', ')})`;
                } else if (gradientType === 'conic') {
                    gradientString = `conic-gradient(${gradientColors.join(', ')})`;
                }
                // Apply gradient
                if (selectedElement.classList.contains('canvas-shape')) {
                    selectedElement.style.background = gradientString;
                } else if (selectedElement.classList.contains('canvas-text')) {
                    const textContent = selectedElement.querySelector('div');
                    textContent.style.background = gradientString;
                    textContent.style.webkitBackgroundClip = 'text';
                    textContent.style.webkitTextFillColor = 'transparent';
                }
                updateCode();
                saveState();
            }
        }

        // Gradient Stroke Tool Functions
        function toggleGradientStrokeTool() {
            if (gradientStrokeTool.style.display === 'none') {
                gradientStrokeTool.style.display = 'flex';
                updateGradientStrokeColors();
                updateGradientStrokePreview();
                isGradientStrokeToolActive = true;
                updateSelectedStroke();
            } else {
                gradientStrokeTool.style.display = 'none';
                isGradientStrokeToolActive = false;
            }
        }

        function addGradientStrokeColor() {
            gradientStrokeColors.push('#ffffff');
            updateGradientStrokeColors();
            updateGradientStrokePreview();
            updateSelectedStroke();
        }

        function updateGradientStrokeColors() {
            const gradientColorsDiv = document.getElementById('gradientStrokeColors');
            gradientColorsDiv.innerHTML = '';
            gradientStrokeColors.forEach((color, index) => {
                const colorInput = document.createElement('input');
                colorInput.type = 'color';
                colorInput.value = color;
                colorInput.oninput = function() {
                    gradientStrokeColors[index] = colorInput.value;
                    updateGradientStrokePreview();
                    updateSelectedStroke();
                };
                gradientColorsDiv.appendChild(colorInput);
            });
        }

        function updateGradientStrokePreview() {
            const gradientType = document.getElementById('gradientStrokeType').value;
            const angle = document.getElementById('gradientStrokeAngle').value;
            const gradientPreview = document.getElementById('gradientStrokePreview');
            let gradientString = '';
            if (gradientType === 'linear') {
                gradientString = `linear-gradient(${angle}deg, ${gradientStrokeColors.join(', ')})`;
            } else if (gradientType === 'radial') {
                gradientString = `radial-gradient(${gradientStrokeColors.join(', ')})`;
            } else if (gradientType === 'conic') {
                gradientString = `conic-gradient(${gradientStrokeColors.join(', ')})`;
            }
            gradientPreview.style.background = gradientString;
        }

        function updateSelectedStroke() {
            const selectedElement = document.querySelector('.canvas-shape.selected, .canvas-text.selected');
            if (selectedElement) {
                const gradientType = document.getElementById('gradientStrokeType').value;
                const angle = document.getElementById('gradientStrokeAngle').value;
                const strokeWidth = document.getElementById('strokeWidth').value;
                let gradientString = '';
                if (gradientType === 'linear') {
                    gradientString = `linear-gradient(${angle}deg, ${gradientStrokeColors.join(', ')})`;
                } else if (gradientType === 'radial') {
                    gradientString = `radial-gradient(${gradientStrokeColors.join(', ')})`;
                } else if (gradientType === 'conic') {
                    gradientString = `conic-gradient(${gradientStrokeColors.join(', ')})`;
                }
                // Apply gradient stroke
                selectedElement.style.border = `${strokeWidth}px solid`;
                selectedElement.style.borderImage = `${gradientString} 1`;
                updateCode();
                saveState();
            }
        }

        // Global Opacity Control
        function changeGlobalOpacity(value) {
            const selectedElement = document.querySelector('.canvas-text.selected, .canvas-media.selected, .canvas-shape.selected');
            if (selectedElement) {
                selectedElement.style.opacity = value / 100;
                updateCode();
                saveState();
            }
        }

        // Monitor selected element changes to update gradient tools
        document.addEventListener('click', function(e) {
            if (isGradientToolActive) {
                const selectedElement = document.querySelector('.canvas-shape.selected, .canvas-text.selected');
                if (selectedElement) {
                    updateSelectedShapeGradient();
                }
            }
            if (isGradientStrokeToolActive) {
                const selectedElement = document.querySelector('.canvas-shape.selected, .canvas-text.selected');
                if (selectedElement) {
                    updateSelectedStroke();
                }
            }
        });

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