-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
678 lines (604 loc) · 31.1 KB
/
script.js
File metadata and controls
678 lines (604 loc) · 31.1 KB
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
document.addEventListener('DOMContentLoaded', () => {
// ── DOM refs ─────────────────────────────────────────────────────────────
const webcam = document.getElementById('webcam');
const captureCanvas = document.getElementById('capture-canvas');
const scanBtn = document.getElementById('scan-btn');
const lastItemInfo = document.getElementById('last-item-info');
const cartItemsContainer = document.getElementById('cart-items');
const emptyCartMsg = document.getElementById('empty-cart');
const itemCountSpan = document.getElementById('item-count');
const totalPriceSpan = document.getElementById('total-price');
const checkoutBtn = document.getElementById('checkout-btn');
const clearBtn = document.getElementById('clear-btn');
const uploadBtn = document.getElementById('upload-btn');
const fileInput = document.getElementById('file-input');
const detectionStatus = document.getElementById('detection-status');
const statusText = document.getElementById('status-text');
const notificationContainer = document.getElementById('notification-container');
// Similar-products modal
const similarModal = document.getElementById('similar-modal');
const similarGrid = document.getElementById('similar-products-grid');
const similarCloseBtn = document.getElementById('similar-close-btn');
const addNewFromSimilarBtn = document.getElementById('add-new-from-similar');
// Add-product modal
const addModal = document.getElementById('add-modal');
const addCloseBtn = document.getElementById('add-close-btn');
const addProductForm = document.getElementById('add-product-form');
const newImagesInput = document.getElementById('new-images-input');
const uploadZone = document.getElementById('upload-zone');
const imagePreviewStrip = document.getElementById('image-preview-strip');
const saveBtn = document.getElementById('save-btn');
const saveLoader = document.getElementById('save-loader');
const captureProductBtn = document.getElementById('capture-product-btn');
const modalCameraPreview = document.getElementById('modal-camera-preview');
// ── State ─────────────────────────────────────────────────────────────────
let cart = [];
let isAnalyzing = false;
let lastCapturedBlob = null; // most recent scan blob, pre-populates add-product form
let lastMatchedItem = null; // last item Gemma matched, used for wrong-product correction
let catalogProducts = []; // products.json items, fetched once on load
let capturedProductBlobs = []; // camera captures taken inside the add-product modal
let pendingUploadFiles = []; // files picked via file-input (copied so we can remove individually)
let useScanCapture = false; // whether the original scan blob is still included
async function loadCatalog() {
try {
const res = await fetch('/api/catalog');
catalogProducts = (await res.json()).products || [];
} catch(e) { console.error('Failed to load catalog:', e); }
}
loadCatalog();
// ── Webcam ───────────────────────────────────────────────────────────────
async function initWebcam() {
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: { ideal: 1280 }, height: { ideal: 720 } }
});
webcam.srcObject = stream;
} catch (err) {
console.error('Camera error:', err);
showNotification('Could not access camera. Check permissions.', 'error');
}
}
initWebcam();
// ── Scan ─────────────────────────────────────────────────────────────────
scanBtn.addEventListener('click', async () => {
if (isAnalyzing) return;
setLoading(true);
detectionStatus.classList.remove('hidden');
statusText.textContent = 'Identifying...';
const MAX = 256;
let w = webcam.videoWidth, h = webcam.videoHeight;
if (w > h) { if (w > MAX) { h = Math.round(h * MAX / w); w = MAX; } }
else { if (h > MAX) { w = Math.round(w * MAX / h); h = MAX; } }
const ctx = captureCanvas.getContext('2d');
captureCanvas.width = w;
captureCanvas.height = h;
ctx.drawImage(webcam, 0, 0, w, h);
const blob = await new Promise(r => captureCanvas.toBlob(r, 'image/jpeg', 0.8));
lastCapturedBlob = blob;
const fd = new FormData();
fd.append('file', blob, 'capture.jpg');
try {
const res = await fetch('/api/inference', { method: 'POST', body: fd });
if (!res.ok) throw new Error('Scan failed');
const data = await res.json();
if (data.success && data.has_conflict) {
handleConflict(data.data, data.vector_results || []);
} else if (data.success && data.data.id !== 'unknown') {
handleMatch(data.data);
} else {
handleNoMatch(data.data.description || 'Item not found in catalog.', data.vector_results || []);
}
} catch (err) {
console.error(err);
showNotification('Error connecting to server.', 'error');
} finally {
setLoading(false);
detectionStatus.classList.add('hidden');
}
});
// ── Upload ───────────────────────────────────────────────────────────────
uploadBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', async (e) => {
const file = e.target.files[0];
if (!file) return;
lastCapturedBlob = file;
setLoading(true);
detectionStatus.classList.remove('hidden');
statusText.textContent = 'Analyzing image...';
const fd = new FormData();
fd.append('file', file);
try {
const res = await fetch('/api/inference', { method: 'POST', body: fd });
const data = await res.json();
if (data.success && data.has_conflict) {
handleConflict(data.data, data.vector_results || []);
} else if (data.success && data.data.id !== 'unknown') {
handleMatch(data.data);
} else {
handleNoMatch(data.data.description || 'Item not found in catalog.', data.vector_results || []);
}
} catch (err) {
showNotification('Error scanning uploaded file.', 'error');
} finally {
setLoading(false);
detectionStatus.classList.add('hidden');
fileInput.value = '';
}
});
// ── Result handlers ───────────────────────────────────────────────────────
function handleMatch(item) {
lastMatchedItem = item;
lastItemInfo.innerHTML = `
<div class="product-result">
<div class="product-main-info">
<div class="product-name">${item.name}</div>
<div class="product-meta">
<span class="sku-tag">${item.id}</span>
<span class="category-tag">${item.category}</span>
<span class="brand-tag">Brand: ${item.brand}</span>
<span class="unit-tag">Unit: ${item.unit}</span>
</div>
<button class="btn-wrong-product" id="wrong-product-btn">✏ Not this product?</button>
</div>
<div class="product-price-info">
<span class="price-label">Price</span>
<span class="price-value">₹${item.price.toFixed(2)}</span>
</div>
</div>`;
document.getElementById('wrong-product-btn').addEventListener('click', () => handleWrongProduct(item));
addToCart(item);
showNotification(`Added ${item.name} to bill`);
}
function handleNoMatch(description, vectorResults) {
const hasMatches = vectorResults && vectorResults.length > 0;
lastItemInfo.innerHTML = `
<div class="no-match">
<p><strong>Unrecognized Item</strong></p>
<p class="placeholder-text">${description}</p>
<span class="vector-hint" id="open-modal-hint">
${hasMatches
? `🔍 ${vectorResults.length} similar product(s) found — click to view`
: '➕ Item not in catalog — click to add it'}
</span>
</div>`;
document.getElementById('open-modal-hint').addEventListener('click', () => {
if (hasMatches) showSimilarModal(vectorResults);
else showAddModal();
});
if (hasMatches) {
showSimilarModal(vectorResults);
showNotification(`Found ${vectorResults.length} similar product(s)`, 'warning');
} else {
showAddModal();
showNotification('Item not recognized — add it to your catalog', 'error');
}
}
// ── Conflict handler (Gemma vs SigLIP disagree) ───────────────────────────
function handleConflict(gemmaResult, vectorResults) {
lastItemInfo.innerHTML = `
<div class="no-match">
<p><strong style="color:#f59e0b">⚠ AI Conflict Detected</strong></p>
<p class="placeholder-text">Gemma identified <strong>${gemmaResult.name}</strong> but the visual search disagrees. Please confirm below.</p>
</div>`;
showNotification('Gemma and visual search disagree — please confirm the product', 'warning');
showSimilarModal(
vectorResults,
[],
'AI Disagrees — Please Confirm',
'Gemma identified one product; visual search found another. Pick the correct one.',
gemmaResult
);
}
// ── Cart ──────────────────────────────────────────────────────────────────
function addToCart(item) {
const existing = cart.find(i => i.id === item.id);
if (existing) {
existing.quantity += 1;
} else {
cart.push({ id: item.id, name: item.name, price: item.price, unit: item.unit || 'N/A', quantity: 1 });
}
renderCart();
}
function renderCart() {
if (cart.length === 0) {
emptyCartMsg.classList.remove('hidden');
cartItemsContainer.querySelectorAll('.cart-item').forEach(el => el.remove());
checkoutBtn.disabled = true;
totalPriceSpan.textContent = '₹0.00';
itemCountSpan.textContent = '0 items';
return;
}
emptyCartMsg.classList.add('hidden');
cartItemsContainer.querySelectorAll('.cart-item').forEach(el => el.remove());
let total = 0, totalQty = 0;
cart.forEach(item => {
const itemTotal = item.price * item.quantity;
total += itemTotal;
totalQty += item.quantity;
const el = document.createElement('div');
el.className = 'cart-item';
el.innerHTML = `
<div class="item-info">
<span class="item-name">${item.name} <small>(${item.unit})</small></span>
<div class="item-details">
<span class="item-sku">${item.id}</span>
<span class="item-qty">Qty: ${item.quantity}</span>
</div>
</div>
<div class="item-price">₹${itemTotal.toFixed(2)}</div>`;
cartItemsContainer.appendChild(el);
});
totalPriceSpan.textContent = `₹${total.toFixed(2)}`;
itemCountSpan.textContent = `${totalQty} item${totalQty !== 1 ? 's' : ''}`;
checkoutBtn.disabled = false;
}
clearBtn.addEventListener('click', () => {
cart = [];
renderCart();
lastItemInfo.innerHTML = '<p class="placeholder-text">Scan an item to see details</p>';
showNotification('Cart cleared');
});
checkoutBtn.addEventListener('click', () => {
const total = cart.reduce((s, i) => s + i.price * i.quantity, 0);
const qty = cart.reduce((s, i) => s + i.quantity, 0);
alert(`Bill Generated!\nTotal Items: ${qty}\nTotal Amount: ₹${total.toFixed(2)}`);
cart = [];
renderCart();
});
// ── Similar Products Modal ────────────────────────────────────────────────
function showSimilarModal(
vectorResults,
catalogItems = [],
title = 'Similar Products Found',
subtitle = "The AI couldn't match this item exactly. Pick one or add it as new.",
gemmaResult = null
) {
document.getElementById('similar-modal-title').textContent = title;
document.getElementById('similar-modal-subtitle').textContent = subtitle;
let html = '';
// Gemma's identified product shown first with amber conflict styling
if (gemmaResult) {
html += `<div class="modal-section-label gemma-label">🤖 Gemma identified this</div>
<div class="similar-grid">${renderGemmaConflictCard(gemmaResult)}</div>`;
}
if (vectorResults.length > 0) {
const lbl = gemmaResult ? 'Visual search found instead' : 'Visual matches from your custom catalog';
html += `<div class="modal-section-label">${lbl}</div>
<div class="similar-grid">${vectorResults.map(renderVectorCard).join('')}</div>`;
}
if (catalogItems.length > 0) {
const lbl = vectorResults.length > 0 ? 'Or pick from your product catalog' : 'Pick from your product catalog';
html += `<div class="modal-section-label">${lbl}</div>
<div class="catalog-grid">${catalogItems.map(renderCatalogCard).join('')}</div>`;
}
if (!html) {
html = `<p class="placeholder-text" style="text-align:center;padding:2rem 0">No matches found.</p>`;
}
similarGrid.innerHTML = html;
similarGrid.querySelectorAll('.btn-add-similar, .btn-add-catalog, .btn-add-gemma').forEach(btn => {
btn.addEventListener('click', () => {
addToCart({ id: btn.dataset.id, name: btn.dataset.name, price: parseFloat(btn.dataset.price), unit: btn.dataset.unit });
closeSimilarModal();
showNotification(`Added ${btn.dataset.name} to bill`);
});
});
similarModal.classList.remove('hidden');
}
function renderGemmaConflictCard(item) {
return `
<div class="similar-card gemma-conflict-card">
<div class="similar-thumb gemma-conflict-thumb">🤖</div>
<div class="similar-card-body">
<div class="similar-name">${item.name}</div>
<div class="similar-meta">${[item.brand, item.unit].filter(Boolean).join(' · ')}</div>
<div class="similar-score-bar">
<div class="score-label"><span>Gemma confidence</span><span>${item.confidence || 'High'}</span></div>
<div class="score-track"><div class="score-fill gemma-score-fill" style="width:85%"></div></div>
</div>
<div class="similar-price">₹${Number(item.price).toFixed(2)}</div>
</div>
<button class="btn-add-gemma"
data-id="${item.id}"
data-name="${item.name.replace(/"/g, '"')}"
data-price="${item.price}"
data-unit="${item.unit || 'N/A'}">Yes, this is correct</button>
</div>`;
}
function renderVectorCard(r) {
return `
<div class="similar-card">
<div class="similar-thumb">
${r.thumbnail_url
? `<img src="${r.thumbnail_url}" alt="${r.name}" onerror="this.parentNode.innerHTML='📦'">`
: '📦'}
</div>
<div class="similar-card-body">
<div class="similar-name">${r.name}</div>
<div class="similar-meta">${[r.brand, r.unit].filter(Boolean).join(' · ')}</div>
<div class="similar-score-bar">
<div class="score-label"><span>Visual match</span><span>${Math.round(r.score * 100)}%</span></div>
<div class="score-track"><div class="score-fill" style="width:${Math.round(r.score * 100)}%"></div></div>
</div>
<div class="similar-price">₹${Number(r.price).toFixed(2)}</div>
</div>
<button class="btn-add-similar"
data-id="${r.product_id}"
data-name="${r.name.replace(/"/g, '"')}"
data-price="${r.price}"
data-unit="${r.unit || 'N/A'}">Add to Cart</button>
</div>`;
}
function renderCatalogCard(p) {
return `
<div class="catalog-card">
<div class="catalog-card-info">
<div class="catalog-card-name" title="${p.name}">${p.name}</div>
<div class="catalog-card-meta">${[p.brand, p.unit].filter(Boolean).join(' · ')}</div>
</div>
<div class="catalog-card-right">
<div class="catalog-card-price">₹${Number(p.price).toFixed(2)}</div>
<button class="btn-add-catalog"
data-id="${p.id}"
data-name="${p.name.replace(/"/g, '"')}"
data-price="${p.price}"
data-unit="${p.unit || 'N/A'}">Add</button>
</div>
</div>`;
}
function closeSimilarModal() {
similarModal.classList.add('hidden');
}
similarCloseBtn.addEventListener('click', closeSimilarModal);
similarModal.addEventListener('click', e => { if (e.target === similarModal) closeSimilarModal(); });
addNewFromSimilarBtn.addEventListener('click', () => { closeSimilarModal(); showAddModal(); });
// ── Misclassification correction ──────────────────────────────────────────
function removeLastFromCart(itemId) {
const idx = cart.findIndex(i => i.id === itemId);
if (idx === -1) return;
if (cart[idx].quantity > 1) cart[idx].quantity -= 1;
else cart.splice(idx, 1);
renderCart();
}
async function handleWrongProduct(wrongItem) {
removeLastFromCart(wrongItem.id);
lastItemInfo.innerHTML = `<p class="placeholder-text">Removed — finding the correct product…</p>`;
showNotification(`Removed ${wrongItem.name} — select the correct one`, 'warning');
let vectorResults = [];
if (lastCapturedBlob) {
try {
const fd = new FormData();
fd.append('file', lastCapturedBlob, 'captured.jpg');
vectorResults = (await (await fetch('/api/vector-search', { method: 'POST', body: fd })).json()).vector_results || [];
} catch(e) { console.error('Correction vector search failed:', e); }
}
showSimilarModal(
vectorResults,
catalogProducts,
'Select the Correct Product',
'The item was misidentified. Pick the correct product from the list or add it as new.'
);
}
// ── Add Product Modal ─────────────────────────────────────────────────────
function totalPhotoCount() {
return (useScanCapture ? 1 : 0) + capturedProductBlobs.length + pendingUploadFiles.length;
}
function refreshPhotoPreviews() {
imagePreviewStrip.innerHTML = '';
const makeWrap = (src, extraClass, onRemove) => {
const wrap = document.createElement('div');
wrap.className = 'preview-thumb-wrap';
const img = document.createElement('img');
img.src = src;
img.className = `preview-thumb${extraClass ? ' ' + extraClass : ''}`;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'preview-remove-btn';
btn.title = 'Remove';
btn.textContent = '×';
btn.addEventListener('click', onRemove);
wrap.appendChild(img);
wrap.appendChild(btn);
imagePreviewStrip.appendChild(wrap);
};
if (useScanCapture && lastCapturedBlob) {
makeWrap(URL.createObjectURL(lastCapturedBlob), 'captured', () => {
useScanCapture = false;
refreshPhotoPreviews();
});
}
capturedProductBlobs.forEach((b, i) => {
makeWrap(URL.createObjectURL(b), 'cam-capture', () => {
capturedProductBlobs.splice(i, 1);
refreshPhotoPreviews();
});
});
pendingUploadFiles.forEach((f, i) => {
makeWrap(URL.createObjectURL(f), '', () => {
pendingUploadFiles.splice(i, 1);
refreshPhotoPreviews();
});
});
}
function showAddModal() {
addProductForm.reset();
newImagesInput.value = '';
capturedProductBlobs = [];
pendingUploadFiles = [];
useScanCapture = !!lastCapturedBlob;
refreshPhotoPreviews();
modalCameraPreview.srcObject = webcam.srcObject || null;
addModal.classList.remove('hidden');
}
function closeAddModal() {
addModal.classList.add('hidden');
modalCameraPreview.srcObject = null;
}
addCloseBtn.addEventListener('click', closeAddModal);
addModal.addEventListener('click', e => { if (e.target === addModal) closeAddModal(); });
uploadZone.addEventListener('click', () => newImagesInput.click());
newImagesInput.addEventListener('change', () => {
const incoming = Array.from(newImagesInput.files);
const slots = 3 - totalPhotoCount();
pendingUploadFiles.push(...incoming.slice(0, slots));
newImagesInput.value = ''; // allow re-selecting same file
refreshPhotoPreviews();
});
captureProductBtn.addEventListener('click', () => {
if (totalPhotoCount() >= 3) {
showNotification('Maximum 3 photos allowed', 'warning');
return;
}
if (!webcam.videoWidth) {
showNotification('Camera not available', 'error');
return;
}
const ctx = captureCanvas.getContext('2d');
captureCanvas.width = webcam.videoWidth;
captureCanvas.height = webcam.videoHeight;
ctx.drawImage(webcam, 0, 0);
captureCanvas.toBlob(blob => {
capturedProductBlobs.push(blob);
refreshPhotoPreviews();
showNotification('Photo captured');
}, 'image/jpeg', 0.85);
});
addProductForm.addEventListener('submit', async e => {
e.preventDefault();
const name = document.getElementById('new-name').value.trim();
const priceVal = document.getElementById('new-price').value;
const category = document.getElementById('new-category').value.trim() || 'General';
const brand = document.getElementById('new-brand').value.trim() || 'Unknown';
const unit = document.getElementById('new-unit').value.trim() || 'N/A';
if (!name || !priceVal) {
showNotification('Please fill in Name and Price.', 'error');
return;
}
const fd = new FormData();
fd.append('name', name);
fd.append('price', parseFloat(priceVal));
fd.append('category', category);
fd.append('brand', brand);
fd.append('unit', unit);
const allImages = [
...(useScanCapture && lastCapturedBlob ? [{ blob: lastCapturedBlob, name: 'captured.jpg' }] : []),
...capturedProductBlobs.map((b, i) => ({ blob: b, name: `cam_${i + 1}.jpg` })),
...pendingUploadFiles.map(f => ({ blob: f, name: f.name })),
].slice(0, 3);
if (allImages.length === 0) {
showNotification('Please add at least one photo.', 'error');
return;
}
allImages.forEach(({ blob, name }) => fd.append('images', blob, name));
setSaveLoading(true);
try {
const res = await fetch('/api/add-product', { method: 'POST', body: fd });
const result = await res.json();
if (result.success) {
addToCart({ id: result.product_id, name, price: parseFloat(priceVal), unit });
closeAddModal();
showNotification(`"${name}" saved to catalog & added to cart`);
} else {
showNotification('Failed to save product.', 'error');
}
} catch (err) {
showNotification('Server error while saving.', 'error');
} finally {
setSaveLoading(false);
}
});
// ── Manage Custom Catalog Modal ───────────────────────────────────────────
const manageModal = document.getElementById('manage-modal');
const manageCloseBtn = document.getElementById('manage-close-btn');
const manageList = document.getElementById('manage-products-list');
const manageCatalogBtn = document.getElementById('manage-catalog-btn');
manageCatalogBtn.addEventListener('click', openManageModal);
manageCloseBtn.addEventListener('click', closeManageModal);
manageModal.addEventListener('click', e => { if (e.target === manageModal) closeManageModal(); });
async function openManageModal() {
manageList.innerHTML = '<p class="placeholder-text" style="text-align:center;padding:2rem">Loading…</p>';
manageModal.classList.remove('hidden');
try {
const data = await (await fetch('/api/vector-products')).json();
renderManageList(data.products || []);
} catch(e) {
manageList.innerHTML = '<p class="placeholder-text" style="text-align:center;padding:2rem">Failed to load.</p>';
}
}
function closeManageModal() {
manageModal.classList.add('hidden');
}
function renderManageList(products) {
if (products.length === 0) {
manageList.innerHTML = `
<div class="manage-empty">
<p style="font-size:2rem">📦</p>
<p>No custom products yet.</p>
<p class="placeholder-text">Scan an unknown item and add it to start building your catalog.</p>
</div>`;
return;
}
manageList.innerHTML = products.map(p => `
<div class="manage-card" id="mc-${p.product_id}">
<div class="manage-thumb">
${p.thumbnail_url
? `<img src="${p.thumbnail_url}" alt="${p.name}" onerror="this.parentNode.innerHTML='📦'">`
: '📦'}
</div>
<div class="manage-info">
<div class="manage-name">${p.name}</div>
<div class="manage-meta">${[p.category, p.brand, p.unit].filter(Boolean).join(' · ')}</div>
<div class="manage-price">₹${Number(p.price).toFixed(2)}</div>
</div>
<button class="btn-delete-product"
data-id="${p.product_id}"
data-name="${p.name.replace(/"/g, '"')}">
🗑 Delete
</button>
</div>`).join('');
manageList.querySelectorAll('.btn-delete-product').forEach(btn => {
btn.addEventListener('click', async () => {
const id = btn.dataset.id;
const name = btn.dataset.name;
if (!confirm(`Delete "${name}" from your catalog?\nThis will also remove all stored photos and cannot be undone.`)) return;
btn.textContent = 'Deleting…';
btn.disabled = true;
try {
const res = await fetch(`/api/delete-product/${id}`, { method: 'DELETE' });
if ((await res.json()).success) {
document.getElementById(`mc-${id}`)?.remove();
showNotification(`Deleted "${name}" from catalog`);
if (!manageList.querySelector('.manage-card')) renderManageList([]);
}
} catch(e) {
showNotification('Failed to delete.', 'error');
btn.textContent = '🗑 Delete';
btn.disabled = false;
}
});
});
}
// ── Utilities ─────────────────────────────────────────────────────────────
function setLoading(on) {
isAnalyzing = on;
scanBtn.disabled = on;
scanBtn.querySelector('.loader').classList.toggle('hidden', !on);
scanBtn.querySelector('.btn-text').textContent = on ? 'Analyzing...' : 'Scan & Add Item';
}
function setSaveLoading(on) {
saveBtn.disabled = on;
saveLoader.classList.toggle('hidden', !on);
saveBtn.querySelector('.btn-text').textContent = on ? 'Saving...' : 'Save & Add to Cart';
}
function showNotification(message, type = 'success') {
const toast = document.createElement('div');
toast.className = `notification ${type}`;
toast.textContent = message;
notificationContainer.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateX(20px)';
setTimeout(() => toast.remove(), 300);
}, 3000);
}
});