Act as a expert programmer in HTML, CSS and JavaScript.

When I edit placement first time it works but when I press preview first design and then go back to edit the placement it stays where it was. I can't change placement after once preview.

<!DOCTYPE html>
<html>
<head>
    <title>Bulk T-shirt Mockup Generator</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <style>
        /* Theme Variables */
        :root {
            /* Light theme (default) */
            --primary-color: #3b82f6;
            --primary-hover: #2563eb;
            --bg-color: #0f172a;
            --border-color: #344158;
            --text-color: #e2e8f0;
            --secondary-text: #94a3b8;
            --card-bg: #1e293b;


            /* --bg-color: #f8fafc;
            --border-color: #e2e8f0;
            --text-color: #1e293b;
            --secondary-text: #64748b;
            --card-bg: white; */
        }

        /* Dark theme */
        [data-theme="light"] {
            /* --bg-color: #0f172a;
            --border-color: #344158;
            --text-color: #e2e8f0;
            --secondary-text: #94a3b8;
            --card-bg: #1e293b; */


            --bg-color: #f8fafc;
            --border-color: #e2e8f0;
            --text-color: #1e293b;
            --secondary-text: #64748b;
            --card-bg: white;            
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
            margin: 0;
            padding: 0;
            overflow: hidden;
            background-color: var(--bg-color);
            color: var(--text-color);
            transition: background-color 0.3s, color 0.3s;
        }

        /* Header Styles */
        .header {
            display: flex;
            align-items: center;
            padding: 1rem 2rem;
            background-color: var(--card-bg);
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .nav-links {
            display: flex;
            gap: 1rem;
            margin-left: auto;
            margin-right: 1rem;
        }

        .nav-links a {
            text-decoration: none;
            color: var(--secondary-text);
            font-weight: 500;
            transition: color 0.2s ease;
        }

        .nav-links a:hover {
            color: var(--primary-color);
        }

        .nav-links a.active {
            color: var(--primary-color);
        }

        .logo {
            display: flex;
            align-items: center;
            gap: 0.5rem;
            font-size: 1.25rem;
            font-weight: 600;
            color: var(--text-color);
        }

        .theme-toggle {
            background: none;
            border: 1px solid var(--primary-color);
            width: 5rem;
            margin: 0;
            color: var(--text-color);
            cursor: pointer;
            padding: 0.5rem;
            border-radius: 0.5rem;
            transition: background-color 0.2s;
        }

        .theme-toggle:hover {
            background-color: var(--card-bg);
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
            display: flex;
            gap: 24px;
            height: calc(100vh - 64px); /* Adjusted for header */
        }

        .canvas-section {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 104px); /* Adjusted for header */
            background: var(--card-bg);
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .canvas-container {
            flex: 1;
            width: 100%;
            display: flex;
            align-items: center;
            justify-content: center;
            background: var(--card-bg);
            border-radius: 12px;
            position: relative;
            overflow: hidden;
            padding: 20px;
        }

        .canvas-wrapper {
            position: relative;
            display: inline-block;
        }

        #mockupCanvas {
            display: block;
            max-width: 100%;
            max-height: calc(100vh - 144px); /* Adjusted for header */
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }

        .controls-section {
            width: 400px;
            padding: 24px;
            background: var(--card-bg);
            border-radius: 12px;
            height: calc(100vh - 104px); /* Adjusted for header */
            overflow-y: auto;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        .upload-section {
            margin-bottom: 24px;
            background: var(--bg-color);
            padding: 20px;
            border-radius: 8px;
            border: 2px dashed var(--border-color);
            transition: all 0.3s ease;
        }

        .upload-section:hover {
            border-color: var(--primary-color);
        }

        .upload-section h3 {
            margin-bottom: 16px;
            font-size: 1.1rem;
            color: var(--text-color);
        }

        .file-input-wrapper {
            position: relative;
            margin-bottom: 16px;
        }

        .file-input-wrapper input[type="file"] {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
        }

        .file-input-button {
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 12px;
            background-color: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            color: var(--secondary-text);
            font-size: 0.9rem;
            transition: all 0.2s ease;
        }

        .file-input-wrapper:hover .file-input-button {
            border-color: var(--primary-color);
            color: var(--primary-color);
        }

        .placement-area {
            position: absolute;
            border: 2px dashed var(--primary-color);
            background-color: rgba(59, 130, 246, 0.1);
            cursor: move;
            touch-action: none;
        }

        .resize-handle {
            width: 12px;
            height: 12px;
            background-color: white;
            border: 2px solid var(--primary-color);
            position: absolute;
            border-radius: 50%;
            transition: transform 0.2s ease;
        }

        .resize-handle:hover {
            transform: scale(1.2);
        }

        .resize-handle.top-left { top: -6px; left: -6px; cursor: nw-resize; }
        .resize-handle.top-right { top: -6px; right: -6px; cursor: ne-resize; }
        .resize-handle.bottom-left { bottom: -6px; left: -6px; cursor: sw-resize; }
        .resize-handle.bottom-right { bottom: -6px; right: -6px; cursor: se-resize; }

        button {
            padding: 12px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            margin: 8px 0;
            width: 100%;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: all 0.2s ease;
        }

        button:hover {
            background-color: var(--primary-hover);
            transform: translateY(-1px);
        }

        .dimensions-info {
            margin: 12px 0;
            padding: 12px;
            background: var(--bg-color);
            border-radius: 6px;
            font-size: 0.9rem;
            color: #64748b;
        }

        #progress {
            margin-top: 24px;
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background-color: var(--bg-color);
            border-radius: 4px;
            overflow: hidden;
        }

        .progress-fill {
            height: 100%;
            background-color: var(--primary-color);
            width: 0%;
            transition: width 0.3s ease;
        }

        .hidden {
            display: none !important;
        }

        #status {
            margin-top: 12px;
            font-size: 0.9rem;
            color: var(--secondary-text);
        }

        /* Add this to your existing CSS */
        .placement-area {
            transform-origin: center center;
        }

        .rotate-handle {
            width: 20px;
            height: 20px;
            background-color: var(--primary-color);
            border: 2px solid white;
            position: absolute;
            border-radius: 50%;
            top: -30px;
            left: 50%;
            transform: translateX(-50%);
            cursor: grab;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 12px;
        }

        .rotate-handle:active {
            cursor: grabbing;
        }

        .rotate-line {
            position: absolute;
            width: 2px;
            height: 20px;
            background-color: var(--primary-color);
            bottom: 100%;
            left: 50%;
            transform: translateX(-50%);
        }

        .option-row {
            display: flex;
            align-items: center;
            gap: 8px;
            margin: 24px 0;
            padding: 12px;
            background: var(--bg-color);
            border-radius: 8px;
        }

        .checkbox-wrapper {
            display: flex;
            align-items: center;
            gap: 8px;
        }

        .custom-checkbox {
            appearance: none;
            width: 18px;
            height: 18px;
            border: 2px solid var(--border-color);
            border-radius: 4px;
            cursor: pointer;
            position: relative;
            background: var(--card-bg);
            transition: all 0.2s ease;
        }

        .custom-checkbox:checked {
            background: var(--primary-color);
            border-color: var(--primary-color);
        }

        .custom-checkbox:checked::after {
            content: '\f00c';
            font-family: 'Font Awesome 5 Free';
            font-weight: 900;
            color: white;
            font-size: 11px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }

        .custom-checkbox:hover {
            border-color: var(--primary-color);
        }

        .checkbox-wrapper label {
            color: var(--text-color);
            cursor: pointer;
            font-size: 0.9rem;
        }

        .tooltip-trigger {
            position: relative;
            color: var(--secondary-text);
            cursor: help;
        }

        .tooltip-trigger i {
            font-size: 16px;
        }

        .tooltip-content {
            visibility: hidden;
            position: absolute;
            bottom: calc(100% + 10px);
            left: 50%;
            transform: translateX(-50%);
            width: 250px;
            padding: 8px 12px;
            background: var(--card-bg);
            border: 1px solid var(--border-color);
            border-radius: 6px;
            color: var(--text-color);
            font-size: 0.85rem;
            line-height: 1.4;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
            opacity: 0;
            transition: opacity 0.2s ease, visibility 0.2s ease;
            z-index: 10;
        }

        .tooltip-content::after {
            content: '';
            position: absolute;
            top: 100%;
            left: 50%;
            transform: translateX(-50%);
            border-width: 6px;
            border-style: solid;
            border-color: var(--border-color) transparent transparent transparent;
        }

        .tooltip-trigger:hover .tooltip-content {
            visibility: visible;
            opacity: 1;
        }

        /* Add these styles to your existing CSS */
        .mockup-selector {
            margin: 20px 0;
            width: 100%;
        }

        .mockup-select {
            width: 100%;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            background-color: var(--card-bg);
            color: var(--text-color);
            font-size: 0.9rem;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .mockup-select:hover {
            border-color: var(--primary-color);
        }

        .mockup-select:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
        }

    </style>
</head>
<body>
    <header class="header">
        <div class="logo">
            <i class="fas fa-tshirt"></i>
            Mockup Generator
        </div>
        <div class="nav-links"> 
            <a href="#">Home</a> <!-- class="active" -->
            <a href="#">About</a>
            <a href="#">Contact</a>
        </div>
        <button class="theme-toggle" onclick="toggleTheme()">
            <i class="fas fa-moon"></i>
            <p>Theme</p>
        </button>
    </header>

    <div class="container">
        <div class="canvas-section">
            <div class="canvas-container">
                <div class="canvas-wrapper">
                    <canvas id="mockupCanvas"></canvas>
                    <div id="placementArea" class="placement-area">
                        <div class="resize-handle top-left"></div>
                        <div class="resize-handle top-right"></div>
                        <div class="resize-handle bottom-left"></div>
                        <div class="resize-handle bottom-right"></div>
                        <div class="rotate-line"></div>
                        <div class="rotate-handle">
                            <i class="fas fa-sync-alt"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="controls-section">
            <div class="upload-section">
                <h3>Upload Mockup Folder</h3>
                <div class="file-input-wrapper">
                    <input type="file" id="mockupInput" webkitdirectory directory multiple>
                    <div class="file-input-button">
                        <i class="fas fa-folder-open"></i>
                        Choose Mockup Folder
                    </div>
                </div>
            </div>

            <div class="upload-section">
                <h3>Upload Design Folder</h3>
                <div class="file-input-wrapper">
                    <input type="file" id="designInput" webkitdirectory directory multiple>
                    <div class="file-input-button">
                        <i class="fas fa-folder-open"></i>
                        Choose Design Folder
                    </div>
                </div>
            </div>


            <div class="option-row">
                <div class="checkbox-wrapper">
                    <input type="checkbox" id="boundingBoxFit" class="custom-checkbox">
                    <label for="boundingBoxFit">Smart Fit</label>
                </div>
                <div class="tooltip-trigger">
                    <i class="fas fa-info-circle"></i>
                    <div class="tooltip-content">
                        Automatically fits the placement area to the visible content of your design, ignoring transparent spaces
                    </div>
                </div>
            </div>

            <div class="mockup-selector">
                <select id="mockupSelect" class="mockup-select">
                    <option value="">Select a mockup</option>
                </select>
            </div>

            <button id="previewButton" onclick="togglePreview()">
                <i class="fas fa-eye"></i>
                Preview First Design
            </button>
            <button onclick="processAllDesigns()">
                <i class="fas fa-magic"></i>
                Generate All Mockups
            </button>

            <div id="progress">
                <div class="progress-bar">
                    <div class="progress-fill" id="progressFill"></div>
                </div>
                <div id="status">Ready to process</div>
            </div>
        </div>
    </div>

    <!-- Include JSZip Library -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script>
        function toggleTheme() {
            const html = document.documentElement;
            const themeToggle = document.querySelector('.theme-toggle i');
            
            if (html.getAttribute('data-theme') === 'light') {
                html.removeAttribute('data-theme');
                themeToggle.className = 'fas fa-moon';
            } else {
                html.setAttribute('data-theme', 'light');
                themeToggle.className = 'fas fa-sun';
            }
        }

        class MockupGenerator {
            constructor() {
                this.initializeElements();
                this.initializeState();
                this.addEventListeners();
                this.isPreviewMode = false;
            }

            // Method remains the same as in the original code
            initializeElements() {
                this.canvas = document.getElementById('mockupCanvas');
                this.ctx = this.canvas.getContext('2d');
                this.progressFill = document.getElementById('progressFill');
                this.statusText = document.getElementById('status');
                this.placementArea = document.getElementById('placementArea');
                this.previewButton = document.getElementById('previewButton');
                this.mockupSelect = document.getElementById('mockupSelect');
            }

            initializeState() {
                this.mockups = []; // Array to store multiple mockup images
                this.mockupData = new Map(); // Map to store placement data for each mockup
                this.currentMockupIndex = 0;
                this.designs = [];
                this.isDragging = false;
                this.isResizing = false;
                this.currentHandle = null;
                this.startX = 0;
                this.startY = 0;
                this.startAreaX = 0;
                this.startAreaY = 0;
                this.startAreaWidth = 0;
                this.startAreaHeight = 0;
                this.scaleFactor = 1;
                this.isRotating = false;
                this.rotation = 0;
                this.rotateStartAngle = 0;
            }

            // Add necessary event listeners
            addEventListeners() {
                window.addEventListener('resize', () => this.handleWindowResize());

                // File inputs
                document.getElementById('mockupInput').addEventListener('change', (e) => this.handleMockupUpload(e));
                document.getElementById('designInput').addEventListener('change', (e) => this.handleDesignUpload(e));

                // Drag and Resize
                this.placementArea.addEventListener('mousedown', (e) => this.handlePlacementAreaMouseDown(e));

                // Resize handles
                const resizeHandles = this.placementArea.querySelectorAll('.resize-handle');
                resizeHandles.forEach(handle => {
                    handle.addEventListener('mousedown', (e) => this.handleResizeHandleMouseDown(e, handle));
                });

                // Mouse move and up on the document
                document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
                document.addEventListener('mouseup', () => this.handleMouseUp());

                const rotateHandle = this.placementArea.querySelector('.rotate-handle');
                rotateHandle.addEventListener('mousedown', (e) => this.handleRotateHandleMouseDown(e));

                document.getElementById('mockupInput').addEventListener('change', (e) => this.handleMockupFolderUpload(e));
    
                this.mockupSelect.addEventListener('change', (e) => {
                    const index = parseInt(e.target.value);
                    if (!isNaN(index)) {
                        this.switchMockup(index);
                    }
                });

                document.addEventListener('mouseup', () => {
                    if (this.isDragging || this.isResizing || this.isRotating) {
                        this.savePlacementData();
                    }
                    this.isDragging = false;
                    this.isResizing = false;
                    this.isRotating = false;
                    this.currentHandle = null;
                });
            }

            // Handle window resize to adjust canvas and placement area
            handleWindowResize() {
                if (this.mockupImage) {
                    this.updateCanvasDisplaySize();
                }
            }

            getBoundingBox(context, width, height) {
                const imageData = context.getImageData(0, 0, width, height);
                const data = imageData.data;
                let minX = width;
                let minY = height;
                let maxX = 0;
                let maxY = 0;

                // Scan through each pixel
                for (let y = 0; y < height; y++) {
                    for (let x = 0; x < width; x++) {
                        const alpha = data[((y * width + x) * 4) + 3];
                        if (alpha > 0) { // If pixel is not completely transparent
                            minX = Math.min(minX, x);
                            minY = Math.min(minY, y);
                            maxX = Math.max(maxX, x);
                            maxY = Math.max(maxY, y);
                        }
                    }
                }

                // Return null if no visible pixels were found
                if (minX > maxX || minY > maxY) {
                    return null;
                }

                return {
                    x: minX,
                    y: minY,
                    width: maxX - minX + 1,
                    height: maxY - minY + 1
                };
            }


            // Handle mockup folder upload
            async handleMockupFolderUpload(event) {
                const files = Array.from(event.target.files).filter(file => file.type.startsWith('image/'));
                this.mockups = [];
                this.mockupData.clear();
                this.mockupSelect.innerHTML = '<option value="">Select a mockup</option>';

                try {
                    for (let i = 0; i < files.length; i++) {
                        const mockupImage = await this.loadImage(files[i]);
                        this.mockups.push({
                            image: mockupImage,
                            name: files[i].name
                        });

                        // Initialize placement data for each mockup
                        this.mockupData.set(i, {
                            areaX: 186,
                            areaY: 189,
                            areaWidth: 707,
                            areaHeight: 588,
                            rotation: 0
                        });

                        // Add to dropdown
                        const option = document.createElement('option');
                        option.value = i;
                        option.textContent = files[i].name;
                        this.mockupSelect.appendChild(option);
                    }

                    if (this.mockups.length > 0) {
                        this.currentMockupIndex = 0;
                        this.mockupSelect.value = "0";
                        await this.switchMockup(0);
                    }

                    this.statusText.textContent = `${this.mockups.length} mockups loaded`;
                } catch (error) {
                    console.error('Error loading mockups:', error);
                    alert('Failed to load some mockup images. Please try again.');
                }
            }            

            // Handle mockup image upload
            async handleMockupUpload(event) {
                const file = event.target.files[0];
                if (!file) return;

                try {
                    this.mockupImage = await this.loadImage(file);
                    
                    // Additional error checks
                    if (!this.mockupImage.width || !this.mockupImage.height) {
                        throw new Error('Invalid image dimensions');
                    }

                    this.canvas.width = this.mockupImage.width;
                    this.canvas.height = this.mockupImage.height;

                    this.updateCanvasDisplaySize();
                    this.drawMockup();
                } catch (error) {
                    console.error('Error loading mockup image:', error);
                    alert('Failed to load mockup image. Please try a different file.');
                }
            }

            // Switch between mockups
            async switchMockup(index) {
                if (index < 0 || index >= this.mockups.length) return;
                
                // Save current placement data before switching
                if (this.currentMockupIndex !== index) {
                    this.savePlacementData();
                }

                this.currentMockupIndex = index;
                const mockup = this.mockups[index];
                let placementData = this.mockupData.get(index);

                // If no placement data exists for this mockup, initialize with default values
                if (!placementData) {
                    placementData = {
                        areaX: 186,
                        areaY: 189,
                        areaWidth: 707,
                        areaHeight: 588,
                        rotation: 0
                    };
                    this.mockupData.set(index, placementData);
                }

                // Update canvas dimensions
                this.canvas.width = mockup.image.width;
                this.canvas.height = mockup.image.height;

                // Restore placement data for this mockup
                this.areaX = placementData.areaX;
                this.areaY = placementData.areaY;
                this.areaWidth = placementData.areaWidth;
                this.areaHeight = placementData.areaHeight;
                this.rotation = placementData.rotation;

                // Exit preview mode if active
                if (this.isPreviewMode) {
                    this.exitPreview();
                }

                this.updateCanvasDisplaySize();
                this.drawMockup();
                this.updatePlacementArea();
                this.placementArea.style.transform = `rotate(${this.rotation}deg)`;
            }

            // Save current placement data
            savePlacementData() {
                this.mockupData.set(this.currentMockupIndex, {
                    areaX: this.areaX,
                    areaY: this.areaY,
                    areaWidth: this.areaWidth,
                    areaHeight: this.areaHeight,
                    rotation: this.rotation
                });
            }



            // Handle design folder upload
            handleDesignUpload(event) {
                this.designs = Array.from(event.target.files).filter(file => file.type.startsWith('image/'));
                this.statusText.textContent = `${this.designs.length} designs ready to process`;
            }

            // Load image from file
            loadImage(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const img = new Image();
                        img.onload = () => resolve(img);
                        img.onerror = reject;
                        img.src = e.target.result;
                    };
                    reader.onerror = reject;
                    reader.readAsDataURL(file);
                });
            }

            // Update the display size of the canvas based on container size
            updateCanvasDisplaySize() {
                const container = this.canvas.parentElement.parentElement;
                const containerWidth = container.clientWidth - 40; // Account for padding
                const containerHeight = container.clientHeight - 40; // Account for padding

                // Calculate scale factor to fit mockup image within container
                this.scaleFactor = Math.min(containerWidth / this.mockupImage.width, containerHeight / this.mockupImage.height);

                // Apply scaling via CSS
                this.canvas.style.width = `${this.mockupImage.width * this.scaleFactor}px`;
                this.canvas.style.height = `${this.mockupImage.height * this.scaleFactor}px`;

                // Update placement area position and size
                this.updatePlacementArea();
            }

            // Draw the mockup image onto the canvas
            drawMockup() {
                if (!this.mockups.length) return;
                const currentMockup = this.mockups[this.currentMockupIndex];
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.ctx.drawImage(currentMockup.image, 0, 0, this.canvas.width, this.canvas.height);
            }

            // Update the placement area's CSS based on current canvas and area coordinates
            updatePlacementArea() {
                const displayedWidth = this.canvas.width * this.scaleFactor;
                const displayedHeight = this.canvas.height * this.scaleFactor;

                // Convert canvas coordinates to CSS pixels
                const left = this.areaX * this.scaleFactor;
                const top = this.areaY * this.scaleFactor;
                const width = this.areaWidth * this.scaleFactor;
                const height = this.areaHeight * this.scaleFactor;

                // Clamp position to stay within the canvas
                const clampedLeft = Math.max(0, Math.min(left, displayedWidth - width));
                const clampedTop = Math.max(0, Math.min(top, displayedHeight - height));

                this.placementArea.style.left = `${clampedLeft}px`;
                this.placementArea.style.top = `${clampedTop}px`;
                this.placementArea.style.width = `${width}px`;
                this.placementArea.style.height = `${height}px`;
            }

            handleRotateHandleMouseDown(event) {
                this.isRotating = true;
                const rect = this.placementArea.getBoundingClientRect();
                const centerX = rect.left + rect.width / 2;
                const centerY = rect.top + rect.height / 2;
                
                // Store the initial angle and current rotation
                this.rotateStartAngle = Math.atan2(event.clientY - centerY, event.clientX - centerX);
                this.initialRotation = this.rotation || 0;
                
                event.stopPropagation();
                event.preventDefault();
            }

            handleRotate(event) {
                const rect = this.placementArea.getBoundingClientRect();
                const centerX = rect.left + rect.width / 2;
                const centerY = rect.top + rect.height / 2;
                
                const currentAngle = Math.atan2(event.clientY - centerY, event.clientX - centerX);
                let angleDiff = (currentAngle - this.rotateStartAngle) * (180 / Math.PI);
                
                // Calculate new rotation based on initial rotation plus the change
                let newRotation = this.initialRotation + angleDiff;
                
                // Add damping factor to make rotation smoother
                const dampingFactor = 0.5; // Adjust this value between 0 and 1 for different sensitivity
                newRotation = this.initialRotation + (angleDiff * dampingFactor);
                
                // Snap to 15-degree intervals when holding Shift
                if (event.shiftKey) {
                    newRotation = Math.round(newRotation / 15) * 15;
                }
                
                this.rotation = newRotation;
                this.placementArea.style.transform = `rotate(${this.rotation}deg)`;
            }


            // Event handler for mousedown on the placement area (for dragging)
            handlePlacementAreaMouseDown(event) {
                if (event.target.classList.contains('resize-handle')) {
                    // If the target is a resize handle, do not initiate drag
                    return;
                }
                this.isDragging = true;
                const rect = this.placementArea.getBoundingClientRect();
                this.startX = event.clientX - rect.left;
                this.startY = event.clientY - rect.top;
                event.preventDefault();
            }

            // Event handler for mousedown on a resize handle
            handleResizeHandleMouseDown(event, handle) {
                this.isResizing = true;
                this.currentHandle = handle;

                // Store initial mouse position and placement area dimensions
                this.startX = event.clientX;
                this.startY = event.clientY;
                this.startAreaX = this.areaX;
                this.startAreaY = this.areaY;
                this.startAreaWidth = this.areaWidth;
                this.startAreaHeight = this.areaHeight;

                event.stopPropagation();
                event.preventDefault();
            }

            // Event handler for mousemove (handles both dragging and resizing)
            handleMouseMove(event) {
                if (this.isDragging) {
                    this.handleDrag(event);
                } else if (this.isResizing) {
                    this.handleResize(event);
                } else if (this.isRotating) {
                    this.handleRotate(event);
                }
            }

            // Handle dragging of the placement area
            handleDrag(event) {
                const canvasRect = this.canvas.getBoundingClientRect();

                // Calculate new position in canvas coordinates
                let newLeft = (event.clientX - canvasRect.left - this.startX) / this.scaleFactor;
                let newTop = (event.clientY - canvasRect.top - this.startY) / this.scaleFactor;

                // Clamp to canvas boundaries
                newLeft = Math.max(0, Math.min(newLeft, this.canvas.width - this.areaWidth));
                newTop = Math.max(0, Math.min(newTop, this.canvas.height - this.areaHeight));

                // Update placement area coordinates
                this.areaX = newLeft;
                this.areaY = newTop;

                this.updatePlacementArea();
            }

            // Handle resizing of the placement area
            handleResize(event) {
                const dx = (event.clientX - this.startX) / this.scaleFactor;
                const dy = (event.clientY - this.startY) / this.scaleFactor;

                let newAreaX = this.startAreaX;
                let newAreaY = this.startAreaY;
                let newAreaWidth = this.startAreaWidth;
                let newAreaHeight = this.startAreaHeight;

                const minSize = 50; // Minimum size in canvas pixels

                if (this.currentHandle.classList.contains('top-left')) {
                    newAreaX = this.startAreaX + dx;
                    newAreaY = this.startAreaY + dy;
                    newAreaWidth = this.startAreaWidth - dx;
                    newAreaHeight = this.startAreaHeight - dy;
                } else if (this.currentHandle.classList.contains('top-right')) {
                    newAreaY = this.startAreaY + dy;
                    newAreaWidth = this.startAreaWidth + dx;
                    newAreaHeight = this.startAreaHeight - dy;
                } else if (this.currentHandle.classList.contains('bottom-left')) {
                    newAreaX = this.startAreaX + dx;
                    newAreaWidth = this.startAreaWidth - dx;
                    newAreaHeight = this.startAreaHeight + dy;
                } else if (this.currentHandle.classList.contains('bottom-right')) {
                    newAreaWidth = this.startAreaWidth + dx;
                    newAreaHeight = this.startAreaHeight + dy;
                }

                // Enforce minimum size
                if (newAreaWidth < minSize) {
                    newAreaWidth = minSize;
                    if (this.currentHandle.classList.contains('top-left') || this.currentHandle.classList.contains('bottom-left')) {
                        newAreaX = this.startAreaX + (this.startAreaWidth - minSize);
                    }
                }

                if (newAreaHeight < minSize) {
                    newAreaHeight = minSize;
                    if (this.currentHandle.classList.contains('top-left') || this.currentHandle.classList.contains('top-right')) {
                        newAreaY = this.startAreaY + (this.startAreaHeight - minSize);
                    }
                }

                // Clamp to canvas boundaries
                if (newAreaX < 0) {
                    newAreaWidth += newAreaX;
                    newAreaX = 0;
                }
                if (newAreaY < 0) {
                    newAreaHeight += newAreaY;
                    newAreaY = 0;
                }
                if (newAreaX + newAreaWidth > this.canvas.width) {
                    newAreaWidth = this.canvas.width - newAreaX;
                }
                if (newAreaY + newAreaHeight > this.canvas.height) {
                    newAreaHeight = this.canvas.height - newAreaY;
                }

                // Update placement area coordinates
                this.areaX = newAreaX;
                this.areaY = newAreaY;
                this.areaWidth = newAreaWidth;
                this.areaHeight = newAreaHeight;

                this.updatePlacementArea();
            }

            // Event handler for mouseup to stop dragging/resizing
            handleMouseUp() {
                this.isDragging = false;
                this.isResizing = false;
                this.isRotating = false;
                this.currentHandle = null;
            }

            // Draw mockup and designs on the main canvas
            async drawMockupWithDesign(context, designImage) {
                context.clearRect(0, 0, this.canvas.width, this.canvas.height);
                context.drawImage(this.mockupImage, 0, 0, this.canvas.width, this.canvas.height);

                // Create a temporary canvas to analyze the design image
                const tempCanvas = document.createElement('canvas');
                const tempCtx = tempCanvas.getContext('2d');
                tempCanvas.width = designImage.width;
                tempCanvas.height = designImage.height;
                tempCtx.drawImage(designImage, 0, 0);

                let designWidth = designImage.width;
                let designHeight = designImage.height;

                // If bounding box fit is enabled, get the actual content dimensions
                if (document.getElementById('boundingBoxFit').checked) {
                    const boundingBox = this.getBoundingBox(tempCtx, designWidth, designHeight);
                    if (boundingBox) {
                        designWidth = boundingBox.width;
                        designHeight = boundingBox.height;
                        // Create another temp canvas for the cropped image
                        const croppedCanvas = document.createElement('canvas');
                        croppedCanvas.width = boundingBox.width;
                        croppedCanvas.height = boundingBox.height;
                        const croppedCtx = croppedCanvas.getContext('2d');
                        croppedCtx.drawImage(designImage, 
                            boundingBox.x, boundingBox.y, boundingBox.width, boundingBox.height,
                            0, 0, boundingBox.width, boundingBox.height
                        );
                        // Create a new image from the cropped canvas
                        const croppedImage = new Image();
                        await new Promise(resolve => {
                            croppedImage.onload = resolve;
                            croppedImage.src = croppedCanvas.toDataURL();
                        });
                        designImage = croppedImage;
                    }
                }

                const [finalWidth, finalHeight] = this.calculateAspectRatioFit(
                    designWidth,
                    designHeight,
                    this.areaWidth,
                    this.areaHeight
                );

                const x = this.areaX + (this.areaWidth - finalWidth) / 2;
                const y = this.areaY;

                // Save the current context state
                context.save();
                
                // Translate to the center of the placement area
                const centerX = x + finalWidth / 2;
                const centerY = y + finalHeight / 2;
                context.translate(centerX, centerY);
                
                // Rotate
                context.rotate(this.rotation * Math.PI / 180);
                
                // Draw the image centered
                context.drawImage(designImage, -finalWidth / 2, -finalHeight / 2, finalWidth, finalHeight);
                
                // Restore the context state
                context.restore();
            }

            // Calculate aspect ratio fit
            calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
                const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
                return [srcWidth * ratio, srcHeight * ratio];
            }

            // Modify preview design method
            async previewDesign() {
                if (!this.mockups[this.currentMockupIndex] || this.designs.length === 0) {
                    alert('Please upload both mockup template and design files.');
                    return;
                }

                try {
                    const currentMockup = this.mockups[this.currentMockupIndex];
                    const designImage = await this.loadImage(this.designs[0]);
                    
                    // Set canvas dimensions for current mockup
                    this.canvas.width = currentMockup.image.width;
                    this.canvas.height = currentMockup.image.height;
                    
                    // Get placement data for current mockup
                    const placementData = this.mockupData.get(this.currentMockupIndex);
                    
                    // Set the current mockup image
                    this.mockupImage = currentMockup.image;
                    
                    // Apply placement data
                    this.areaX = placementData.areaX;
                    this.areaY = placementData.areaY;
                    this.areaWidth = placementData.areaWidth;
                    this.areaHeight = placementData.areaHeight;
                    this.rotation = placementData.rotation;
                    
                    await this.drawMockupWithDesign(this.ctx, designImage);
                    
                    // Toggle preview mode
                    this.placementArea.classList.add('hidden');
                    this.isPreviewMode = true;
                    this.previewButton.innerHTML = `<i class="fas fa-eye-slash"></i> Hide Preview`;
                } catch (error) {
                    console.error('Error previewing design:', error);
                    alert('Failed to preview design. Please try a different file.');
                }
            }

            // Method to exit preview mode
            exitPreview() {
                if (!this.mockupImage) return;

                const currentMockup = this.mockups[this.currentMockupIndex];
                // Make sure we're using the current mockup image
                this.mockupImage = currentMockup.image;
                this.drawMockup();
                this.placementArea.classList.remove('hidden');
                this.isPreviewMode = false;
                this.previewButton.innerHTML = `<i class="fas fa-eye"></i> Preview First Design`;
            }

            // Process all designs and generate mockups
            async processAllDesigns() {
                if (this.mockups.length === 0 || this.designs.length === 0) {
                    alert('Please upload both mockup templates and design files.');
                    return;
                }

                const zip = new JSZip();
                const total = this.mockups.length * this.designs.length;
                let current = 0;

                // Save current mockup index to restore later
                const originalMockupIndex = this.currentMockupIndex;

                try {
                    // First loop through mockups, then designs
                    for (let mockupIndex = 0; mockupIndex < this.mockups.length; mockupIndex++) {
                        const mockup = this.mockups[mockupIndex];
                        const placementData = this.mockupData.get(mockupIndex);

                        // Set up canvas and placement data for this mockup
                        this.canvas.width = mockup.image.width;
                        this.canvas.height = mockup.image.height;
                        this.mockupImage = mockup.image;

                        // Apply placement data
                        this.areaX = placementData.areaX;
                        this.areaY = placementData.areaY;
                        this.areaWidth = placementData.areaWidth;
                        this.areaHeight = placementData.areaHeight;
                        this.rotation = placementData.rotation;

                        // Process each design for this mockup
                        for (let designIndex = 0; designIndex < this.designs.length; designIndex++) {
                            const design = this.designs[designIndex];
                            const designImage = await this.loadImage(design);

                            // Draw mockup with design
                            await this.drawMockupWithDesign(this.ctx, designImage);

                            // Save to zip
                            const mockupBlob = await new Promise(resolve => {
                                this.canvas.toBlob(resolve, 'image/png', 1.0);
                            });

                            // Create a descriptive filename
                            const fileName = `mockup${mockupIndex + 1}_${mockup.name}_design${designIndex + 1}_${design.name}.png`;
                            zip.file(fileName, mockupBlob);

                            current++;
                            this.updateProgress(current, total);
                        }
                    }

                    // Generate and download zip
                    const zipBlob = await zip.generateAsync({ type: 'blob' });
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(zipBlob);
                    link.download = 'mockups.zip';
                    link.click();

                    // Clean up
                    URL.revokeObjectURL(link.href);
                    
                    // Restore original mockup state
                    await this.switchMockup(originalMockupIndex);
                    
                    this.statusText.textContent = 'All mockups generated and downloaded!';
                } catch (error) {
                    console.error('Error processing designs:', error);
                    alert('Failed to process all designs. Please try again.');
                    // Restore original mockup state even if there's an error
                    await this.switchMockup(originalMockupIndex);
                }
            }

            // Update progress bar and status text
            updateProgress(current, total) {
                const percentage = (current / total) * 100;
                this.progressFill.style.width = `${percentage}%`;
                this.statusText.textContent = `Processing: ${current} of ${total} designs`;
            }

        }

        // Initialize the application
        const mockupGenerator = new MockupGenerator();

        // Global function to toggle preview
        function togglePreview() {
            if (mockupGenerator.isPreviewMode) {
                mockupGenerator.exitPreview();
            } else {
                mockupGenerator.previewDesign();
            }
        }

        // Expose global functions for button clicks
        window.processAllDesigns = () => mockupGenerator.processAllDesigns();
        window.previewDesign = () => mockupGenerator.previewDesign();
        window.togglePreview = togglePreview;
    </script>
</body>
</html>