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
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415

class Item {
    constructor(name, length, width, weight) {
        this.name = name;
        this.length = parseFloat(length);
        this.width = parseFloat(width);
        this.weight = parseFloat(weight) || 0;
        this.area = this.length * this.width;
    }
}

class SpaceAllocator {
    constructor() {
        this.containerWidth = 600;
        this.containerHeight = 250;
        this.items = [];
        this.canvas = document.getElementById('space-canvas');
        this.ctx = this.canvas.getContext('2d');
        this.scale = 1;
        this.offsetX = 0;
        this.offsetY = 0;
        
        this.initElements();
        this.initEventListeners();
        this.resizeCanvas();
        this.updateUI();
    }
    initElements() {
        this.containerWidthInput = document.getElementById('container-width');
        this.containerHeightInput = document.getElementById('container-height');
        this.containerWeightInput = document.getElementById('container-weight');
this.itemNameInput = document.getElementById('item-name');
        this.itemLengthInput = document.getElementById('item-length');
        this.itemWidthInput = document.getElementById('item-width');
        this.itemWeightInput = document.getElementById('item-weight');
        this.itemQuantityInput = document.getElementById('item-quantity');
this.addItemBtn = document.getElementById('add-item-btn');
        this.removeItemBtn = document.getElementById('remove-item-btn');
        this.updateContainerBtn = document.getElementById('update-container-btn');
        this.clearAllBtn = document.getElementById('clear-all-btn');
        this.itemsTable = document.getElementById('items-table');
        this.spaceStats = document.getElementById('space-stats');
        this.visualizationContainer = document.getElementById('visualization-container');
    }
    
    initEventListeners() {
        // Set default container dimensions
        this.containerWidthInput.value = this.containerWidth;
        this.containerHeightInput.value = this.containerHeight;
        
        // Button events
        this.addItemBtn.addEventListener('click', () => this.addItem());
        this.removeItemBtn.addEventListener('click', () => this.removeSelectedItem());
        this.updateContainerBtn.addEventListener('click', () => this.updateContainer());
        this.clearAllBtn.addEventListener('click', () => this.clearAll());
        
        // Allow adding items with Enter key
        this.itemNameInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addItem();
        });
        this.itemLengthInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addItem();
        });
        this.itemWidthInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addItem();
        });
        this.itemWeightInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addItem();
        });
        this.itemQuantityInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.addItem();
        });
// Handle window resize
        window.addEventListener('resize', () => {
            this.resizeCanvas();
            this.drawContainer();
        });
        
        // Initialize visualization
        this.resizeCanvas();
        this.drawContainer();
    }
    
    resizeCanvas() {
        const container = this.visualizationContainer;
        this.canvas.width = container.clientWidth;
        this.canvas.height = container.clientHeight;
    }
    
    addItem() {
        const name = this.itemNameInput.value.trim() || `Item ${this.items.length + 1}`;
        const length = parseFloat(this.itemLengthInput.value);
        const width = parseFloat(this.itemWidthInput.value);
        const weight = parseFloat(this.itemWeightInput.value);
        const quantity = parseInt(this.itemQuantityInput.value) || 1;

        if (isNaN(length) || isNaN(width) || length <= 0 || width <= 0 || quantity <= 0) {
alert('Please enter valid positive numbers for length and width.');
            return;
        }
        for (let i = 0; i < quantity; i++) {
            const itemName = quantity > 1 ? `${name} #${i+1}` : name;
            const item = new Item(itemName, length, width, weight);
            this.items.push(item);
        }
// Clear inputs
        this.itemNameInput.value = '';
        this.itemLengthInput.value = '';
        this.itemWidthInput.value = '';
        this.itemWeightInput.value = '';
        this.itemQuantityInput.value = '1';
this.updateUI();
    }
    
    removeSelectedItem() {
        const selectedRow = this.itemsTable.querySelector('tr.selected');
        if (!selectedRow) {
            alert('Please select an item to remove.');
            return;
        }
        
        const itemName = selectedRow.getAttribute('data-name');
        this.items = this.items.filter(item => item.name !== itemName);
        this.updateUI();
    }
    
    updateContainer() {
        const width = parseFloat(this.containerWidthInput.value);
        const height = parseFloat(this.containerHeightInput.value);
        
        if (isNaN(width) || isNaN(height) || width <= 0 || height <= 0) {
            alert('Please enter valid positive numbers for container dimensions.');
            return;
        }
        
        this.containerWidth = width;
        this.containerHeight = height;
        this.updateUI();
    }
    
    clearAll() {
        if (confirm('Are you sure you want to clear all items?')) {
            this.items = [];
            this.updateUI();
        }
    }
    
    updateUI() {
        this.updateItemsTable();
        this.updateSpaceStats();
        this.drawContainer();
    }
    
    updateItemsTable() {
        this.itemsTable.innerHTML = '';
        
        this.items.forEach(item => {
            const row = document.createElement('tr');
            row.setAttribute('data-name', item.name);
            
            row.innerHTML = `
                <td class="p-2 border-b border-gray-600">${item.name}</td>
                <td class="p-2 border-b border-gray-600 text-center">${item.length.toFixed(1)} cm</td>
                <td class="p-2 border-b border-gray-600 text-center">${item.width.toFixed(1)} cm</td>
                <td class="p-2 border-b border-gray-600 text-center">${item.area.toFixed(1)} cm²</td>
                <td class="p-2 border-b border-gray-600 text-center">${item.weight.toFixed(1)} kg</td>
`;
            
            row.addEventListener('click', () => {
                this.itemsTable.querySelectorAll('tr').forEach(r => r.classList.remove('selected'));
                row.classList.add('selected');
            });
            
            this.itemsTable.appendChild(row);
        });
    }
    updateSpaceStats() {
        const totalArea = this.containerWidth * this.containerHeight;
        const usedArea = this.items.reduce((sum, item) => sum + item.area, 0);
        const freeArea = Math.max(0, totalArea - usedArea);
        const efficiency = totalArea > 0 ? (usedArea / totalArea * 100).toFixed(1) : 0;
        
        const containerWeight = parseFloat(this.containerWeightInput.value) || 7200;
        const usedWeight = this.items.reduce((sum, item) => sum + item.weight, 0);
        const freeWeight = Math.max(0, containerWeight - usedWeight);
        const weightEfficiency = containerWeight > 0 ? (usedWeight / containerWeight * 100).toFixed(1) : 0;
        
        this.spaceStats.innerHTML = `
            <div class="grid grid-cols-4 gap-2 text-center">
<div>
                    <div class="text-sm text-gray-400">Total</div>
                    <div class="font-bold">${totalArea.toFixed(1)} cm²</div>
                </div>
                <div>
                    <div class="text-sm text-gray-400">Used</div>
                    <div class="font-bold">${usedArea.toFixed(1)} cm²</div>
                </div>
                <div>
                    <div class="text-sm text-gray-400">Free</div>
                    <div class="font-bold">${freeArea.toFixed(1)} cm²</div>
                    <div>
                        <div class="text-sm text-gray-400">Max Weight</div>
                        <div class="font-bold">${containerWeight.toFixed(1)} kg</div>
                    </div>
                    <div>
                        <div class="text-sm text-gray-400">Used Weight</div>
                        <div class="font-bold">${usedWeight.toFixed(1)} kg</div>
                    </div>
                    <div>
                        <div class="text-sm text-gray-400">Free Weight</div>
                        <div class="font-bold ${freeWeight < 0 ? 'text-red-500' : ''}">${freeWeight.toFixed(1)} kg</div>
                    </div>
                </div>
            </div>
            <div class="mt-2">
                <div class="text-sm text-gray-400 mb-1">Weight Usage</div>
                <div class="w-full bg-gray-600 rounded-full h-2.5">
                    <div class="${usedWeight > containerWeight ? 'bg-red-600' : 'bg-green-600'} h-2.5 rounded-full" style="width: ${Math.min(100, weightEfficiency)}%"></div>
                </div>
                <div class="text-right text-sm mt-1">${weightEfficiency}%</div>
                <div class="mt-2">
<div class="text-sm text-gray-400 mb-1">Efficiency</div>
                <div class="w-full bg-gray-600 rounded-full h-2.5">
                    <div class="bg-blue-600 h-2.5 rounded-full" style="width: ${efficiency}%"></div>
                </div>
                <div class="text-right text-sm mt-1">${efficiency}%</div>
            </div>
        `;
    }
    
    drawContainer() {
        this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
        
        // Calculate scale and offsets to maintain aspect ratio
        this.scale = Math.min(
            this.canvas.width / this.containerWidth,
            this.canvas.height / this.containerHeight
        ) * 0.9; // 90% of available space
        
        this.offsetX = (this.canvas.width - this.containerWidth * this.scale) / 2;
        this.offsetY = (this.canvas.height - this.containerHeight * this.scale) / 2;
        
        // Draw container
        this.ctx.fillStyle = '#111827';
        this.ctx.strokeStyle = '#374151';
        this.ctx.lineWidth = 2;
        this.ctx.fillRect(
            this.offsetX, 
            this.offsetY, 
            this.containerWidth * this.scale, 
            this.containerHeight * this.scale
        );
        this.ctx.strokeRect(
            this.offsetX, 
            this.offsetY, 
            this.containerWidth * this.scale, 
            this.containerHeight * this.scale
        );
        
        // Draw grid
        this.ctx.strokeStyle = 'rgba(55, 65, 81, 0.5)';
        this.ctx.lineWidth = 1;
        
        const gridSize = 50; // cm
        const gridStep = gridSize * this.scale;
        
        for (let x = this.offsetX; x <= this.offsetX + this.containerWidth * this.scale; x += gridStep) {
            this.ctx.beginPath();
            this.ctx.moveTo(x, this.offsetY);
            this.ctx.lineTo(x, this.offsetY + this.containerHeight * this.scale);
            this.ctx.stroke();
        }
        
        for (let y = this.offsetY; y <= this.offsetY + this.containerHeight * this.scale; y += gridStep) {
            this.ctx.beginPath();
            this.ctx.moveTo(this.offsetX, y);
            this.ctx.lineTo(this.offsetX + this.containerWidth * this.scale, y);
            this.ctx.stroke();
        }
        
        // Draw items
        const colors = [
            '#3B82F6', '#10B981', '#F59E0B', '#EF4444', 
            '#8B5CF6', '#EC4899', '#14B8A6', '#F97316'
        ];
        
        const placements = this.gridPackItems();
        
        placements.forEach((placement, index) => {
            const item = placement.item;
            const fits = placement.fits;
            
            if (!fits) {
                // Draw overflow indicator
                this.ctx.fillStyle = 'rgba(239, 68, 68, 0.2)';
                this.ctx.strokeStyle = 'rgba(239, 68, 68, 0.5)';
                this.ctx.lineWidth = 1;
                this.ctx.fillRect(
                    this.offsetX + this.containerWidth * this.scale - 120,
                    this.offsetY + 20 + index * 25,
                    120,
                    20
                );
                this.ctx.strokeRect(
                    this.offsetX + this.containerWidth * this.scale - 120,
                    this.offsetY + 20 + index * 25,
                    120,
                    20
                );
                
                this.ctx.fillStyle = '#fff';
                this.ctx.font = '10px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText(
                    `Overflow: ${item.name}`,
                    this.offsetX + this.containerWidth * this.scale - 60,
                    this.offsetY + 34 + index * 25
                );
                return;
            }
            
            const color = colors[index % colors.length];
            const x = this.offsetX + placement.x_cm * this.scale;
            const y = this.offsetY + placement.y_cm * this.scale;
            const width = placement.w_cm * this.scale;
            const height = placement.h_cm * this.scale;
            
            // Draw item rectangle
            this.ctx.fillStyle = color;
            this.ctx.strokeStyle = '#1F2937';
            this.ctx.lineWidth = 1;
            this.ctx.fillRect(x, y, width, height);
            this.ctx.strokeRect(x, y, width, height);
            
            // Draw item label
            this.ctx.fillStyle = '#fff';
            this.ctx.font = 'bold 10px Arial';
            this.ctx.textAlign = 'left';
            this.ctx.fillText(
                `${item.name} (${item.length.toFixed(0)}×${item.width.toFixed(0)})`,
                x + 5,
                y + 15
            );
        });
    }
    
    gridPackItems(cellSize = 5) {
        const cols = Math.max(1, Math.floor(this.containerWidth / cellSize));
        const rows = Math.max(1, Math.floor(this.containerHeight / cellSize));
        const grid = Array(rows).fill().map(() => Array(cols).fill(false));
        
        const findSpace = (wCells, hCells) => {
            for (let r = 0; r <= rows - hCells; r++) {
                for (let c = 0; c <= cols - wCells; c++) {
                    let spaceAvailable = true;
                    for (let dr = 0; dr < hCells; dr++) {
                        for (let dc = 0; dc < wCells; dc++) {
                            if (grid[r + dr][c + dc]) {
                                spaceAvailable = false;
                                break;
                            }
                        }
                        if (!spaceAvailable) break;
                    }
                    if (spaceAvailable) return { r, c };
                }
            }
            return null;
        };
        
        const placements = [];
        const sortedItems = [...this.items].sort((a, b) => b.area - a.area);
        
        for (const item of sortedItems) {
            const wCells = Math.max(1, Math.floor(item.length / cellSize));
            const hCells = Math.max(1, Math.floor(item.width / cellSize));
            const pos = findSpace(wCells, hCells);
            
            if (!pos) {
                placements.push({
                    item,
                    x_cm: null,
                    y_cm: null,
                    w_cm: item.length,
                    h_cm: item.width,
                    fits: false
                });
                continue;
            }
            
            const { r, c } = pos;
            for (let dr = 0; dr < hCells; dr++) {
                for (let dc = 0; dc < wCells; dc++) {
                    grid[r + dr][c + dc] = true;
                }
            }
            
            placements.push({
                item,
                x_cm: c * cellSize,
                y_cm: r * cellSize,
                w_cm: item.length,
                h_cm: item.width,
                fits: true
            });
        }
        
        return placements;
    }
}

// Initialize the app when DOM is loaded
document.addEventListener('DOMContentLoaded', () => {
    new SpaceAllocator();
});