cookcli 0.30.0

A command-line interface for managing and working with Cooklang recipes
Documentation
1
2
3
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
{% extends "base.html" %}

{% block content %}
<div class="px-4 sm:px-8 lg:px-12 xl:px-16">
    <div id="pantry-error-banner" class="hidden mb-4 bg-red-50 border border-red-200 rounded-xl p-4">
        <div class="flex items-start gap-3">
            <div class="flex-shrink-0 text-red-500">
                <svg class="w-5 h-5 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L4.082 16.5c-.77.833.192 2.5 1.732 2.5z"></path>
                </svg>
            </div>
            <p id="pantry-error-message" class="flex-1 text-red-700 text-sm font-mono whitespace-pre-wrap"></p>
            <button onclick="document.getElementById('pantry-error-banner').classList.add('hidden')" class="text-red-400 hover:text-red-600">
                <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                </svg>
            </button>
        </div>
    </div>
    <div class="mt-8 mb-6">
        <div class="flex items-center justify-between">
            <h1 class="text-3xl font-bold text-gray-800">{{ tr.t("pantry-title") }}</h1>

            {% if !sections.is_empty() %}
            <div class="flex items-center gap-4">
                <span id="out-of-stock-count" class="text-sm text-gray-500 dark:text-gray-400"></span>
                <label class="flex items-center cursor-pointer group">
                    <input type="checkbox" id="filter-out-of-stock" class="mr-2 w-4 h-4 text-orange-600 rounded focus:ring-orange-500 focus:ring-2">
                    <span class="text-sm text-gray-600 group-hover:text-gray-800 dark:text-gray-400 dark:group-hover:text-gray-200">{{ tr.t("pantry-show-out-of-stock") }}</span>
                </label>
            </div>
            {% endif %}
        </div>
    </div>

    {% if !configured %}
    <div class="recipe-card">
        <div class="p-8 text-center">
            <svg class="mx-auto h-12 w-12 text-gray-400 mb-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" />
            </svg>
            <h3 class="text-lg font-medium text-gray-900 mb-2">{{ tr.t("pantry-no-config") }}</h3>
            <p class="text-gray-500">{{ tr.t("pantry-create-config") }}</p>
            <a href="{{ prefix }}/preferences" class="mt-4 inline-block text-orange-600 hover:text-orange-700">
                {{ tr.t("pantry-configure") }}
            </a>
        </div>
    </div>
    {% else %}
    <div class="space-y-6">
        {% for section in sections %}
        <div class="recipe-card">
            <div class="p-6">
                <h2 class="text-xl font-semibold text-gray-800 mb-4 capitalize">{{ section.name }}</h2>
                
                {% if section.items.is_empty() %}
                <p class="text-gray-500 italic">{{ tr.t("pantry-no-items-section") }}</p>
                {% else %}
                <div class="grid gap-3 md:grid-cols-2 lg:grid-cols-3">
                    {% for item in section.items %}
                    <div class="pantry-item p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-all duration-200 group"
                         data-section="{{ section.name }}"
                         data-name="{{ item.name }}"
                         data-quantity="{% if let Some(quantity) = item.quantity %}{{ quantity }}{% endif %}"
                         data-low="{% if let Some(low) = item.low %}{{ low }}{% endif %}">
                        <!-- Main content with aligned name and attributes -->
                        <div class="flex items-start justify-between">
                            <div class="flex-grow">
                                <!-- Name aligned with attributes -->
                                <h3 class="font-medium text-gray-900 mb-2">{{ item.name }}</h3>

                                <!-- Attributes section -->
                                <div class="item-display">
                                    <div class="space-y-1 text-sm">
                                        <div class="quantity-display flex items-center text-gray-600">
                                            <span class="text-gray-500 mr-2">{{ tr.t("pantry-item-quantity-short") }}</span>
                                            <span class="item-quantity font-medium">{% if let Some(quantity) = item.quantity %}{{ quantity }}{% else %}-{% endif %}</span>
                                            <svg class="out-of-stock-icon w-4 h-4 ml-1 text-red-500 hidden" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"></path>
                                            </svg>
                                        </div>
                                        <div class="flex items-center text-gray-600">
                                            <span class="text-gray-500 mr-2">{{ tr.t("pantry-item-bought") }}</span>
                                            <span class="item-bought">{% if let Some(bought) = item.bought %}{{ bought }}{% else %}-{% endif %}</span>
                                        </div>
                                        <div class="flex items-center text-gray-600">
                                            <span class="text-gray-500 mr-2">{{ tr.t("pantry-item-expire") }}</span>
                                            <span class="item-expire">{% if let Some(expire) = item.expire %}{{ expire }}{% else %}-{% endif %}</span>
                                        </div>
                                        <div class="flex items-center text-gray-600">
                                            <span class="text-gray-500 mr-2">{{ tr.t("pantry-item-low") }}</span>
                                            <span class="item-low">{% if let Some(low) = item.low %}{{ low }}{% else %}-{% endif %}</span>
                                        </div>
                                    </div>
                                </div>

                                <!-- Edit form (hidden by default) -->
                                <div class="item-edit hidden">
                                    <div class="space-y-2">
                                        <input type="text" class="edit-quantity w-full px-2 py-1 text-sm border rounded"
                                               placeholder="Quantity (e.g., 500%g)"
                                               value="{% if let Some(quantity) = item.quantity %}{{ quantity }}{% endif %}">
                                        <input type="text" class="edit-bought w-full px-2 py-1 text-sm border rounded"
                                               placeholder="Bought (DD.MM.YYYY)"
                                               value="{% if let Some(bought) = item.bought %}{{ bought }}{% endif %}">
                                        <input type="text" class="edit-expire w-full px-2 py-1 text-sm border rounded"
                                               placeholder="Expires (DD.MM.YYYY)"
                                               value="{% if let Some(expire) = item.expire %}{{ expire }}{% endif %}">
                                        <input type="text" class="edit-low w-full px-2 py-1 text-sm border rounded"
                                               placeholder="Low threshold (e.g., 100%g)"
                                               value="{% if let Some(low) = item.low %}{{ low }}{% endif %}">
                                        <div class="flex items-center justify-end space-x-2 mt-2">
                                            <button class="save-btn px-3 py-1.5 text-xs bg-green-600 text-white rounded hover:bg-green-700 font-medium">{{ tr.t("pantry-save") }}</button>
                                            <button class="cancel-btn px-3 py-1.5 text-xs bg-gray-400 text-white rounded hover:bg-gray-500 font-medium">{{ tr.t("pantry-cancel") }}</button>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Action buttons and status indicator -->
                            <div class="flex items-start space-x-2 ml-4">
                                <div class="item-status-dot w-2 h-2 bg-green-500 rounded-full mt-1 flex-shrink-0"></div>
                                <div class="flex items-center space-x-1 opacity-0 group-hover:opacity-100 transition-opacity">
                                    <button class="edit-btn p-1 text-blue-500 hover:text-blue-700 hover:bg-blue-50 rounded"
                                            title="{{ tr.t("pantry-edit-item") }}">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"></path>
                                        </svg>
                                    </button>
                                    <button class="delete-btn p-1 text-red-500 hover:text-red-700 hover:bg-red-50 rounded"
                                            title="{{ tr.t("pantry-remove-item") }}">
                                        <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
                                        </svg>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
                {% endif %}
            </div>
        </div>
        {% endfor %}
    </div>
    
    <div class="mt-8 flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4">
        <div class="text-sm text-gray-500">
            {{ tr.t("pantry-total-sections") }} {{ sections.len() }}
        </div>
        <div class="flex flex-wrap gap-2">
            <button id="add-item-btn" class="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700 transition-colors">
                {{ tr.t("pantry-add-item") }}
            </button>
            <a href="{{ prefix }}/preferences" class="px-4 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition-colors inline-block">
                {{ tr.t("pantry-edit-config") }}
            </a>
        </div>
    </div>
    {% endif %}
</div>

<!-- Add Item Modal -->
<div id="add-modal" class="fixed inset-0 bg-black bg-opacity-50 hidden items-center justify-center z-50">
    <div class="bg-white dark:bg-gray-800 rounded-lg p-6 w-full max-w-md mx-4">
        <h2 class="text-xl font-bold mb-4">{{ tr.t("pantry-add-pantry-item") }}</h2>
        <form id="add-form">
            <div class="mb-4">
                <label class="block text-sm font-medium mb-2">{{ tr.t("pantry-section-label") }}</label>
                <select id="add-section" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" required>
                    <option value="">{{ tr.t("pantry-section-select") }}</option>
                    {% if sections.is_empty() %}
                    <option value="freezer">{{ tr.t("pantry-section-freezer") }}</option>
                    <option value="fridge">{{ tr.t("pantry-section-fridge") }}</option>
                    <option value="pantry">{{ tr.t("pantry-section-pantry") }}</option>
                    <option value="spices">{{ tr.t("pantry-section-spices") }}</option>
                    <option value="other">{{ tr.t("pantry-section-other") }}</option>
                    {% else %}
                    {% for section in sections %}
                    <option value="{{ section.name }}">{{ section.name }}</option>
                    {% endfor %}
                    {% endif %}
                </select>
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium mb-2">{{ tr.t("pantry-item-name") }}</label>
                <input type="text" id="add-name" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" required>
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium mb-2">{{ tr.t("pantry-item-quantity") }} ({{ tr.t("pantry-optional") }})</label>
                <input type="text" id="add-quantity" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" placeholder="e.g., 500%g or 2%L">
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium mb-2">{{ tr.t("pantry-item-bought-date") }} ({{ tr.t("pantry-optional") }})</label>
                <input type="text" id="add-bought" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" placeholder="DD.MM.YYYY">
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium mb-2">{{ tr.t("pantry-item-expire-date") }} ({{ tr.t("pantry-optional") }})</label>
                <input type="text" id="add-expire" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" placeholder="DD.MM.YYYY">
            </div>
            <div class="mb-4">
                <label class="block text-sm font-medium mb-2">{{ tr.t("pantry-item-low-threshold") }} ({{ tr.t("pantry-optional") }})</label>
                <input type="text" id="add-low" class="w-full px-3 py-2 border rounded-lg dark:bg-gray-700 dark:border-gray-600" placeholder="e.g., 100%g or 2">
            </div>
            <div class="flex justify-end space-x-3">
                <button type="button" onclick="closeAddModal()" class="px-4 py-2 border rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700">{{ tr.t("pantry-cancel") }}</button>
                <button type="submit" class="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700">{{ tr.t("pantry-save") }}</button>
            </div>
        </form>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    // Define all functions first
    function updateOutOfStockCount() {
        const totalItems = document.querySelectorAll('.pantry-item').length;
        const outOfStockItems = document.querySelectorAll('.pantry-item.out-of-stock').length;
        const outOfStockCountSpan = document.getElementById('out-of-stock-count');
        if (outOfStockCountSpan) {
            outOfStockCountSpan.textContent = `(${outOfStockItems} out of stock / ${totalItems} total)`;
        }
    }

    function applyFilter() {
        const filterCheckbox = document.getElementById('filter-out-of-stock');
        const showOnlyOutOfStock = filterCheckbox && filterCheckbox.checked;
        const sections = document.querySelectorAll('.recipe-card');

        sections.forEach(section => {
            const items = section.querySelectorAll('.pantry-item');
            let visibleItems = 0;

            items.forEach(item => {
                if (showOnlyOutOfStock && !item.classList.contains('out-of-stock')) {
                    item.style.display = 'none';
                } else {
                    item.style.display = '';
                    visibleItems++;
                }
            });

            // Hide entire section if no items are visible
            const sectionContainer = section.querySelector('.grid');
            const emptyMessage = section.querySelector('.empty-section-message');

            if (sectionContainer) {
                if (visibleItems === 0 && showOnlyOutOfStock) {
                    // Hide the grid and show empty message
                    sectionContainer.style.display = 'none';
                    if (!emptyMessage) {
                        const message = document.createElement('p');
                        message.className = 'empty-section-message text-gray-500 italic';
                        message.textContent = {{ tr.t("pantry-no-out-of-stock")|json|safe }};
                        sectionContainer.parentNode.appendChild(message);
                    }
                } else {
                    // Show the grid and hide empty message
                    sectionContainer.style.display = '';
                    if (emptyMessage) {
                        emptyMessage.remove();
                    }
                }
            }
        });
    }

    // Parse quantity to extract numeric value and unit
    function parseQuantity(quantity) {
        if (!quantity) return null;
        const cleaned = quantity.replace('%', ' ').trim();
        const match = cleaned.match(/^(\d+(?:\.\d+)?)\s*(.*)$/);
        if (match) {
            return {
                value: parseFloat(match[1]),
                unit: match[2] || ''
            };
        }
        return null;
    }

    // Check for out-of-stock and low-stock items and apply styling
    function checkOutOfStock() {
        const items = document.querySelectorAll('.pantry-item');

        items.forEach(item => {
            const quantity = item.dataset.quantity || '';
            const lowThreshold = item.dataset.low || '';
            const isOutOfStock = quantity === '0' || quantity === '0%g' || quantity === '0%kg' ||
                                quantity === '0%ml' || quantity === '0%L' || quantity === '';

            // Check if low on stock
            let isLowStock = false;
            if (quantity && lowThreshold) {
                const currentQty = parseQuantity(quantity);
                const lowQty = parseQuantity(lowThreshold);
                if (currentQty && lowQty && currentQty.unit === lowQty.unit) {
                    isLowStock = currentQty.value <= lowQty.value;
                }
            }

            // Reset all styling first
            item.classList.remove('out-of-stock', 'low-stock', 'bg-gray-50', 'bg-red-50', 'bg-orange-50',
                                 'border', 'border-2', 'border-red-200', 'border-orange-400');

            const statusDot = item.querySelector('.item-status-dot');
            if (statusDot) {
                statusDot.classList.remove('in-stock', 'out-of-stock', 'low-stock', 'animate-pulse',
                                          'bg-green-500', 'bg-red-500', 'bg-orange-500');
            }

            const qtyDisplay = item.querySelector('.quantity-display');
            if (qtyDisplay) {
                qtyDisplay.classList.remove('font-semibold', 'text-gray-600', 'text-red-600', 'text-orange-600');
            }

            const warningIcon = item.querySelector('.out-of-stock-icon');
            if (warningIcon) {
                warningIcon.classList.add('hidden');
                warningIcon.classList.remove('text-red-500', 'text-orange-500');
            }

            // Apply appropriate styling based on stock status
            if (isOutOfStock) {
                // Apply out-of-stock styling
                item.classList.add('out-of-stock', 'bg-red-50', 'border', 'border-red-200');

                if (statusDot) {
                    statusDot.classList.add('out-of-stock', 'bg-red-500', 'animate-pulse');
                }

                if (qtyDisplay) {
                    qtyDisplay.classList.add('font-semibold', 'text-red-600');
                }

                if (warningIcon) {
                    warningIcon.classList.remove('hidden');
                    warningIcon.classList.add('text-red-500');
                }
            } else if (isLowStock) {
                // Apply low-stock styling with orange frame
                item.classList.add('low-stock', 'bg-orange-50', 'border-2', 'border-orange-400');

                if (statusDot) {
                    statusDot.classList.add('low-stock', 'bg-orange-500', 'animate-pulse');
                }

                if (qtyDisplay) {
                    qtyDisplay.classList.add('font-semibold', 'text-orange-600');
                }

                if (warningIcon) {
                    warningIcon.classList.remove('hidden');
                    warningIcon.classList.add('text-orange-500');
                }
            } else {
                // Apply in-stock styling
                item.classList.add('bg-gray-50');

                if (statusDot) {
                    statusDot.classList.add('in-stock', 'bg-green-500');
                }

                if (qtyDisplay) {
                    qtyDisplay.classList.add('text-gray-600');
                }
            }
        });

        // Update count after checking stock status
        updateOutOfStockCount();
    }

    // Initialize: Run check on page load
    checkOutOfStock();

    // Add filter event listener
    const filterCheckbox = document.getElementById('filter-out-of-stock');
    if (filterCheckbox) {
        filterCheckbox.addEventListener('change', applyFilter);
    }
    
    const addBtn = document.getElementById('add-item-btn');
    const addModal = document.getElementById('add-modal');
    const addForm = document.getElementById('add-form');
    
    if (addBtn) {
        addBtn.addEventListener('click', function() {
            addModal.classList.remove('hidden');
            addModal.classList.add('flex');
        });
    }
    
    if (addForm) {
        addForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const data = {
                section: document.getElementById('add-section').value,
                name: document.getElementById('add-name').value,
                quantity: document.getElementById('add-quantity').value || null,
                bought: document.getElementById('add-bought').value || null,
                expire: document.getElementById('add-expire').value || null,
                low: document.getElementById('add-low').value || null
            };
            
            try {
                const response = await fetch('{{ prefix }}/api/pantry/add', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });
                
                if (response.ok) {
                    window.location.reload();
                } else {
                    const data = await response.json().catch(() => ({}));
                    showPantryError(data.error || {{ tr.t("pantry-failed-add")|json|safe }});
                }
            } catch (error) {
                showPantryError('Error adding item: ' + error);
            }
        });
    }
    
    // Add inline editing and delete functionality to items
    document.querySelectorAll('.pantry-item').forEach(item => {
        const section = item.dataset.section;
        const name = item.dataset.name;
        const editBtn = item.querySelector('.edit-btn');
        const deleteBtn = item.querySelector('.delete-btn');
        const saveBtn = item.querySelector('.save-btn');
        const cancelBtn = item.querySelector('.cancel-btn');
        const displayDiv = item.querySelector('.item-display');
        const editDiv = item.querySelector('.item-edit');
        
        // Edit button handler
        if (editBtn) {
            editBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                displayDiv.classList.add('hidden');
                editDiv.classList.remove('hidden');
            });
        }
        
        // Cancel button handler
        if (cancelBtn) {
            cancelBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                displayDiv.classList.remove('hidden');
                editDiv.classList.add('hidden');
            });
        }
        
        // Save function that can be called from button click or Enter key
        async function saveItem(e) {
            if (e) e.stopPropagation();

            const quantityInput = item.querySelector('.edit-quantity');
            const boughtInput = item.querySelector('.edit-bought');
            const expireInput = item.querySelector('.edit-expire');
            const lowInput = item.querySelector('.edit-low');

            // Get original values from display
            const originalQuantity = item.querySelector('.item-quantity').textContent;
            const originalBought = item.querySelector('.item-bought').textContent;
            const originalExpire = item.querySelector('.item-expire').textContent;
            const originalLow = item.querySelector('.item-low').textContent;

            // Only include fields that have changed
            const data = {};

            const newQuantity = quantityInput.value.trim();
            const displayQuantity = originalQuantity === '-' ? '' : originalQuantity;
            if (newQuantity !== displayQuantity) {
                data.quantity = newQuantity || null;
            }

            const newBought = boughtInput.value.trim();
            const displayBought = originalBought === '-' ? '' : originalBought;
            if (newBought !== displayBought) {
                data.bought = newBought || null;
            }

            const newExpire = expireInput.value.trim();
            const displayExpire = originalExpire === '-' ? '' : originalExpire;
            if (newExpire !== displayExpire) {
                data.expire = newExpire || null;
            }

            const newLow = lowInput.value.trim();
            const displayLow = originalLow === '-' ? '' : originalLow;
            if (newLow !== displayLow) {
                data.low = newLow || null;
            }

            try {
                const response = await fetch(`{{ prefix }}/api/pantry/${section}/${encodeURIComponent(name)}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(data)
                });

                if (response.ok) {
                    // Update display with new values, preserving unchanged fields
                    if (data.hasOwnProperty('quantity')) {
                        item.querySelector('.item-quantity').textContent = data.quantity || '-';
                        item.dataset.quantity = data.quantity || '';
                    }
                    if (data.hasOwnProperty('bought')) {
                        item.querySelector('.item-bought').textContent = data.bought || '-';
                    }
                    if (data.hasOwnProperty('expire')) {
                        item.querySelector('.item-expire').textContent = data.expire || '-';
                    }
                    if (data.hasOwnProperty('low')) {
                        item.querySelector('.item-low').textContent = data.low || '-';
                        item.dataset.low = data.low || '';
                    }

                    displayDiv.classList.remove('hidden');
                    editDiv.classList.add('hidden');

                    // Re-check out-of-stock status after update
                    checkOutOfStock();
                } else {
                    const data = await response.json().catch(() => ({}));
                    showPantryError(data.error || {{ tr.t("pantry-failed-update")|json|safe }});
                }
            } catch (error) {
                showPantryError('Error updating item: ' + error);
            }
        }

        // Save button handler
        if (saveBtn) {
            saveBtn.addEventListener('click', saveItem);
        }

        // Add Enter key support for all edit inputs
        const editInputs = item.querySelectorAll('.edit-quantity, .edit-bought, .edit-expire, .edit-low');
        editInputs.forEach(input => {
            input.addEventListener('keydown', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    saveItem(e);
                } else if (e.key === 'Escape') {
                    e.preventDefault();
                    displayDiv.classList.remove('hidden');
                    editDiv.classList.add('hidden');
                }
            });
        });
        
        // Delete button handler
        if (deleteBtn) {
            deleteBtn.addEventListener('click', async function(e) {
                e.stopPropagation();

                if (confirm({{ tr.t("pantry-confirm-remove-template")|json|safe }}.replace('%s', name).replace('%s', section))) {
                    try {
                        const response = await fetch(`{{ prefix }}/api/pantry/${section}/${encodeURIComponent(name)}`, {
                            method: 'DELETE'
                        });

                        if (response.ok) {
                            // Smoothly remove the item
                            item.style.opacity = '0';
                            item.style.transform = 'scale(0.95)';
                            setTimeout(() => {
                                item.remove();
                                // Check if section is now empty and reload if needed
                                const sectionContainer = document.querySelector(`[data-section="${section}"]`);
                                if (sectionContainer && !document.querySelector(`.pantry-item[data-section="${section}"]`)) {
                                    window.location.reload();
                                }
                            }, 200);
                        } else {
                            const data = await response.json().catch(() => ({}));
                            showPantryError(data.error || {{ tr.t("pantry-failed-remove")|json|safe }});
                        }
                    } catch (error) {
                        showPantryError('Error removing item: ' + error);
                    }
                }
            });
        }
    });
});

function closeAddModal() {
    const addModal = document.getElementById('add-modal');
    addModal.classList.add('hidden');
    addModal.classList.remove('flex');
    document.getElementById('add-form').reset();
}

function showPantryError(message) {
    const banner = document.getElementById('pantry-error-banner');
    document.getElementById('pantry-error-message').textContent = message;
    banner.classList.remove('hidden');
    banner.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
</script>
{% endblock %}