-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.js
More file actions
1639 lines (1444 loc) · 65.8 KB
/
app.js
File metadata and controls
1639 lines (1444 loc) · 65.8 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
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Main Application Logic for Sustainable Food Tracker
const API_BASE = 'https://world.openfoodfacts.org';
// Utility function
const $ = (id) => document.getElementById(id);
// Initialize app
document.addEventListener('DOMContentLoaded', () => {
initHomePage();
});
// Initialize home page
function initHomePage() {
const searchForm = $('searchForm');
const searchInput = $('searchInput');
if (searchForm) {
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
const query = searchInput.value.trim();
if (query) {
handleSearch(query);
}
});
}
}
// Handle search
async function handleSearch(query) {
const loadingState = $('loadingState');
const searchResults = $('searchResults');
if (loadingState) loadingState.classList.remove('hidden');
if (searchResults) searchResults.classList.add('hidden');
// Check if it's a barcode (all digits)
if (/^\d+$/.test(query)) {
// Direct to product page
window.location.href = `product.html?barcode=${query}`;
} else {
// Search for products
await searchProducts(query);
}
}
// Search products
async function searchProducts(query) {
try {
const response = await fetch(
`${API_BASE}/cgi/search.pl?search_terms=${encodeURIComponent(query)}&search_simple=1&json=1&page_size=20`
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
displaySearchResults(data.products || []);
} catch (error) {
console.error('Search error:', error);
alert('Search failed. Please try again.');
} finally {
const loadingState = $('loadingState');
if (loadingState) loadingState.classList.add('hidden');
}
}
// Display search results
function displaySearchResults(products) {
const resultsSection = $('searchResults');
const resultsGrid = $('resultsGrid');
if (!resultsSection || !resultsGrid) return;
if (products.length === 0) {
resultsGrid.innerHTML = '<p class="empty-state">No products found. Try a different search term.</p>';
resultsSection.classList.remove('hidden');
return;
}
resultsGrid.innerHTML = products.map(product => {
// Enhanced image source - try multiple image sources
const imageSrc = product.image_url ||
product.image_front_url ||
product.image_front_small_url ||
product.image_small_url ||
product.image_front_thumb_url ||
product.image_thumb_url ||
product.selected_images?.front?.display?.url ||
product.selected_images?.front?.small?.url ||
'placeholder.svg';
return `
<div class="product-item" onclick="viewProduct('${product.code}')">
<img
src="${imageSrc}"
alt="${product.product_name || 'Product'}"
class="product-item-image"
onerror="this.src='placeholder.svg'"
>
<div class="product-item-content">
<h3 class="product-item-name">${product.product_name || 'Unknown Product'}</h3>
<p class="product-item-brand">${product.brands || 'Unknown Brand'}</p>
<div class="product-item-grades">
${createGradeBadge(product.nutriscore_grade || product.nutrition_grades, 'small')}
${createGradeBadge(product.ecoscore_grade, 'small')}
</div>
</div>
</div>
`;
}).join('');
resultsSection.classList.remove('hidden');
}
// Create grade badge
function createGradeBadge(grade, size = '') {
if (!grade || grade === 'N/A') {
return `<span class="grade-badge grade-na ${size}">N/A</span>`;
}
const gradeValue = String(grade).toLowerCase().trim();
const validGrades = ['a', 'b', 'c', 'd', 'e'];
const normalizedGrade = gradeValue.length === 1 ? gradeValue : gradeValue.charAt(0);
const gradeClass = validGrades.includes(normalizedGrade) ? `grade-${normalizedGrade}` : 'grade-na';
const displayGrade = validGrades.includes(normalizedGrade) ? normalizedGrade.toUpperCase() : 'N/A';
return `<span class="grade-badge ${gradeClass} ${size}">${displayGrade}</span>`;
}
// View product
window.viewProduct = function(barcode) {
window.location.href = `product.html?barcode=${barcode}`;
};
// Go back
window.goBack = function() {
window.history.back();
};
// Load product details
async function loadProduct(barcode) {
const loadingState = $('productLoading');
const detailsSection = $('productDetails');
if (!barcode) {
alert('No barcode provided');
window.location.href = 'index.html';
return;
}
try {
console.log('Loading product with barcode:', barcode);
// Try API v2 first (simplified fetch without explicit CORS mode)
let response;
let data;
let success = false;
// Try v2 API
try {
console.log('Trying API v2...');
const url = `${API_BASE}/api/v2/product/${encodeURIComponent(barcode)}`;
console.log('Fetching from:', url);
response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
data = await response.json();
console.log('API v2 response:', data);
if (data.status === 1 && data.product) {
success = true;
}
} catch (fetchError) {
console.warn('API v2 failed:', fetchError.message);
}
// If v2 failed or no product, try v0 API
if (!success) {
try {
console.log('Trying API v0...');
const url = `${API_BASE}/api/v0/product/${encodeURIComponent(barcode)}.json`;
console.log('Fetching from:', url);
response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
data = await response.json();
console.log('API v0 response:', data);
if (data.product) {
success = true;
}
} catch (v0Error) {
console.warn('API v0 failed:', v0Error.message);
}
}
// If still no product, try JSON endpoint
if (!success) {
try {
console.log('Trying JSON endpoint...');
const url = `${API_BASE}/cgi/product.pl?code=${encodeURIComponent(barcode)}&action=display&json=1`;
console.log('Fetching from:', url);
response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
data = await response.json();
console.log('JSON endpoint response:', data);
if (data.product) {
success = true;
}
} catch (jsonError) {
console.warn('JSON endpoint failed:', jsonError.message);
}
}
// If still no product, try searching by barcode
if (!success) {
try {
console.log('Trying search by barcode as fallback...');
const url = `${API_BASE}/cgi/search.pl?code=${encodeURIComponent(barcode)}&json=1&page_size=1`;
console.log('Fetching from:', url);
response = await fetch(url);
if (response.ok) {
data = await response.json();
console.log('Search by barcode response:', data);
if (data.products && data.products.length > 0) {
// Find exact barcode match
const exactMatch = data.products.find(p => p.code === barcode);
if (exactMatch) {
data = { product: exactMatch };
success = true;
} else if (data.products[0]) {
// Use first result if no exact match
data = { product: data.products[0] };
success = true;
}
}
}
} catch (searchError) {
console.warn('Search by barcode failed:', searchError.message);
}
}
// If still no product, try with padded zeros (for EAN-8 to EAN-13 conversion)
if (!success && barcode.length === 8) {
try {
console.log('Trying with padded zeros for EAN-8...');
// Try different padding combinations
const paddedBarcodes = [
'0' + barcode, // 9 digits
'00' + barcode, // 10 digits
'000' + barcode, // 11 digits
'0000' + barcode, // 12 digits
'00000' + barcode // 13 digits
];
for (const paddedBarcode of paddedBarcodes) {
try {
const url = `${API_BASE}/api/v2/product/${encodeURIComponent(paddedBarcode)}`;
response = await fetch(url);
if (response.ok) {
const paddedData = await response.json();
if (paddedData.status === 1 && paddedData.product) {
data = paddedData;
success = true;
console.log('Found product with padded barcode:', paddedBarcode);
break;
}
}
} catch (e) {
continue;
}
}
} catch (padError) {
console.warn('Padded barcode search failed:', padError.message);
}
}
if (success && data && data.product) {
const product = data.product;
// Log full API response for debugging
console.log('=== FULL API RESPONSE ===');
console.log('Complete product data:', product);
console.log('Product keys:', Object.keys(product));
console.log('NutriScore fields:', {
nutriscore_grade: product.nutriscore_grade,
nutrition_grades: product.nutrition_grades,
nutriscore_data: product.nutriscore_data,
nutriscore_score: product.nutriscore_score
});
console.log('EcoScore fields:', {
ecoscore_grade: product.ecoscore_grade,
ecoscore_data: product.ecoscore_data,
ecoscore_score: product.ecoscore_score
});
console.log('CO2 fields:', {
ecoscore_data_agribalyse: product.ecoscore_data?.agribalyse,
carbon_footprint: product.carbon_footprint
});
console.log('Additives fields:', {
additives_tags: product.additives_tags,
additives: product.additives,
additives_original_tags: product.additives_original_tags
});
// Save to history and calculate points
const historyItem = storage.saveToHistory(product);
// Extract scores for points calculation
const nutriGrade = product.nutriscore_grade || product.nutrition_grades || product.nutriscore_data?.grade;
const ecoGrade = product.ecoscore_grade || product.ecoscore_data?.grade;
const points = storage.calculatePoints(nutriGrade, ecoGrade);
storage.addEcoPoints(points);
// Display product
displayProduct(product);
if (loadingState) loadingState.classList.add('hidden');
if (detailsSection) detailsSection.classList.remove('hidden');
} else {
console.error('Product not found. Final data:', data);
console.error('Barcode tried:', barcode);
// Show helpful error with options
const testBarcodes = [
'3017620422003', // Nutella
'7622210945078', // Oreo
'3017620429484', // Coca Cola
'5000159461125' // Kit Kat
];
let message = `Product not found for barcode: ${barcode}\n\n`;
if (barcode.length < 8) {
message += `⚠ This barcode is too short (${barcode.length} digits).\n`;
message += `Valid barcodes are usually 8-13 digits.\n\n`;
} else if (barcode.length === 8) {
message += `⚠ This is an EAN-8 barcode.\n`;
message += `The product might not be in the database, or the barcode format might be different.\n\n`;
}
message += `Options:\n`;
message += `1. Try these test barcodes: ${testBarcodes.join(', ')}\n`;
message += `2. Search by product name instead\n`;
message += `3. Try scanning a different product`;
// Show error but allow user to go back
if (confirm(message + '\n\nClick OK to go back to search, or Cancel to stay here.')) {
window.location.href = 'index.html';
} else {
if (loadingState) loadingState.classList.add('hidden');
}
}
} catch (error) {
console.error('Load product error:', error);
console.error('Error details:', {
name: error.name,
message: error.message,
stack: error.stack
});
// Better error messages based on error type
let errorMessage = 'Failed to load product. ';
if (error.message.includes('Failed to fetch') ||
error.message.includes('NetworkError') ||
error.name === 'TypeError' ||
error.message.includes('network')) {
errorMessage += 'Network error detected.\n\n';
errorMessage += 'Possible causes:\n';
errorMessage += '1. No internet connection\n';
errorMessage += '2. OpenFoodFacts API is temporarily down\n';
errorMessage += '3. Firewall or security software blocking requests\n';
errorMessage += '4. Make sure you are using http://localhost:8000\n\n';
errorMessage += 'Please:\n';
errorMessage += '- Check your internet connection\n';
errorMessage += '- Try again in a few moments\n';
errorMessage += '- Or search by product name instead';
} else if (error.message.includes('CORS')) {
errorMessage += 'CORS error detected.\n\n';
errorMessage += 'Make sure you are accessing the app via:\n';
errorMessage += '- http://localhost:8000 (not file://)\n';
errorMessage += '- Or a proper web server';
} else {
errorMessage += error.message || 'Unknown error occurred.';
errorMessage += '\n\nCheck browser console (F12) for more details.';
}
alert(errorMessage);
if (loadingState) loadingState.classList.add('hidden');
}
}
// Display product details
function displayProduct(product) {
console.log('Displaying product with full data:', product);
// Product header
const productImage = $('productImage');
const productName = $('productName');
const productBrand = $('productBrand');
// Enhanced image loading - try multiple image sources
if (productImage) {
const imageSources = [
product.image_front_url,
product.image_url,
product.image_front_small_url,
product.image_small_url,
product.image_front_thumb_url,
product.image_thumb_url,
product.images?.front?.display?.en || product.images?.front?.display?.fr,
product.images?.front?.small?.en || product.images?.front?.small?.fr,
product.images?.front?.thumb?.en || product.images?.front?.thumb?.fr,
product.selected_images?.front?.display?.url,
product.selected_images?.front?.small?.url,
product.selected_images?.front?.thumb?.url
].filter(Boolean); // Remove null/undefined values
// Try first available image
if (imageSources.length > 0) {
productImage.src = imageSources[0];
productImage.alt = product.product_name || 'Product';
// Fallback chain if image fails to load
let currentIndex = 0;
productImage.onerror = function() {
currentIndex++;
if (currentIndex < imageSources.length) {
this.src = imageSources[currentIndex];
} else {
// All images failed, use placeholder
this.src = 'placeholder.svg';
this.onerror = null; // Prevent infinite loop
}
};
} else {
productImage.src = 'placeholder.svg';
}
productImage.alt = product.product_name || 'Product';
console.log('Loading product image from:', imageSources[0] || 'placeholder.svg');
}
if (productName) {
productName.textContent = product.product_name ||
product.product_name_en ||
product.product_name_fr ||
'Unknown Product';
}
if (productBrand) {
const brands = product.brands ||
product.brand ||
(product.brands_tags ? product.brands_tags.join(', ') : '') ||
'';
productBrand.textContent = brands;
}
// Scores - Enhanced extraction with multiple field checks
// Always show scores section
const scoresCard = document.querySelector('.scores-card');
if (scoresCard) {
scoresCard.style.display = 'block';
}
const nutriScore = $('nutriScore');
const ecoScore = $('ecoScore');
const co2Score = $('co2Value');
// Log all possible score fields for debugging
console.log('=== SCORE EXTRACTION DEBUG ===');
console.log('nutriscore_grade:', product.nutriscore_grade);
console.log('nutrition_grades:', product.nutrition_grades);
console.log('nutrition_grade_fr:', product.nutrition_grade_fr);
console.log('nutriscore_data:', product.nutriscore_data);
console.log('ecoscore_grade:', product.ecoscore_grade);
console.log('ecoscore_data:', product.ecoscore_data);
console.log('nutriments:', product.nutriments ? Object.keys(product.nutriments) : 'none');
if (nutriScore) {
// Enhanced NutriScore extraction from multiple API response structures
console.log('=== NUTRISCORE EXTRACTION DEBUG ===');
console.log('nutriscore_grade:', product.nutriscore_grade);
console.log('nutrition_grades:', product.nutrition_grades);
console.log('nutrition_grade_fr:', product.nutrition_grade_fr);
console.log('nutriscore_data:', product.nutriscore_data);
console.log('nutriscore_score:', product.nutriscore_score);
let grade = null;
// Method 1: Direct nutriscore_grade (most common)
if (product.nutriscore_grade) {
grade = product.nutriscore_grade;
console.log('Found NutriScore in nutriscore_grade:', grade);
}
// Method 2: nutrition_grades
else if (product.nutrition_grades) {
grade = product.nutrition_grades;
console.log('Found NutriScore in nutrition_grades:', grade);
}
// Method 3: nutrition_grade_fr
else if (product.nutrition_grade_fr) {
grade = product.nutrition_grade_fr;
console.log('Found NutriScore in nutrition_grade_fr:', grade);
}
// Method 4: nutriscore_data.grade
else if (product.nutriscore_data?.grade) {
grade = product.nutriscore_data.grade;
console.log('Found NutriScore in nutriscore_data.grade:', grade);
}
// Method 5: Calculate from nutriscore_data.score
else if (product.nutriscore_data?.score !== undefined) {
const score = product.nutriscore_data.score;
// NutriScore scale: -15 to 40, lower is better
if (score <= -1) grade = 'a';
else if (score <= 2) grade = 'b';
else if (score <= 10) grade = 'c';
else if (score <= 18) grade = 'd';
else grade = 'e';
console.log('Calculated NutriScore from nutriscore_data.score:', score, '->', grade);
}
// Method 6: nutriscore_score (direct)
else if (product.nutriscore_score !== undefined) {
const score = product.nutriscore_score;
if (score <= -1) grade = 'a';
else if (score <= 2) grade = 'b';
else if (score <= 10) grade = 'c';
else if (score <= 18) grade = 'd';
else grade = 'e';
console.log('Calculated NutriScore from nutriscore_score:', score, '->', grade);
}
// Method 7: Calculate from nutriments nutrition-score-fr
else if (product.nutriments) {
const score = product.nutriments['nutrition-score-fr'] ||
product.nutriments['nutrition-score-fr_100g'] ||
product.nutriments['nutrition-score-fr_value'] ||
product.nutriments['nutrition-score'] ||
product.nutriments['nutrition_score_fr'];
if (score !== undefined && score !== null) {
const numScore = parseFloat(score);
if (!isNaN(numScore)) {
if (numScore <= -1) grade = 'a';
else if (numScore <= 2) grade = 'b';
else if (numScore <= 10) grade = 'c';
else if (numScore <= 18) grade = 'd';
else grade = 'e';
console.log('Calculated NutriScore from nutriments score:', numScore, '->', grade);
}
}
}
// Normalize grade
if (grade) {
grade = String(grade).toLowerCase().trim();
// Extract first character if it's a longer string
if (grade.length > 1 && !['a', 'b', 'c', 'd', 'e'].includes(grade)) {
grade = grade.charAt(0).toLowerCase();
}
if (!['a', 'b', 'c', 'd', 'e'].includes(grade)) {
grade = null;
}
}
// If still no grade, try to estimate from nutritional values
if (!grade && product.nutriments) {
const fat = product.nutriments.fat_100g || 0;
const satFat = product.nutriments['saturated-fat_100g'] || 0;
const sugar = product.nutriments.sugars_100g || 0;
const salt = product.nutriments.salt_100g || 0;
const fiber = product.nutriments.fiber_100g || 0;
const protein = product.nutriments.proteins_100g || 0;
// Simple estimation based on key nutrients
let estimatedScore = 0;
if (fat > 20 || satFat > 10) estimatedScore += 10;
if (sugar > 22.5) estimatedScore += 10;
if (salt > 1.5) estimatedScore += 10;
if (fiber > 3) estimatedScore -= 5;
if (protein > 10) estimatedScore -= 2;
if (estimatedScore <= -1) grade = 'a';
else if (estimatedScore <= 2) grade = 'b';
else if (estimatedScore <= 10) grade = 'c';
else if (estimatedScore <= 18) grade = 'd';
else grade = 'e';
console.log('Estimated NutriScore from nutrients:', estimatedScore, '->', grade);
}
// Final fallback - show estimated if available
if (!grade) {
grade = 'c'; // Default to C if nothing found
console.log('Using default NutriScore: C');
}
console.log('Final NutriScore:', grade);
nutriScore.innerHTML = createGradeBadge(grade);
// Store for impact score calculation
window.currentNutriScore = grade;
}
if (ecoScore) {
// Enhanced EcoScore extraction from multiple API response structures
console.log('=== ECOSCORE EXTRACTION DEBUG ===');
console.log('ecoscore_grade:', product.ecoscore_grade);
console.log('ecoscore_data:', product.ecoscore_data);
console.log('ecoscore_score:', product.ecoscore_score);
console.log('environment_impact_level:', product.environment_impact_level);
let grade = null;
// Method 1: Direct ecoscore_grade
if (product.ecoscore_grade) {
grade = product.ecoscore_grade;
console.log('Found EcoScore in ecoscore_grade:', grade);
}
// Method 2: ecoscore_data.grade
else if (product.ecoscore_data?.grade) {
grade = product.ecoscore_data.grade;
console.log('Found EcoScore in ecoscore_data.grade:', grade);
}
// Method 3: ecoscore_data.adjusted_grade
else if (product.ecoscore_data?.adjusted_grade) {
grade = product.ecoscore_data.adjusted_grade;
console.log('Found EcoScore in ecoscore_data.adjusted_grade:', grade);
}
// Method 4: Calculate from ecoscore_score
else if (product.ecoscore_data?.score !== undefined) {
const score = product.ecoscore_data.score;
// Convert numeric score to grade (0-100 scale, lower is better)
if (score <= 20) grade = 'a';
else if (score <= 40) grade = 'b';
else if (score <= 60) grade = 'c';
else if (score <= 80) grade = 'd';
else grade = 'e';
console.log('Calculated EcoScore from score:', score, '->', grade);
}
// Method 5: ecoscore_score (direct)
else if (product.ecoscore_score !== undefined) {
const score = product.ecoscore_score;
if (score <= 20) grade = 'a';
else if (score <= 40) grade = 'b';
else if (score <= 60) grade = 'c';
else if (score <= 80) grade = 'd';
else grade = 'e';
console.log('Calculated EcoScore from ecoscore_score:', score, '->', grade);
}
// Method 6: environment_impact_level (if it's a grade)
else if (product.environment_impact_level && /^[a-e]$/i.test(product.environment_impact_level)) {
grade = product.environment_impact_level.toLowerCase();
console.log('Found EcoScore in environment_impact_level:', grade);
}
// Normalize grade
if (grade) {
grade = String(grade).toLowerCase().trim();
if (!['a', 'b', 'c', 'd', 'e'].includes(grade)) {
grade = null;
}
}
// If still no grade, try to estimate from packaging and origin
if (!grade) {
const packaging = product.packaging || '';
const origins = product.origins || '';
const labels = product.labels_tags || [];
// Estimate based on eco-friendly indicators
let ecoIndicators = 0;
if (packaging.toLowerCase().includes('recycl') || packaging.toLowerCase().includes('biodegrad')) ecoIndicators += 2;
if (labels.some(l => l.includes('organic') || l.includes('bio') || l.includes('fair-trade'))) ecoIndicators += 3;
if (origins && origins.length > 0) ecoIndicators += 1; // Local origin is better
if (ecoIndicators >= 4) grade = 'a';
else if (ecoIndicators >= 3) grade = 'b';
else if (ecoIndicators >= 2) grade = 'c';
else if (ecoIndicators >= 1) grade = 'd';
else grade = 'c'; // Default to C
console.log('Estimated EcoScore from indicators:', ecoIndicators, '->', grade);
}
// Final fallback
if (!grade) {
grade = 'c'; // Default to C if nothing found
console.log('Using default EcoScore: C');
}
console.log('Final EcoScore:', grade);
ecoScore.innerHTML = createGradeBadge(grade);
// Store for impact score calculation
window.currentEcoScore = grade;
}
// CO₂ Impact - Enhanced extraction from multiple API response structures
if (co2Score) {
console.log('=== CO2 EXTRACTION DEBUG ===');
console.log('ecoscore_data:', product.ecoscore_data);
console.log('ecoscore_data.agribalyse:', product.ecoscore_data?.agribalyse);
console.log('environment_impact_level:', product.environment_impact_level);
let co2 = null;
// Try multiple paths for CO2 data
if (product.ecoscore_data) {
// Path 1: ecoscore_data.agribalyse.co2_total
if (product.ecoscore_data.agribalyse?.co2_total) {
co2 = product.ecoscore_data.agribalyse.co2_total;
console.log('Found CO2 in agribalyse.co2_total:', co2);
}
// Path 2: ecoscore_data.co2_total
else if (product.ecoscore_data.co2_total) {
co2 = product.ecoscore_data.co2_total;
console.log('Found CO2 in ecoscore_data.co2_total:', co2);
}
// Path 3: ecoscore_data.agribalyse.ef_agriculture
else if (product.ecoscore_data.agribalyse?.ef_agriculture) {
co2 = product.ecoscore_data.agribalyse.ef_agriculture;
console.log('Found CO2 in agribalyse.ef_agriculture:', co2);
}
// Path 4: ecoscore_data.agribalyse.ef_consumption
else if (product.ecoscore_data.agribalyse?.ef_consumption) {
co2 = product.ecoscore_data.agribalyse.ef_consumption;
console.log('Found CO2 in agribalyse.ef_consumption:', co2);
}
}
// Path 5: Direct environment_impact_level (if it's a number)
if (!co2 && product.environment_impact_level) {
const envImpact = parseFloat(product.environment_impact_level);
if (!isNaN(envImpact) && envImpact > 0) {
co2 = envImpact;
console.log('Found CO2 in environment_impact_level:', co2);
}
}
// Path 6: Check for carbon_footprint fields
if (!co2 && product.carbon_footprint) {
co2 = product.carbon_footprint;
console.log('Found CO2 in carbon_footprint:', co2);
}
// Path 7: Check for carbon_footprint_per_kg
if (!co2 && product.carbon_footprint_per_kg_of_product) {
co2 = product.carbon_footprint_per_kg_of_product;
console.log('Found CO2 in carbon_footprint_per_kg_of_product:', co2);
}
// Display CO2 value - always show a value, estimate if needed
if (co2 !== null && co2 !== undefined) {
const co2Value = typeof co2 === 'number' ? co2 : parseFloat(co2);
if (!isNaN(co2Value) && co2Value > 0) {
if (co2Value >= 1000) {
co2Score.textContent = (co2Value / 1000).toFixed(2) + ' kg CO₂';
} else {
co2Score.textContent = co2Value.toFixed(1) + ' g CO₂';
}
co2Score.style.color = 'var(--foreground)';
console.log('Final CO2 value displayed:', co2Value);
} else {
// Estimate CO2 based on product category
const estimatedCo2 = estimateCO2FromProduct(product);
if (estimatedCo2 >= 1000) {
co2Score.textContent = (estimatedCo2 / 1000).toFixed(2) + ' kg CO₂ (est.)';
} else {
co2Score.textContent = estimatedCo2.toFixed(1) + ' g CO₂ (est.)';
}
co2Score.style.color = 'var(--muted-foreground)';
console.log('Estimated CO2 value:', estimatedCo2);
}
} else {
// Estimate CO2 based on product category
const estimatedCo2 = estimateCO2FromProduct(product);
if (estimatedCo2 >= 1000) {
co2Score.textContent = (estimatedCo2 / 1000).toFixed(2) + ' kg CO₂ (est.)';
} else {
co2Score.textContent = estimatedCo2.toFixed(1) + ' g CO₂ (est.)';
}
co2Score.style.color = 'var(--muted-foreground)';
console.log('Estimated CO2 value:', estimatedCo2);
}
// Store CO2 value for impact score calculation
if (co2 !== null && co2 !== undefined) {
const co2Value = typeof co2 === 'number' ? co2 : parseFloat(co2);
if (!isNaN(co2Value) && co2Value > 0) {
window.currentCo2Value = co2Value;
} else {
window.currentCo2Value = null;
}
} else {
window.currentCo2Value = null;
}
}
// Ingredients - Always show section, even if empty
const ingredientsSection = $('ingredientsSection');
const ingredientsList = $('ingredientsList');
if (ingredientsSection && ingredientsList) {
if (product.ingredients_text) {
ingredientsList.textContent = product.ingredients_text;
} else if (product.ingredients && product.ingredients.length > 0) {
// Try to build from ingredients array
const ingredientsText = product.ingredients.map(ing => ing.text || ing.id || '').join(', ');
ingredientsList.textContent = ingredientsText || 'Ingredients information not available';
} else {
ingredientsList.textContent = 'Ingredients information not available for this product.';
}
ingredientsSection.classList.remove('hidden');
}
// Additives - Enhanced extraction with detailed information
const additivesSection = $('additivesSection');
const additivesList = $('additivesList');
if (additivesSection && additivesList) {
console.log('=== ADDITIVES EXTRACTION DEBUG ===');
console.log('additives_tags:', product.additives_tags);
console.log('additives:', product.additives);
console.log('additives_original_tags:', product.additives_original_tags);
console.log('additives_debug:', product.additives_debug);
let additivesFound = [];
// Method 1: additives_tags (most common)
if (product.additives_tags && product.additives_tags.length > 0) {
additivesFound = product.additives_tags.map(tag => {
// Clean tag format: "en:e100" -> "E100"
const cleanName = tag
.replace(/^(en|fr|de|es|it|pt|nl):/, '') // Remove language prefix
.replace(/^e/, 'E') // Capitalize E
.replace(/-/g, ' '); // Replace hyphens with spaces
return cleanName;
});
console.log('Found additives from additives_tags:', additivesFound);
}
// Method 2: additives array with objects
else if (product.additives && Array.isArray(product.additives) && product.additives.length > 0) {
additivesFound = product.additives.map(additive => {
if (typeof additive === 'string') {
return additive.replace(/^e/i, 'E').replace(/-/g, ' ');
} else if (typeof additive === 'object') {
return additive.name ||
additive.id ||
additive.text ||
(additive.id ? additive.id.replace(/^e/i, 'E') : 'Unknown');
}
return String(additive).replace(/^e/i, 'E').replace(/-/g, ' ');
});
console.log('Found additives from additives array:', additivesFound);
}
// Method 3: additives_original_tags
else if (product.additives_original_tags && product.additives_original_tags.length > 0) {
additivesFound = product.additives_original_tags.map(tag => {
return tag.replace(/^(en|fr|de|es|it|pt|nl):/, '').replace(/^e/i, 'E').replace(/-/g, ' ');
});
console.log('Found additives from additives_original_tags:', additivesFound);
}
// Method 4: Check ingredients for additives (E numbers)
if (additivesFound.length === 0 && product.ingredients) {
const eNumberRegex = /\bE\d{3}[a-z]?\b/gi;
const ingredientsText = product.ingredients_text ||
(Array.isArray(product.ingredients) ?
product.ingredients.map(i => i.text || i.id || '').join(' ') : '');
if (ingredientsText) {
const matches = ingredientsText.match(eNumberRegex);
if (matches) {
additivesFound = [...new Set(matches)]; // Remove duplicates
console.log('Found additives from ingredients text:', additivesFound);
}
}
}
// Display additives
if (additivesFound.length > 0) {
// Remove duplicates and limit to 15
const uniqueAdditives = [...new Set(additivesFound)].slice(0, 15);
additivesList.innerHTML = uniqueAdditives.map(additive => {
return `<span class="badge badge-warning" title="Additive: ${additive}">${additive}</span>`;
}).join('');
// Show count if more than displayed
if (additivesFound.length > 15) {
additivesList.innerHTML += `<span class="badge badge-secondary">+${additivesFound.length - 15} more</span>`;
}
console.log('Displaying additives:', uniqueAdditives);
} else {
additivesList.innerHTML = '<span class="badge badge-success">No additives detected</span>';
console.log('No additives found');
}
additivesSection.classList.remove('hidden');
}
// Health Initiatives Section
displayHealthInitiatives(product);
// Nutrition facts - Always show section
const nutritionSection = $('nutritionSection');
const nutritionGrid = $('nutritionGrid');
if (nutritionSection && nutritionGrid) {
const nutrients = [
{ key: 'energy-kcal_100g', label: 'Calories', unit: 'kcal' },
{ key: 'proteins_100g', label: 'Proteins', unit: 'g' },
{ key: 'carbohydrates_100g', label: 'Carbohydrates', unit: 'g' },
{ key: 'fat_100g', label: 'Fats', unit: 'g' },
{ key: 'sugars_100g', label: 'Sugars', unit: 'g' },
{ key: 'salt_100g', label: 'Salt', unit: 'g' },
{ key: 'fiber_100g', label: 'Fiber', unit: 'g' },
{ key: 'saturated-fat_100g', label: 'Saturated Fat', unit: 'g' }
];
if (product.nutriments) {
const availableNutrients = nutrients.filter(n => {
const value = product.nutriments[n.key];
return value !== undefined && value !== null && !isNaN(value) && value !== '';
});
if (availableNutrients.length > 0) {
nutritionGrid.innerHTML = availableNutrients.map(nutrient => `
<div class="nutrition-item">
<div class="nutrition-item-label">${nutrient.label}</div>
<div class="nutrition-item-value">
${product.nutriments[nutrient.key].toFixed(1)}
<span class="nutrition-item-unit">${nutrient.unit}</span>
</div>
</div>
`).join('');
nutritionSection.classList.remove('hidden');
// Create nutrition chart
createNutritionChart(product.nutriments, availableNutrients);
} else {
nutritionGrid.innerHTML = '<p class="empty-state">Nutrition information not available for this product.</p>';
nutritionSection.classList.remove('hidden');
}
} else {
nutritionGrid.innerHTML = '<p class="empty-state">Nutrition information not available for this product.</p>';
nutritionSection.classList.remove('hidden');
}
}
}
// Create nutrition chart
function createNutritionChart(nutriments, nutrients) {
const chartSection = $('nutritionChartSection');
if (!chartSection || typeof Chart === 'undefined') return;
chartSection.classList.remove('hidden');
const ctx = document.getElementById('nutritionChart');
if (!ctx) return;
const labels = nutrients.map(n => n.label);
const data = nutrients.map(n => nutriments[n.key]);
const colors = [
'rgba(255, 99, 132, 0.8)',
'rgba(54, 162, 235, 0.8)',
'rgba(255, 206, 86, 0.8)',
'rgba(75, 192, 192, 0.8)',
'rgba(153, 102, 255, 0.8)',
'rgba(255, 159, 64, 0.8)'
];
new Chart(ctx, {
type: 'bar',
data: {
labels: labels,