-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1601 lines (1391 loc) · 57.9 KB
/
Copy pathscript.js
File metadata and controls
1601 lines (1391 loc) · 57.9 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
// ====================================================================
// Fitent - Premium JavaScript Controller & Integrations
// ====================================================================
// Global Application Configuration & State
let config = {
supabaseUrl: localStorage.getItem('np_supabase_url') || '',
supabaseKey: localStorage.getItem('np_supabase_key') || '',
geminiKey: localStorage.getItem('np_gemini_key') || ''
};
let supabaseClient = null;
let currentUser = null;
let currentSelectedDate = '';
let foodDatabase = {};
const notificationMeta = {
success: { title: 'Success', icon: '✓' },
error: { title: 'Error', icon: '!' },
warning: { title: 'Heads up', icon: '?' },
info: { title: 'Notice', icon: 'i' }
};
function inferNotificationType(message) {
const text = String(message).toLowerCase();
if (/(success|saved|updated|sent|logged|synchronized)/.test(text)) return 'success';
if (/(error|failed|failure|unable|missing|required|invalid|corrupted)/.test(text)) return 'error';
if (/(please|verify|must|check|configure)/.test(text)) return 'warning';
return 'info';
}
function removeNotification(toast) {
if (!toast || toast.classList.contains('is-leaving')) return;
toast.classList.add('is-leaving');
toast.addEventListener('animationend', () => toast.remove(), { once: true });
}
function showNotification(message, type = 'info', duration = 4500) {
const container = document.getElementById('notification-container');
if (!container) {
console.log(message);
return;
}
const safeType = notificationMeta[type] ? type : 'info';
const meta = notificationMeta[safeType];
const toast = document.createElement('div');
toast.className = `app-toast app-toast-${safeType}`;
toast.setAttribute('role', safeType === 'error' ? 'alert' : 'status');
toast.innerHTML = `
<div class="toast-icon">${meta.icon}</div>
<div>
<p class="toast-title">${meta.title}</p>
<p class="toast-message"></p>
</div>
<button type="button" class="toast-close" aria-label="Dismiss notification">
×
</button>
`;
toast.querySelector('.toast-message').innerText = message;
toast.querySelector('.toast-close').addEventListener('click', () => removeNotification(toast));
container.appendChild(toast);
window.setTimeout(() => removeNotification(toast), duration);
}
function notify(message, type, duration) {
showNotification(message, type || inferNotificationType(message), duration);
}
window.alert = (message) => notify(message);
// Local Fallback State (when Supabase is not configured)
let localState = {
profile: {
age: 25,
weight: 70,
height: 175,
gender: 'male',
activity: '1.2',
fitnessGoal: 'maintain',
macroSplit: 'balanced',
customProtein: 25,
customCarbs: 45,
customFat: 30,
waterTarget: 2500
},
history: {} // Schema: { "YYYY-MM-DD": { loggedEntries: [], waterConsumed: 0 } }
};
// Active state for the currently loaded date
let dayState = {
loggedEntries: [],
waterConsumed: 0,
targets: {
calories: 2000,
macros: { protein: 125, carbs: 225, fat: 67 }
},
consumedTotals: {
calories: 0,
protein: 0,
carbs: 0,
fat: 0
}
};
// Initialize Application
window.addEventListener('DOMContentLoaded', async () => {
initDate();
await loadFoodDatabase();
initSupabase();
loadConfigUI();
// Setup event listeners for clicking outside autocomplete suggestions
document.addEventListener('click', (e) => {
const inputEl = document.getElementById('food-input');
const listEl = document.getElementById('autocomplete-list');
if (listEl && e.target !== inputEl && e.target !== listEl && !listEl.contains(e.target)) {
hideSuggestions();
}
});
// Check custom macros toggle onload
toggleCustomMacros();
});
// Setup Initial Date to Today
function initDate() {
const today = getLocalDateString(new Date());
currentSelectedDate = today;
const picker = document.getElementById('calendar-picker');
if (picker) {
picker.value = today;
picker.max = today; // Prevent logging in future (optional)
}
}
// Format date to local YYYY-MM-DD
function getLocalDateString(date) {
const offset = date.getTimezoneOffset();
const localDate = new Date(date.getTime() - (offset * 60 * 1000));
return localDate.toISOString().split('T')[0];
}
// Load Food Database from foodDB.json
async function loadFoodDatabase() {
try {
const response = await fetch('foodDB.json');
if (response.ok) {
foodDatabase = await response.json();
console.log('Loaded food database successfully.');
} else {
throw new Error('Fallback database used');
}
} catch (e) {
console.warn("Could not load foodDB.json, using local fallback DB", e);
// Minimum local fallback database
foodDatabase = {
'apple': { cal: 52, carbs: 14, protein: 0.3, fat: 0.2 },
'banana': { cal: 89, carbs: 23, protein: 1.1, fat: 0.3 },
'orange': { cal: 47, carbs: 12, protein: 0.9, fat: 0.1 },
'rice': { cal: 130, carbs: 28, protein: 2.7, fat: 0.3 },
'egg': { cal: 155, carbs: 1.1, protein: 13, fat: 11 },
'chicken breast': { cal: 165, carbs: 0, protein: 31, fat: 3.6 },
'oats': { cal: 389, carbs: 66, protein: 16.9, fat: 6.9 },
'milk': { cal: 42, carbs: 5, protein: 3.4, fat: 1 },
'paneer': { cal: 265, carbs: 1.2, protein: 18, fat: 20 },
'tofu': { cal: 76, carbs: 1.9, protein: 8, fat: 4.8 }
};
}
}
// Initialize Supabase Client
function initSupabase() {
const demoBadge = document.getElementById('demo-badge');
const loginBtn = document.getElementById('login-trigger-btn');
const userInfo = document.getElementById('user-info');
if (config.supabaseUrl && config.supabaseKey) {
try {
if (!window.supabase || !window.supabase.createClient) {
throw new Error("Supabase SDK is not loaded.");
}
supabaseClient = window.supabase.createClient(config.supabaseUrl, config.supabaseKey);
if (demoBadge) demoBadge.classList.add('hidden');
// Listen for authentication changes
supabaseClient.auth.onAuthStateChange((event, session) => {
if (session) {
currentUser = session.user;
const emailEl = document.getElementById('user-email');
if (emailEl) emailEl.innerText = currentUser.email;
if (userInfo) userInfo.classList.remove('hidden');
if (loginBtn) loginBtn.classList.add('hidden');
loadUserData();
} else {
currentUser = null;
if (userInfo) userInfo.classList.add('hidden');
if (loginBtn) loginBtn.classList.remove('hidden');
loadLocalFallbackData();
}
});
// Render immediately instead of relying only on the auth listener.
supabaseClient.auth.getSession()
.then(({ data, error }) => {
if (error) throw error;
const session = data?.session;
if (session) {
currentUser = session.user;
const emailEl = document.getElementById('user-email');
if (emailEl) emailEl.innerText = currentUser.email;
if (userInfo) userInfo.classList.remove('hidden');
if (loginBtn) loginBtn.classList.add('hidden');
loadUserData();
} else {
currentUser = null;
if (userInfo) userInfo.classList.add('hidden');
if (loginBtn) loginBtn.classList.remove('hidden');
loadLocalFallbackData();
}
})
.catch((err) => {
console.error("Supabase session check failed:", err);
setupLocalDemoMode(demoBadge, loginBtn, userInfo);
});
} catch (err) {
console.error("Supabase connection failed:", err);
setupLocalDemoMode(demoBadge, loginBtn, userInfo);
}
} else {
setupLocalDemoMode(demoBadge, loginBtn, userInfo);
}
}
// Helper to activate Local Fallback UI
function setupLocalDemoMode(demoBadge, loginBtn, userInfo) {
supabaseClient = null;
currentUser = null;
if (demoBadge) demoBadge.classList.remove('hidden');
if (loginBtn) loginBtn.classList.add('hidden');
if (userInfo) userInfo.classList.add('hidden');
loadLocalFallbackData();
}
// Load configurations into config modal inputs
function loadConfigUI() {
document.getElementById('supabase-url-input').value = config.supabaseUrl;
document.getElementById('supabase-key-input').value = config.supabaseKey;
document.getElementById('gemini-key-input').value = config.geminiKey;
}
// Open Config settings modal
function openConfigModal() {
document.getElementById('config-modal').classList.remove('hidden');
}
// Close Config settings modal
function closeConfigModal() {
document.getElementById('config-modal').classList.add('hidden');
}
// Save database & AI settings
function saveConfiguration() {
const url = document.getElementById('supabase-url-input').value.trim();
const key = document.getElementById('supabase-key-input').value.trim();
const gemini = document.getElementById('gemini-key-input').value.trim();
localStorage.setItem('np_supabase_url', url);
localStorage.setItem('np_supabase_key', key);
localStorage.setItem('np_gemini_key', gemini);
notify("Configuration saved. The application will reload to apply changes.", "success", 1800);
window.setTimeout(() => window.location.reload(), 900);
}
// ====================================================================
// AUTHENTICATION & OVERLAYS
// ====================================================================
let activeAuthTab = 'login';
function openAuthModal() {
document.getElementById('auth-modal').classList.remove('hidden');
switchAuthTab('login');
}
function closeAuthModal() {
document.getElementById('auth-modal').classList.add('hidden');
}
function switchAuthTab(tab) {
activeAuthTab = tab;
const loginTab = document.getElementById('auth-tab-login');
const signupTab = document.getElementById('auth-tab-signup');
const submitBtn = document.getElementById('auth-submit-btn');
const forgotLink = document.getElementById('forgot-password-link');
if (tab === 'login') {
loginTab.classList.add('active');
signupTab.classList.remove('active');
submitBtn.innerText = "Sign In";
forgotLink.classList.remove('hidden');
} else {
signupTab.classList.add('active');
loginTab.classList.remove('active');
submitBtn.innerText = "Register Account";
forgotLink.classList.add('hidden');
}
}
async function submitAuthForm() {
const email = document.getElementById('auth-email').value.trim();
const password = document.getElementById('auth-password').value.trim();
if (!email || !password) {
alert("Please fill in email and password fields.");
return;
}
if (!supabaseClient) {
alert("Please configure Supabase connection first.");
return;
}
try {
if (activeAuthTab === 'login') {
const { data, error } = await supabaseClient.auth.signInWithPassword({ email, password });
if (error) throw error;
closeAuthModal();
} else {
const { data, error } = await supabaseClient.auth.signUp({ email, password });
if (error) throw error;
alert("Sign up successful! Please check your email for confirmation link.");
closeAuthModal();
}
} catch (err) {
alert("Authentication Error: " + err.message);
}
}
async function handleLogout() {
if (supabaseClient) {
await supabaseClient.auth.signOut();
window.location.reload();
}
}
function handleForgotPassword() {
const email = document.getElementById('auth-email').value.trim();
if (!email) {
alert("Please enter your email address to reset password.");
return;
}
if (supabaseClient) {
supabaseClient.auth.resetPasswordForEmail(email)
.then(({ error }) => {
if (error) throw error;
alert("Password reset email sent!");
})
.catch(err => alert(err.message));
}
}
// ====================================================================
// CORE DATA LOADERS & CALCULATIONS
// ====================================================================
// Fetch user data from Supabase DB
async function loadUserData() {
if (!supabaseClient || !currentUser) return;
try {
// 1. Fetch Profile
let { data: profile, error: pError } = await supabaseClient
.from('profiles')
.select('*')
.eq('user_id', currentUser.id)
.maybeSingle();
if (pError) throw pError;
// Fallback or Trigger safeguard: Insert default profile row if not present
if (!profile) {
const defaultProfile = {
user_id: currentUser.id,
age: 25,
weight: 70,
height: 175,
gender: 'male',
activity_level: 1.2,
fitness_goal: 'maintain',
macro_split: 'balanced',
water_target: 2500
};
const { data: newProfile, error: insError } = await supabaseClient
.from('profiles')
.insert([defaultProfile])
.select()
.single();
if (insError) throw insError;
profile = newProfile;
}
// Set inputs
document.getElementById('age').value = profile.age;
document.getElementById('weight').value = profile.weight;
document.getElementById('height').value = profile.height;
document.getElementById('gender').value = profile.gender;
document.getElementById('activity').value = profile.activity_level.toString();
document.getElementById('fitness-goal').value = profile.fitness_goal;
document.getElementById('macro-split').value = profile.macro_split;
document.getElementById('custom-protein-pct').value = profile.custom_protein || 25;
document.getElementById('custom-carbs-pct').value = profile.custom_carbs || 45;
document.getElementById('custom-fat-pct').value = profile.custom_fat || 30;
document.getElementById('water-target-input').value = profile.water_target;
toggleCustomMacros();
// 2. Fetch logged data for the current date
const dateQuery = currentSelectedDate;
let { data: foodLogs, error: fError } = await supabaseClient
.from('food_logs')
.select('*')
.eq('user_id', currentUser.id)
.eq('log_date', dateQuery);
if (fError) throw fError;
let { data: waterLogs, error: wError } = await supabaseClient
.from('water_logs')
.select('*')
.eq('user_id', currentUser.id)
.eq('log_date', dateQuery);
if (wError) throw wError;
// Calculate water sums
const totalWater = waterLogs.reduce((sum, item) => sum + item.amount_ml, 0);
// Load into State
dayState.loggedEntries = foodLogs.map(item => ({
id: item.id,
name: item.food_name,
qty: parseFloat(item.quantity_grams),
cal: item.calories,
protein: parseFloat(item.protein),
carbs: parseFloat(item.carbs),
fat: parseFloat(item.fat),
mealType: item.meal_type
}));
dayState.waterConsumed = totalWater;
calculateTargetNutrition(profile);
recalculateTotals();
refreshUI();
} catch (err) {
console.error("Error loading user data:", err);
}
}
// Load data in Local Fallback mode
function loadLocalFallbackData() {
const saved = localStorage.getItem('FitentLocalState');
if (saved) {
try {
localState = JSON.parse(saved);
} catch (e) {
console.error("Local data corrupted, resetting");
}
}
// Safeguard profile and history structures
if (!localState) {
localState = {};
}
if (!localState.profile) {
localState.profile = {
age: 25,
weight: 70,
height: 175,
gender: 'male',
activity: '1.2',
fitnessGoal: 'maintain',
macroSplit: 'balanced',
customProtein: 25,
customCarbs: 45,
customFat: 30,
waterTarget: 2500
};
}
if (!localState.history) {
localState.history = {};
}
// Populate inputs from localState
document.getElementById('age').value = localState.profile.age || 25;
document.getElementById('weight').value = localState.profile.weight || 70;
document.getElementById('height').value = localState.profile.height || 175;
document.getElementById('gender').value = localState.profile.gender || 'male';
document.getElementById('activity').value = localState.profile.activity || '1.2';
document.getElementById('fitness-goal').value = localState.profile.fitnessGoal || 'maintain';
document.getElementById('macro-split').value = localState.profile.macroSplit || 'balanced';
document.getElementById('custom-protein-pct').value = localState.profile.customProtein || 25;
document.getElementById('custom-carbs-pct').value = localState.profile.customCarbs || 45;
document.getElementById('custom-fat-pct').value = localState.profile.customFat || 30;
document.getElementById('water-target-input').value = localState.profile.waterTarget || 2500;
toggleCustomMacros();
// Retrieve selected day details
const dayData = localState.history[currentSelectedDate] || { loggedEntries: [], waterConsumed: 0 };
dayState.loggedEntries = dayData.loggedEntries || [];
dayState.waterConsumed = dayData.waterConsumed || 0;
calculateTargetNutrition(localState.profile);
recalculateTotals();
refreshUI();
}
// Calculate target Calorie & Macros split
function calculateTargetNutrition(profile) {
const age = parseFloat(profile.age || profile.age_level);
const weight = parseFloat(profile.weight);
const height = parseFloat(profile.height);
const gender = profile.gender;
// Activity level maps differently depending on key formats
const activity = parseFloat(profile.activity_level || profile.activity || 1.2);
const goal = profile.fitness_goal || profile.fitnessGoal || 'maintain';
const splitType = profile.macro_split || profile.macroSplit || 'balanced';
if (age && weight && height) {
// Mifflin-St Jeor Equation
let bmr = 0;
if (gender === 'female') {
bmr = 10 * weight + 6.25 * height - 5 * age - 161;
} else {
bmr = 10 * weight + 6.25 * height - 5 * age + 5;
}
// TDEE
let tdee = Math.round(bmr * activity);
// Adjust based on goal
if (goal === 'lose') {
dayState.targets.calories = Math.max(1200, tdee - 500); // 1200 kcal floor safety limit
} else if (goal === 'gain') {
dayState.targets.calories = tdee + 300;
} else {
dayState.targets.calories = tdee;
}
// Select splits: Protein (4 kcal/g), Carbs (4 kcal/g), Fats (9 kcal/g)
let cp = 25, cc = 45, cf = 30;
if (splitType === 'lowcarb') {
cp = 40; cc = 15; cf = 45;
} else if (splitType === 'highprotein') {
cp = 40; cc = 35; cf = 25;
} else if (splitType === 'custom') {
cp = parseFloat(profile.custom_protein || profile.customProtein || 25);
cc = parseFloat(profile.custom_carbs || profile.customCarbs || 45);
cf = parseFloat(profile.custom_fat || profile.customFat || 30);
// Total sanitization check (must equal 100%)
if (cp + cc + cf !== 100) {
// Adjust balanced default
cp = 25; cc = 45; cf = 30;
}
}
dayState.targets.macros.protein = Math.round((dayState.targets.calories * (cp / 100)) / 4);
dayState.targets.macros.carbs = Math.round((dayState.targets.calories * (cc / 100)) / 4);
dayState.targets.macros.fat = Math.round((dayState.targets.calories * (cf / 100)) / 9);
dayState.targets.waterTarget = parseInt(profile.water_target || profile.waterTarget || 2500);
}
}
// Update settings values from DOM input to DB/Storage
async function updateProfileSettings() {
const age = parseInt(document.getElementById('age').value);
const weight = parseFloat(document.getElementById('weight').value);
const height = parseFloat(document.getElementById('height').value);
const gender = document.getElementById('gender').value;
const activity = parseFloat(document.getElementById('activity').value);
const fitnessGoal = document.getElementById('fitness-goal').value;
const macroSplit = document.getElementById('macro-split').value;
const customProtein = parseInt(document.getElementById('custom-protein-pct').value);
const customCarbs = parseInt(document.getElementById('custom-carbs-pct').value);
const customFat = parseInt(document.getElementById('custom-fat-pct').value);
const waterTarget = parseInt(document.getElementById('water-target-input').value);
// Validation limits
if (!age || age < 1 || age > 120) return alert("Please enter a valid age.");
if (!weight || weight < 10 || weight > 300) return alert("Please enter a valid weight (10kg - 300kg).");
if (!height || height < 50 || height > 280) return alert("Please enter a valid height (50cm - 280cm).");
if (macroSplit === 'custom' && (customProtein + customCarbs + customFat !== 100)) {
return alert("Custom macro percentages must add up to exactly 100%. (Currently: " + (customProtein + customCarbs + customFat) + "%)");
}
if (currentUser && supabaseClient) {
try {
const { error } = await supabaseClient
.from('profiles')
.update({
age,
weight,
height,
gender,
activity_level: activity,
fitness_goal: fitnessGoal,
macro_split: macroSplit,
custom_protein: customProtein,
custom_carbs: customCarbs,
custom_fat: customFat,
water_target: waterTarget,
updated_at: new Date()
})
.eq('user_id', currentUser.id);
if (error) throw error;
alert("Goal details successfully synchronized to online database!");
await loadUserData();
} catch (err) {
alert("Database Error: " + err.message);
}
} else {
// Update Local Fallback state
localState.profile = {
age, weight, height, gender,
activity: activity.toString(),
fitnessGoal, macroSplit,
customProtein, customCarbs, customFat,
waterTarget
};
saveLocalState();
loadLocalFallbackData();
alert("Goals updated locally!");
}
}
// Local Fallback Storage Saver
function saveLocalState() {
// Sync current dayState logs back to localState history
if (!localState) {
localState = {};
}
if (!localState.history) {
localState.history = {};
}
localState.history[currentSelectedDate] = {
loggedEntries: dayState.loggedEntries,
waterConsumed: dayState.waterConsumed
};
localStorage.setItem('FitentLocalState', JSON.stringify(localState));
}
// Toggle Custom macros panel visibility
function toggleCustomMacros() {
const macroVal = document.getElementById('macro-split').value;
const customPanel = document.getElementById('custom-macros-row');
if (macroVal === 'custom') {
customPanel.classList.remove('hidden');
} else {
customPanel.classList.add('hidden');
}
}
// Toggle sidebar section collapse
function toggleSection(sectionId) {
const el = document.getElementById(sectionId);
const arrow = document.getElementById(sectionId === 'profile-settings' ? 'profile-arrow' : '');
if (el.classList.contains('hidden')) {
el.classList.remove('hidden');
if (arrow) arrow.style.transform = 'rotate(0deg)';
} else {
el.classList.add('hidden');
if (arrow) arrow.style.transform = 'rotate(180deg)';
}
}
// Recalculate logged macros and calories summation
function recalculateTotals() {
dayState.consumedTotals.calories = 0;
dayState.consumedTotals.protein = 0;
dayState.consumedTotals.carbs = 0;
dayState.consumedTotals.fat = 0;
dayState.loggedEntries.forEach(entry => {
const normalized = normalizeEntry(entry);
dayState.consumedTotals.calories += normalized.calories;
dayState.consumedTotals.protein += normalized.protein;
dayState.consumedTotals.carbs += normalized.carbs;
dayState.consumedTotals.fat += normalized.fats;
});
// Rounding decimals
dayState.consumedTotals.protein = Math.round(dayState.consumedTotals.protein * 10) / 10;
dayState.consumedTotals.carbs = Math.round(dayState.consumedTotals.carbs * 10) / 10;
dayState.consumedTotals.fat = Math.round(dayState.consumedTotals.fat * 10) / 10;
}
// ====================================================================
// FOOD LOGGING LOGIC
// ====================================================================
let activeLoggingMealType = 'breakfast';
let editingEntryId = null;
function openAddFoodModal(mealType = 'breakfast') {
activeLoggingMealType = mealType || 'breakfast';
document.getElementById('food-meal-type').value = activeLoggingMealType;
document.getElementById('add-food-modal').classList.remove('hidden');
document.body.classList.add('drawer-open');
document.getElementById('food-input').focus();
}
function closeAddFoodModal() {
document.getElementById('add-food-modal').classList.add('hidden');
document.body.classList.remove('drawer-open');
editingEntryId = null;
// Clear fields
document.getElementById('food-input').value = '';
document.getElementById('qty-input').value = '';
document.getElementById('manual-cal').value = '';
document.getElementById('manual-protein').value = '';
document.getElementById('manual-carbs').value = '';
document.getElementById('manual-fat').value = '';
const toggle = document.getElementById('toggle-manual-nutrients');
if (toggle.checked) {
toggle.checked = false;
toggleManualNutritionFields();
}
}
function normalizeEntry(entry) {
return {
id: entry.id,
category: entry.category || entry.mealType || 'snack',
foodName: entry.foodName || entry.name || 'Food item',
quantity: parseFloat(entry.quantity || entry.qty || 100),
calories: Math.round(parseFloat(entry.calories ?? entry.cal ?? 0)),
protein: Math.round((parseFloat(entry.protein || 0)) * 10) / 10,
carbs: Math.round((parseFloat(entry.carbs || 0)) * 10) / 10,
fats: Math.round((parseFloat(entry.fats ?? entry.fat ?? 0)) * 10) / 10,
createdAt: entry.createdAt || entry.created_at || entry.id || new Date().toISOString()
};
}
function toStoredEntry(entry) {
return {
id: entry.id,
category: entry.category,
foodName: entry.foodName,
quantity: entry.quantity,
calories: entry.calories,
protein: entry.protein,
carbs: entry.carbs,
fats: entry.fats,
createdAt: entry.createdAt,
mealType: entry.category,
name: entry.foodName,
qty: entry.quantity,
cal: entry.calories,
fat: entry.fats
};
}
function toggleManualNutritionFields() {
const isChecked = document.getElementById('toggle-manual-nutrients').checked;
const manualFields = document.getElementById('manual-nutrient-fields');
if (isChecked) {
manualFields.classList.remove('hidden');
} else {
manualFields.classList.add('hidden');
}
}
// Autocomplete suggestions
function showSuggestions() {
const inputEl = document.getElementById('food-input');
const listEl = document.getElementById('autocomplete-list');
const query = inputEl.value.toLowerCase().trim();
if (!query) {
hideSuggestions();
return;
}
const matches = Object.keys(foodDatabase).filter(key => key.includes(query)).slice(0, 5);
if (matches.length === 0) {
hideSuggestions();
return;
}
listEl.innerHTML = '';
matches.forEach(match => {
const item = foodDatabase[match];
const div = document.createElement('div');
div.className = "suggestion-item";
div.innerHTML = `
<strong>${match}</strong>
<span>C:${item.carbs}g P:${item.protein}g F:${item.fat}g | ${item.cal} kcal/100g</span>
`;
div.addEventListener('click', () => {
inputEl.value = match;
hideSuggestions();
document.getElementById('qty-input').focus();
});
listEl.appendChild(div);
});
listEl.classList.remove('hidden');
}
function hideSuggestions() {
const listEl = document.getElementById('autocomplete-list');
if (listEl) listEl.classList.add('hidden');
}
// Log food entry (manual or autocomplete)
async function addEntry() {
const foodInput = document.getElementById('food-input');
const qtyInput = document.getElementById('qty-input');
const mealSelect = document.getElementById('food-meal-type');
const name = foodInput.value.trim();
const qty = parseFloat(qtyInput.value) || 100;
const mealType = mealSelect.value;
if (!name) return alert("Please enter a food item.");
let entryCal = 0, entryCarbs = 0, entryProtein = 0, entryFat = 0;
const manualToggle = document.getElementById('toggle-manual-nutrients').checked;
if (manualToggle) {
// Manual input values
entryCal = Math.round(parseFloat(document.getElementById('manual-cal').value) || 0);
entryProtein = Math.round((parseFloat(document.getElementById('manual-protein').value) || 0) * 10) / 10;
entryCarbs = Math.round((parseFloat(document.getElementById('manual-carbs').value) || 0) * 10) / 10;
entryFat = Math.round((parseFloat(document.getElementById('manual-fat').value) || 0) * 10) / 10;
} else {
// Database lookup
let baseInfo = foodDatabase[name.toLowerCase()];
if (!baseInfo) {
// General generic item fallback
baseInfo = { cal: 120, carbs: 12, protein: 8, fat: 4 };
}
const factor = qty / 100;
entryCal = Math.round(baseInfo.cal * factor);
entryCarbs = Math.round(baseInfo.carbs * factor * 10) / 10;
entryProtein = Math.round(baseInfo.protein * factor * 10) / 10;
entryFat = Math.round(baseInfo.fat * factor * 10) / 10;
}
if (editingEntryId) {
await saveEditedEntry(editingEntryId, {
name,
qty,
mealType,
cal: entryCal,
protein: entryProtein,
carbs: entryCarbs,
fat: entryFat
});
closeAddFoodModal();
return;
}
if (currentUser && supabaseClient) {
try {
const { data, error } = await supabaseClient
.from('food_logs')
.insert([{
user_id: currentUser.id,
log_date: currentSelectedDate,
meal_type: mealType,
food_name: name,
quantity_grams: qty,
calories: entryCal,
protein: entryProtein,
carbs: entryCarbs,
fat: entryFat
}])
.select();
if (error) throw error;
await loadUserData();
} catch (err) {
alert("Database Error: " + err.message);
}
} else {
// Local mode log addition
const newLocalEntry = {
id: Date.now().toString(),
category: mealType,
foodName: name,
quantity: qty,
calories: entryCal,
protein: entryProtein,
carbs: entryCarbs,
fats: entryFat,
createdAt: new Date().toISOString(),
name,
qty,
cal: entryCal,
fat: entryFat,
mealType
};
dayState.loggedEntries.push(newLocalEntry);
saveLocalState();
loadLocalFallbackData();
}
closeAddFoodModal();
}
// Edit Logged Entry Quantity
async function editEntry(id) {
const entry = dayState.loggedEntries.find(e => e.id === id);
if (!entry) return;
const normalized = normalizeEntry(entry);
editingEntryId = id;
openAddFoodModal(normalized.category);
document.getElementById('food-input').value = normalized.foodName;
document.getElementById('qty-input').value = normalized.quantity;
document.getElementById('manual-cal').value = normalized.calories;
document.getElementById('manual-protein').value = normalized.protein;
document.getElementById('manual-carbs').value = normalized.carbs;
document.getElementById('manual-fat').value = normalized.fats;
const toggle = document.getElementById('toggle-manual-nutrients');
toggle.checked = true;
toggleManualNutritionFields();
}
async function saveEditedEntry(id, updatedEntry) {
const newQty = parseFloat(updatedEntry.qty);
if (isNaN(newQty) || newQty <= 0) {
return alert("Please enter a valid positive number.");
}
// Lookup base factors
const entryCal = updatedEntry.cal;
const entryCarbs = updatedEntry.carbs;
const entryProtein = updatedEntry.protein;
const entryFat = updatedEntry.fat;
if (currentUser && supabaseClient) {
try {
const { error } = await supabaseClient
.from('food_logs')
.update({
meal_type: updatedEntry.mealType,
food_name: updatedEntry.name,
quantity_grams: newQty,
calories: entryCal,
protein: entryProtein,
carbs: entryCarbs,
fat: entryFat
})
.eq('id', id);
if (error) throw error;
await loadUserData();
} catch (err) {
alert("Database Update Error: " + err.message);
}
} else {
const entry = dayState.loggedEntries.find(e => e.id === id);
if (!entry) return;
entry.category = updatedEntry.mealType;
entry.foodName = updatedEntry.name;
entry.quantity = newQty;
entry.calories = entryCal;
entry.fats = entryFat;
entry.mealType = updatedEntry.mealType;
entry.name = updatedEntry.name;
entry.qty = newQty;
entry.cal = entryCal;
entry.carbs = entryCarbs;
entry.protein = entryProtein;
entry.fat = entryFat;
saveLocalState();
loadLocalFallbackData();
}
}
// Delete Logged Entry