Problem resizing placement area. I can drag the placement area but not resize it. I have uploaded older version where the resizing function is working for your reference. 

New Version where resizing is nor working
<!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>
        :root {
            --primary-color: #3b82f6;
            --primary-hover: #2563eb;
            --bg-color: #f8fafc;
            --border-color: #e2e8f0;
        }

        * {
            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: #1e293b;
        }

        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
            display: flex;
            gap: 24px;
            height: 100vh;
        }

        .canvas-section {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 40px);
            background: white;
            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: #fff;
            border-radius: 12px;
            position: relative;
            overflow: hidden;
            padding: 20px;
        }

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

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

        .controls-section {
            width: 400px;
            padding: 24px;
            background: white;
            border-radius: 12px;
            height: calc(100vh - 40px);
            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: #1e293b;
        }

        .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: white;
            border: 1px solid var(--border-color);
            border-radius: 6px;
            color: #64748b;
            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;
        }

        #status {
            margin-top: 12px;
            font-size: 0.9rem;
            color: #64748b;
        }

        .preview {
            margin-top: 24px;
        }

        .preview h3 {
            margin-bottom: 12px;
            font-size: 1.1rem;
        }

        #previewCanvas {
            width: 100%;
            height: auto;
            border-radius: 6px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
        }

        /* Loading animation */
        @keyframes pulse {
            0% { transform: scale(1); }
            50% { transform: scale(1.05); }
            100% { transform: scale(1); }
        }

        .loading {
            animation: pulse 2s infinite;
        }
    </style>
</head>
<body>
    <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>
                </div>
            </div>
        </div>

        <div class="controls-section">
            <div class="upload-section">
                <h3>Upload Mockup Template</h3>
                <div class="file-input-wrapper">
                    <input type="file" id="mockupInput" accept="image/*">
                    <div class="file-input-button">
                        <i class="fas fa-upload"></i>
                        Choose Mockup Template
                    </div>
                </div>
                <div class="dimensions-info" id="mockupDimensions">
                    No mockup template uploaded
                </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>

            <button onclick="processAllDesigns()">
                <i class="fas fa-magic"></i>
                Generate All Mockups
            </button>
            <button onclick="previewDesign()">
                <i class="fas fa-eye"></i>
                Preview First Design
            </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 class="preview">
                <h3>Preview:</h3>
                <canvas id="previewCanvas"></canvas>
            </div>
        </div>
    </div>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
    <script>
        class MockupGenerator {
            constructor() {
                this.initializeElements();
                this.initializeState();
                this.addEventListeners();
            }

            initializeElements() {
                this.canvas = document.getElementById('mockupCanvas');
                this.ctx = this.canvas.getContext('2d');
                this.previewCanvas = document.getElementById('previewCanvas');
                this.previewCtx = this.previewCanvas.getContext('2d');
                this.progressFill = document.getElementById('progressFill');
                this.statusText = document.getElementById('status');
                this.placementArea = document.getElementById('placementArea');
                this.mockupDimensions = document.getElementById('mockupDimensions');
            }

            initializeState() {
                this.mockupImage = null;
                this.designs = [];
                this.isDragging = false;
                this.isResizing = false;
                this.currentHandle = null;
                this.startX = 0;
                this.startY = 0;
                this.startLeft = 0;
                this.startTop = 0;
                this.startWidth = 0;
                this.startHeight = 0;
                this.scaleFactor = 1;
                this.areaX = 186;
                this.areaY = 189;
                this.areaWidth = 707;
                this.areaHeight = 588;
            }

            addEventListeners() {
                window.addEventListener('resize', () => this.handleResize());
                this.setupDragAndResize();
                this.setupFileInputs();
            }

            setupFileInputs() {
                document.getElementById('mockupInput').addEventListener('change', (e) => this.handleMockupUpload(e));
                document.getElementById('designInput').addEventListener('change', (e) => this.handleDesignUpload(e));
            }

            setupDragAndResize() {
                this.placementArea.addEventListener('mousedown', (e) => this.handlePlacementAreaMouseDown(e));
                document.querySelectorAll('.resize-handle').forEach(handle => {
                    handle.addEventListener('mousedown', (e) => this.handleResizeHandleMouseDown(e, handle));
                });
                document.addEventListener('mousemove', (e) => this.handleMouseMove(e));
                document.addEventListener('mouseup', () => this.handleMouseUp());
            }

            updateCanvasSize() {
                if (!this.mockupImage) return;

                const container = this.canvas.parentElement.parentElement;
                const containerWidth = container.clientWidth - 40;
                const containerHeight = container.clientHeight - 40;

                // Set canvas dimensions to match mockup image
                this.canvas.width = this.mockupImage.width;
                this.canvas.height = this.mockupImage.height;

                // Calculate the scaling ratios
                const widthRatio = containerWidth / this.mockupImage.width;
                const heightRatio = containerHeight / this.mockupImage.height;

                // Use the smaller ratio to ensure the image fits in both dimensions
                this.scaleFactor = Math.min(widthRatio, heightRatio);

                // Calculate the display dimensions
                const displayWidth = this.mockupImage.width * this.scaleFactor;
                const displayHeight = this.mockupImage.height * this.scaleFactor;

                // Update canvas display size
                this.canvas.style.width = `${displayWidth}px`;
                this.canvas.style.height = `${displayHeight}px`;

                this.drawMockup();
                this.updatePlacementArea();
            }

            drawMockup() {
                if (!this.mockupImage) return;
                this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
                this.ctx.drawImage(this.mockupImage, 0, 0, this.canvas.width, this.canvas.height);
            }

            updatePlacementArea() {
                const rect = this.canvas.getBoundingClientRect();
                const displayedWidth = rect.width;
                const displayedHeight = rect.height;

                this.placementArea.style.left = (this.areaX * displayedWidth / this.canvas.width) + 'px';
                this.placementArea.style.top = (this.areaY * displayedHeight / this.canvas.height) + 'px';
                this.placementArea.style.width = (this.areaWidth * displayedWidth / this.canvas.width) + 'px';
                this.placementArea.style.height = (this.areaHeight * displayedHeight / this.canvas.height) + 'px';
            }

            // Event Handlers
            async handleMockupUpload(e) {
                const file = e.target.files[0];
                if (!file) return;

                try {
                    this.mockupImage = await this.loadImage(file);
                    this.updateCanvasSize();
                    this.mockupDimensions.textContent = `Mockup dimensions: ${this.mockupImage.width}px × ${this.mockupImage.height}px`;
                    
                    // Initialize preview canvas
                    this.previewCanvas.width = this.mockupImage.width;
                    this.previewCanvas.height = this.mockupImage.height;
                    this.previewCanvas.style.width = '100%';
                    this.previewCanvas.style.height = 'auto';
                } catch (error) {
                    console.error('Error loading mockup:', error);
                    alert('Error loading mockup image. Please try again.');
                }
            }

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

            handlePlacementAreaMouseDown(e) {
                if (e.target === this.placementArea) {
                    this.isDragging = true;
                    const rect = this.placementArea.getBoundingClientRect();
                    this.startX = e.clientX - rect.left;
                    this.startY = e.clientY - rect.top;
                    e.preventDefault();
                }
            }

            handleResizeHandleMouseDown(e, handle) {
                this.isResizing = true;
                this.currentHandle = handle;
                const rect = this.placementArea.getBoundingClientRect();
                this.startX = e.clientX;
                this.startY = e.clientY;
                this.startLeft = rect.left;
                this.startTop = rect.top;
                this.startWidth = rect.width;
                this.startHeight = rect.height;
                e.stopPropagation();
                e.preventDefault();
            }

            handleMouseMove(e) {
                if (this.isDragging) {
                    this.handleDrag(e);
                } else if (this.isResizing) {
                    this.handleResize(e);
                }
            }

            handleDrag(e) {
                const canvasRect = this.canvas.getBoundingClientRect();
                const scaleX = this.canvas.width / canvasRect.width;
                const scaleY = this.canvas.height / canvasRect.height;
                
                let newX = e.clientX - canvasRect.left - this.startX;
                let newY = e.clientY - canvasRect.top - this.startY;
                
                // Constrain to canvas bounds
                newX = Math.max(0, Math.min(newX, canvasRect.width - this.placementArea.offsetWidth));
                newY = Math.max(0, Math.min(newY, canvasRect.height - this.placementArea.offsetHeight));
                
                this.areaX = newX * scaleX;
                this.areaY = newY * scaleY;
                
                this.updatePlacementArea();
            }

            handleResize(e) {
                const canvasRect = this.canvas.getBoundingClientRect();
                const scaleX = this.canvas.width / canvasRect.width;
                const scaleY = this.canvas.height / canvasRect.height;
                
                const dx = e.clientX - this.startX;
                const dy = e.clientY - this.startY;
                
                const minSize = 50;
                let newWidth, newHeight, newX, newY;
                
                if (this.currentHandle.classList.contains('top-left')) {
                    newWidth = this.startWidth - dx;
                    newHeight = this.startHeight - dy;
                    newX = this.startLeft + dx;
                    newY = this.startTop + dy;
                } else if (this.currentHandle.classList.contains('top-right')) {
                    newWidth = this.startWidth + dx;
                    newHeight = this.startHeight - dy;
                    newX = this.startLeft;
                    newY = this.startTop + dy;
                } else if (this.currentHandle.classList.contains('bottom-left')) {
                    newWidth = this.startWidth - dx;
                    newHeight = this.startHeight + dy;
                    newX = this.startLeft + dx;
                    newY = this.startTop;
                } else if (this.currentHandle.classList.contains('bottom-right')) {
                    newWidth = this.startWidth + dx;
                    newHeight = this.startHeight + dy;
                    newX = this.startLeft;
                    newY = this.startTop;
                }
                
                if (newWidth > minSize && newHeight > minSize) {
                    const rect = this.canvas.getBoundingClientRect();
                    this.areaWidth = newWidth * scaleX;
                    this.areaHeight = newHeight * scaleY;
                    this.areaX = (newX - rect.left) * scaleX;
                    this.areaY = (newY - rect.top) * scaleY;
                    
                    this.updatePlacementArea();
                }
            }

            handleMouseUp() {
                this.isDragging = false;
                this.isResizing = false;
                this.currentHandle = null;
            }

            handleResize() {
                if (this.mockupImage) {
                    this.updateCanvasSize();
                }
            }

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

            calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
                const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
                return {
                    width: srcWidth * ratio,
                    height: srcHeight * ratio
                };
            }

            // Core Functionality Methods
            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);

                const dimensions = this.calculateAspectRatioFit(
                    designImage.width,
                    designImage.height,
                    this.areaWidth,
                    this.areaHeight
                );

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

                context.drawImage(designImage, x, y, dimensions.width, dimensions.height);
            }

            async previewDesign() {
                if (!this.mockupImage || this.designs.length === 0) {
                    alert('Please upload both mockup template and design files');
                    return;
                }

                try {
                    const designImage = await this.loadImage(this.designs[0]);
                    await this.drawMockupWithDesign(this.previewCtx, designImage);
                } catch (error) {
                    console.error('Error previewing design:', error);
                    alert('Error previewing design. Please try again.');
                }
            }

            async processAllDesigns() {
                if (!this.mockupImage || this.designs.length === 0) {
                    alert('Please upload both mockup template and design files');
                    return;
                }

                const zip = new JSZip();
                
                try {
                    for (let i = 0; i < this.designs.length; i++) {
                        this.updateProgress(i + 1, this.designs.length);
                        
                        const designImage = await this.loadImage(this.designs[i]);
                        await this.drawMockupWithDesign(this.ctx, designImage);
                        
                        const mockupBlob = await new Promise(resolve => {
                            this.canvas.toBlob(resolve, 'image/png', 1.0);
                        });
                        
                        zip.file(`mockup_${this.designs[i].name}`, mockupBlob);
                    }

                    const zipBlob = await zip.generateAsync({type: 'blob'});
                    const link = document.createElement('a');
                    link.href = URL.createObjectURL(zipBlob);
                    link.download = 'mockups.zip';
                    link.click();
                    
                    this.statusText.textContent = 'All mockups generated and downloaded!';
                } catch (error) {
                    console.error('Error processing designs:', error);
                    alert('Error processing designs. Please try again.');
                }
            }

            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 references for HTML buttons
        window.processAllDesigns = () => mockupGenerator.processAllDesigns();
        window.previewDesign = () => mockupGenerator.previewDesign();
    </script>
</body>
</html>

older version where resizing is working
<!DOCTYPE html>
<html>
<head>
    <title>Bulk T-shirt Mockup Generator</title>
    <style>
        .container {
            max-width: 1600px;
            margin: 0 auto;
            padding: 20px;
            font-family: Arial, sans-serif;
            display: flex;
            gap: 20px;
            height: 100vh;
        }
        .canvas-section {
            flex: 1;
            min-width: 0;
            display: flex;
            flex-direction: column;
            height: calc(100vh - 40px);
        }
        .controls-section {
            width: 400px;
            padding: 20px;
            background: #f5f5f5;
            border-radius: 8px;
            height: calc(100vh - 40px);
            overflow-y: auto;
        }
        .upload-section {
            margin-bottom: 20px;
        }
        .canvas-container {
            height: 100%;
            width: 100%;
            display: flex;
            align-items: flex-start; /* Changed from center to flex-start */
            justify-content: center;
            background: #f8f8f8;
            border: 1px solid #ddd;
            position: relative;
            overflow: hidden;
            /* padding: 20px; Added padding */
        }

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

        #mockupCanvas {
            display: block; /* Added display block */
            max-width: 100%;
            max-height: calc(100vh - 80px); /* Adjusted max height */
        }
        .placement-area {
            position: absolute;
            border: 2px dashed #007bff;
            background-color: rgba(0, 123, 255, 0.1);
            cursor: move;
            touch-action: none;
        }
        .resize-handle {
            width: 10px;
            height: 10px;
            background-color: #007bff;
            position: absolute;
            border-radius: 50%;
        }
        .resize-handle.top-left { top: -5px; left: -5px; cursor: nw-resize; }
        .resize-handle.top-right { top: -5px; right: -5px; cursor: ne-resize; }
        .resize-handle.bottom-left { bottom: -5px; left: -5px; cursor: sw-resize; }
        .resize-handle.bottom-right { bottom: -5px; right: -5px; cursor: se-resize; }
        button {
            padding: 8px 16px;
            background-color: #007bff;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px 0;
            width: 100%;
        }
        button:hover {
            background-color: #0056b3;
        }
        #progress {
            margin-top: 20px;
        }
        .progress-bar {
            width: 100%;
            height: 20px;
            background-color: #fff;
            border-radius: 10px;
            overflow: hidden;
        }
        .progress-fill {
            height: 100%;
            background-color: #007bff;
            width: 0%;
            transition: width 0.3s ease;
        }
        #status {
            margin-top: 10px;
            font-weight: bold;
        }
        .preview {
            margin-top: 20px;
        }
        .preview canvas {
            max-width: 100%;
            height: auto;
        }
        h3 {
            margin: 10px 0;
        }
        .dimensions-info {
            margin: 10px 0;
            padding: 10px;
            background: #fff;
            border-radius: 4px;
        }
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
    </style>
</head>
<body>
    <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>
                </div>
            </div>
        </div>

        <div class="controls-section">
            <div class="upload-section">
                <h3>Upload Mockup Template</h3>
                <input type="file" id="mockupInput" accept="image/*">
                <div class="dimensions-info" id="mockupDimensions"></div>
            </div>

            <div class="upload-section">
                <h3>Upload Design Folder</h3>
                <input type="file" id="designInput" webkitdirectory directory multiple>
            </div>

            <button onclick="processAllDesigns()">Generate All Mockups</button>
            <button onclick="previewDesign()">Preview First Design</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 class="preview">
                <h3>Preview:</h3>
                <canvas id="previewCanvas"></canvas>
            </div>
        </div>
    </div>

    <script>
        const canvas = document.getElementById('mockupCanvas');
        const ctx = canvas.getContext('2d');
        const previewCanvas = document.getElementById('previewCanvas');
        const previewCtx = previewCanvas.getContext('2d');
        const progressFill = document.getElementById('progressFill');
        const statusText = document.getElementById('status');
        const placementArea = document.getElementById('placementArea');
        const mockupDimensions = document.getElementById('mockupDimensions');
        
        let mockupImage = null;
        let designs = [];
        let isDragging = false;
        let isResizing = false;
        let currentHandle = null;
        let startX, startY, startLeft, startTop, startWidth, startHeight;
        let originalImageWidth, originalImageHeight;
        let scaleFactor = 1;
        let areaX = 186, areaY = 189, areaWidth = 707, areaHeight = 588;

        function updateCanvasSize() {
            const container = canvas.parentElement.parentElement;
            const containerWidth = container.clientWidth - 40; // Account for padding
            const containerHeight = container.clientHeight - 40; // Account for padding
            
            if (mockupImage) {
                // Set canvas dimensions to match mockup image
                canvas.width = mockupImage.width;
                canvas.height = mockupImage.height;
                
                // Calculate the scaling ratios
                const widthRatio = containerWidth / mockupImage.width;
                const heightRatio = containerHeight / mockupImage.height;
                
                // Use the smaller ratio to ensure the image fits in both dimensions
                scaleFactor = Math.min(widthRatio, heightRatio);
                
                // Calculate the display dimensions
                const displayWidth = mockupImage.width * scaleFactor;
                const displayHeight = mockupImage.height * scaleFactor;
                
                // Update canvas display size
                canvas.style.width = `${displayWidth}px`;
                canvas.style.height = `${displayHeight}px`;
                
                // Draw the image
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(mockupImage, 0, 0, canvas.width, canvas.height);
                
                updatePlacementArea();
            }
        }

        function updatePlacementArea() {
            const rect = canvas.getBoundingClientRect();
            const displayedWidth = rect.width;
            const displayedHeight = rect.height;
            
            placementArea.style.left = (areaX * displayedWidth / canvas.width) + 'px';
            placementArea.style.top = (areaY * displayedHeight / canvas.height) + 'px';
            placementArea.style.width = (areaWidth * displayedWidth / canvas.width) + 'px';
            placementArea.style.height = (areaHeight * displayedHeight / canvas.height) + 'px';
        }

        document.getElementById('mockupInput').addEventListener('change', (e) => {
            const file = e.target.files[0];
            const reader = new FileReader();
            
            reader.onload = (event) => {
                mockupImage = new Image();
                mockupImage.onload = () => {
                    updateCanvasSize();
                    mockupDimensions.textContent = `Mockup dimensions: ${mockupImage.width}px × ${mockupImage.height}px`;
                    
                    ctx.clearRect(0, 0, canvas.width, canvas.height);
                    ctx.drawImage(mockupImage, 0, 0, canvas.width, canvas.height);
                    
                    previewCanvas.width = mockupImage.width;
                    previewCanvas.height = mockupImage.height;
                    previewCanvas.style.width = '100%';
                    previewCanvas.style.height = 'auto';
                };
                mockupImage.src = event.target.result;
            };
            
            reader.readAsDataURL(file);
        });

        placementArea.addEventListener('mousedown', function(e) {
            if (e.target === placementArea) {
                isDragging = true;
                const rect = placementArea.getBoundingClientRect();
                startX = e.clientX - rect.left;
                startY = e.clientY - rect.top;
                e.preventDefault();
            }
        });

        document.querySelectorAll('.resize-handle').forEach(handle => {
            handle.addEventListener('mousedown', function(e) {
                isResizing = true;
                currentHandle = handle;
                const rect = placementArea.getBoundingClientRect();
                startX = e.clientX;
                startY = e.clientY;
                startLeft = rect.left;
                startTop = rect.top;
                startWidth = rect.width;
                startHeight = rect.height;
                e.stopPropagation();
                e.preventDefault();
            });
        });

        document.addEventListener('mousemove', function(e) {
            if (isDragging) {
                const canvasRect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / canvasRect.width;
                const scaleY = canvas.height / canvasRect.height;
                
                let newX = e.clientX - canvasRect.left - startX;
                let newY = e.clientY - canvasRect.top - startY;
                
                newX = Math.max(0, Math.min(newX, canvasRect.width - placementArea.offsetWidth));
                newY = Math.max(0, Math.min(newY, canvasRect.height - placementArea.offsetHeight));
                
                areaX = newX * scaleX;
                areaY = newY * scaleY;
                
                updatePlacementArea();
            } else if (isResizing) {
                const canvasRect = canvas.getBoundingClientRect();
                const scaleX = canvas.width / canvasRect.width;
                const scaleY = canvas.height / canvasRect.height;
                
                const dx = e.clientX - startX;
                const dy = e.clientY - startY;
                
                const minSize = 50;
                let newWidth, newHeight, newX, newY;
                
                if (currentHandle.classList.contains('top-left')) {
                    newWidth = startWidth - dx;
                    newHeight = startHeight - dy;
                    newX = startLeft + dx;
                    newY = startTop + dy;
                } else if (currentHandle.classList.contains('top-right')) {
                    newWidth = startWidth + dx;
                    newHeight = startHeight - dy;
                    newX = startLeft;
                    newY = startTop + dy;
                } else if (currentHandle.classList.contains('bottom-left')) {
                    newWidth = startWidth - dx;
                    newHeight = startHeight + dy;
                    newX = startLeft + dx;
                    newY = startTop;
                } else if (currentHandle.classList.contains('bottom-right')) {
                    newWidth = startWidth + dx;
                    newHeight = startHeight + dy;
                    newX = startLeft;
                    newY = startTop;
                }
                
                if (newWidth > minSize && newHeight > minSize) {
                    const rect = canvas.getBoundingClientRect();
                    areaWidth = newWidth * scaleX;
                    areaHeight = newHeight * scaleY;
                    areaX = (newX - rect.left) * scaleX;
                    areaY = (newY - rect.top) * scaleY;
                    
                    updatePlacementArea();
                }
            }
        });

        document.addEventListener('mouseup', function() {
            isDragging = false;
            isResizing = false;
            currentHandle = null;
        });

        window.addEventListener('resize', () => {
            if (mockupImage) {
                updateCanvasSize();
                ctx.clearRect(0, 0, canvas.width, canvas.height);
                ctx.drawImage(mockupImage, 0, 0, canvas.width, canvas.height);
            }
        });

        document.getElementById('designInput').addEventListener('change', (e) => {
            designs = Array.from(e.target.files).filter(file => 
                file.type.startsWith('image/')
            );
            statusText.textContent = `${designs.length} designs ready to process`;
        });

        function calculateAspectRatioFit(srcWidth, srcHeight, maxWidth, maxHeight) {
            const ratio = Math.min(maxWidth / srcWidth, maxHeight / srcHeight);
            return {
                width: srcWidth * ratio,
                height: srcHeight * ratio
            };
        }

        function drawMockupWithDesign(context, designImage) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.drawImage(mockupImage, 0, 0, canvas.width, canvas.height);

            const dimensions = calculateAspectRatioFit(
                designImage.width,
                designImage.height,
                areaWidth,
                areaHeight
            );

            // Center horizontally but align to top of placement area
            const x = areaX + (areaWidth - dimensions.width) / 2;
            const y = areaY; // Remove vertical centering

            context.drawImage(designImage, x, y, dimensions.width, dimensions.height);
        }

        async function previewDesign() {
            if (!mockupImage || designs.length === 0) {
                alert('Please upload both mockup template and design files');
                return;
            }

            const design = designs[0];
            const designImage = await loadDesignImage(design);
            drawMockupWithDesign(previewCtx, designImage);
        }

        async function processAllDesigns() {
            if (!mockupImage || designs.length === 0) {
                alert('Please upload both mockup template and design files');
                return;
            }

            const zip = new JSZip();
            
            for (let i = 0; i < designs.length; i++) {
                updateProgress(i + 1, designs.length);
                
                const designImage = await loadDesignImage(designs[i]);
                drawMockupWithDesign(ctx, designImage);
                
                const mockupBlob = await new Promise(resolve => {
                    canvas.toBlob(resolve, 'image/png', 1.0); // Maximum quality
                });
                
                zip.file(`mockup_${designs[i].name}`, mockupBlob);
            }

            const zipBlob = await zip.generateAsync({type: 'blob'});
            const link = document.createElement('a');
            link.href = URL.createObjectURL(zipBlob);
            link.download = 'mockups.zip';
            link.click();
            
            statusText.textContent = 'All mockups generated and downloaded!';
        }

        function updateProgress(current, total) {
            const percentage = (current / total) * 100;
            progressFill.style.width = percentage + '%';
            statusText.textContent = `Processing: ${current} of ${total} designs`;
        }

        function loadDesignImage(file) {
            return new Promise((resolve) => {
                const reader = new FileReader();
                reader.onload = (event) => {
                    const img = new Image();
                    img.onload = () => resolve(img);
                    img.src = event.target.result;
                };
                reader.readAsDataURL(file);
            });
        }        


    </script>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
</body>
</html>