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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52c05e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00b70a9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5304bf3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52c05e9
ed2b765
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056

// Pulse App Main JavaScript
class PulseApp {
    constructor() {
        this.currentPage = 'dashboard';
        this.isIFActive = false;
        this.ifTimer = null;
        this.ifStartTime = null;
        this.init();
    }

    init() {
        // Set current date
        this.updateDate();
        
        // Initialize navigation
        this.initNavigation();
        
        // Initialize IF timer
        this.initIFTimer();
        
        // Initialize page-specific features
        this.initMoodLogging();
        this.initNutritionTracking();
        this.initActivityTracking();
        this.initSleepTracking();
        
        // Simulate real-time data updates
        this.startRealTimeUpdates();
        
        // Initialize location services
        this.requestLocationPermission();
        
        // Check device capabilities
        this.checkDeviceCapabilities();
    }

    updateDate() {
        const date = new Date();
        const options = { day: 'numeric', month: 'short', year: 'numeric' };
        const thaiDate = date.toLocaleDateString('th-TH', options);
        const dateElement = document.getElementById('currentDate');
        if (dateElement) {
            dateElement.textContent = thaiDate;
        }
    }

    initNavigation() {
        // Set active navigation
        this.setActiveNav('dashboard');
    }

    setActiveNav(page) {
        const navButtons = document.querySelectorAll('.nav-btn');
        navButtons.forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.page === page) {
                btn.classList.add('active');
            }
        });
        
        // Hide all navigation items for special pages
        const specialPages = ['recovery', 'strain'];
        const nav = document.querySelector('nav.fixed.bottom-0');
        if (nav) {
            if (specialPages.includes(page)) {
                nav.classList.add('hidden');
            } else {
                nav.classList.remove('hidden');
            }
        }
    }

    // Initialize mood logging
    initMoodLogging() {
        const moodButtons = document.querySelectorAll('.mood-btn');
        moodButtons.forEach(btn => {
            btn.addEventListener('click', (e) => {
                moodButtons.forEach(b => b.classList.remove('selected'));
                btn.classList.add('selected');
                const mood = btn.querySelector('span:last-child').textContent;
                this.logMood(mood);
            });
        });
    }

    logMood(mood) {
        // Save mood to localStorage
        const today = new Date().toISOString().split('T')[0];
        const moodLog = JSON.parse(localStorage.getItem('moodLog') || '{}');
        moodLog[today] = {
            mood: mood,
            timestamp: new Date().toISOString(),
            factors: this.getSelectedStressFactors()
        };
        localStorage.setItem('moodLog', JSON.stringify(moodLog));
        
        this.showNotification(`บันทึกอารมณ์: ${mood}`);
    }

    getSelectedStressFactors() {
        const checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
        return Array.from(checkboxes).map(cb => {
            const label = cb.parentElement.querySelector('span');
            return label ? label.textContent : '';
        }).filter(text => text);
    }

    // Initialize nutrition tracking
    initNutritionTracking() {
        this.updateNutritionDisplay();
        this.loadRecentMeals();
    }

    updateNutritionDisplay() {
        const today = new Date().toISOString().split('T')[0];
        const nutritionData = JSON.parse(localStorage.getItem('nutritionData') || '{}');
        
        if (nutritionData[today]) {
            const data = nutritionData[today];
            const caloriesElement = document.querySelector('.nutrition-calories');
            const carbsElement = document.querySelector('.nutrition-carbs');
            const proteinElement = document.querySelector('.nutrition-protein');
            
            if (caloriesElement) caloriesElement.textContent = data.calories || 0;
            if (carbsElement) carbsElement.textContent = (data.carbs || 0) + 'g';
            if (proteinElement) proteinElement.textContent = (data.protein || 0) + 'g';
        }
    }

    loadRecentMeals() {
        const today = new Date().toISOString().split('T')[0];
        const mealsData = JSON.parse(localStorage.getItem('mealsData') || '{}');
        
        if (mealsData[today]) {
            const recentMeals = mealsData[today].slice(-3);
            // Update recent meals display
            this.displayRecentMeals(recentMeals);
        }
    }

    displayRecentMeals(meals) {
        const recentMealsContainer = document.querySelector('#nutrition .space-y-3');
        if (!recentMealsContainer) return;
        
        let mealsHTML = '';
        meals.forEach(meal => {
            mealsHTML += `
                <div class="bg-white rounded-xl p-3 shadow-sm border border-gray-100">
                    <div class="flex items-center justify-between">
                        <div>
                            <p class="font-semibold text-sm">${meal.name}</p>
                            <p class="text-xs text-gray-500">แคลอรี่: ${meal.calories} kcal</p>
                        </div>
                        <span class="text-xs text-gray-400">${meal.time}</span>
                    </div>
                </div>
            `;
        });
        
        if (mealsHTML) {
            recentMealsContainer.innerHTML = mealsHTML;
        }
    }

    // Initialize activity tracking
    initActivityTracking() {
        this.updateActivityDisplay();
        this.loadThaiActivities();
    }

    updateActivityDisplay() {
        const today = new Date().toISOString().split('T')[0];
        const activityData = JSON.parse(localStorage.getItem('activityData') || '{}');
        
        if (activityData[today]) {
            const data = activityData[today];
            // Update strain display
            const strainElements = document.querySelectorAll('.strain-score');
            strainElements.forEach(el => {
                if (el) el.textContent = data.strain || '0.0';
            });
        }
    }

    loadThaiActivities() {
        // Thai activity database
        const thaiActivities = [
            { name: 'มวยไทย', strain: 9.5, duration: 60, icon: '🥊' },
            { name: 'นั่งสมาธิ', strain: 1.5, duration: 30, icon: '🧘' },
            { name: 'เดินจงกรม', strain: 2.0, duration: 45, icon: '🚶' },
            { name: 'แบดมินตัน', strain: 7.0, duration: 90, icon: '🏸' },
            { name: 'เวทเทรนนิ่ง', strain: 8.0, duration: 75, icon: '🏋️' },
            { name: 'สวดมนต์', strain: 1.0, duration: 20, icon: '📿' }
        ];
        
        // Update activity buttons with Thai activities
        const activityButtons = document.querySelectorAll('#activity .grid button');
        thaiActivities.forEach((activity, index) => {
            if (activityButtons[index]) {
                activityButtons[index].addEventListener('click', () => {
                    this.startActivity(activity);
                });
            }
        });
    }

    startActivity(activity) {
        const confirmation = confirm(`เริ่ม ${activity.name}?\nระยะเวลา: ${activity.duration} นาที\nStrain: ${activity.strain}`);
        if (confirmation) {
            this.showNotification(`เริ่ม ${activity.name}!`);
            // Save activity start
            this.saveActivityStart(activity);
        }
    }

    saveActivityStart(activity) {
        const today = new Date().toISOString().split('T')[0];
        const activityData = JSON.parse(localStorage.getItem('activityData') || '{}');
        
        if (!activityData[today]) {
            activityData[today] = {
                activities: [],
                totalStrain: 0,
                startTime: new Date().toISOString()
            };
        }
        
        activityData[today].activities.push({
            ...activity,
            startTime: new Date().toISOString()
        });
        
        localStorage.setItem('activityData', JSON.stringify(activityData));
    }

    // Initialize sleep tracking
    initSleepTracking() {
        this.updateSleepDisplay();
        this.loadSleepInsights();
    }

    updateSleepDisplay() {
        const lastNight = this.getLastSleepDate();
        const sleepData = JSON.parse(localStorage.getItem('sleepData') || '{}');
        
        if (sleepData[lastNight]) {
            const data = sleepData[lastNight];
            // Update sleep score
            const sleepScoreElements = document.querySelectorAll('.sleep-score');
            sleepScoreElements.forEach(el => {
                if (el) el.textContent = data.performance + '%';
            });
            
            // Update sleep duration
            const durationElements = document.querySelectorAll('.sleep-duration');
            durationElements.forEach(el => {
                if (el) {
                    const hours = Math.floor(data.duration / 60);
                    const minutes = data.duration % 60;
                    el.textContent = `${hours}ชม ${minutes}นาที`;
                }
            });
        }
    }

    getLastSleepDate() {
        const now = new Date();
        const yesterday = new Date(now);
        yesterday.setDate(yesterday.getDate() - 1);
        return yesterday.toISOString().split('T')[0];
    }

    loadSleepInsights() {
        const insights = [
            'Deep Sleep เพิ่มขึ้น 20% หลังงดกินกาแฟหลังบ่าย',
            'ความสม่ำเสมอดีขึ้น 88% จากสัปดาห์ที่แล้ว 75%',
            'ควรรักษาเวลานอนที่ 22:00-06:00 ต่อเนื่อง',
            'อุณหภูมิห้องเหมาะสมที่ 22-24°C ช่วยให้นอนหลับลึกขึ้น'
        ];
        
        // Display random insight
        const insightElement = document.querySelector('.sleep-insights ul');
        if (insightElement) {
            const randomInsight = insights[Math.floor(Math.random() * insights.length)];
            insightElement.innerHTML = `<li>• ${randomInsight}</li>`;
        }
    }

    showPage(page) {
        // Hide all sections
        document.querySelectorAll('.page-section').forEach(section => {
            section.classList.add('hidden');
        });
        
        // Show selected section
        const targetSection = document.getElementById(page);
        if (targetSection) {
            targetSection.classList.remove('hidden');
            this.currentPage = page;
            this.setActiveNav(page);
            
            // Scroll to top
            window.scrollTo({ top: 0, behavior: 'smooth' });
            
            // Re-initialize icons for new content
            if (typeof feather !== 'undefined') {
                feather.replace();
            }
        }
    }
    // IF (Intermittent Fasting) Properties
    ifType = '16:8';
    isIFPaused = false;
    ifPausedTime = 0;
    ifTotalDuration = 16 * 60 * 60 * 1000; // 16 hours in milliseconds
    ifEatingWindow = 8 * 60 * 60 * 1000; // 8 hours in milliseconds

    initIFTimer() {
        // Check if IF was active before
        const ifState = localStorage.getItem('ifState');
        if (ifState === 'active' || ifState === 'paused') {
            const startTime = localStorage.getItem('ifStartTime');
            const ifType = localStorage.getItem('ifType') || '16:8';
            const ifPausedTime = localStorage.getItem('ifPausedTime') || 0;
            
            if (startTime) {
                this.ifType = ifType;
                this.ifPausedTime = parseInt(ifPausedTime);
                this.updateIFConfiguration();
                
                if (ifState === 'paused') {
                    this.isIFPaused = true;
                    this.showPausedIF();
                } else {
                    this.startIF(new Date(startTime));
                }
            }
        }
    }

    updateIFConfiguration() {
        const configs = {
            '16:8': { fast: 16, eat: 8, difficulty: 'ง่าย', difficultyColor: 'green', difficultyPercent: 20 },
            '18:6': { fast: 18, eat: 6, difficulty: 'ปานกลาง', difficultyColor: 'yellow', difficultyPercent: 40 },
            '20:4': { fast: 20, eat: 4, difficulty: 'ยาก', difficultyColor: 'orange', difficultyPercent: 60 },
            'eat-stop-eat': { fast: 24, eat: 0, difficulty: 'ยากมาก', difficultyColor: 'red', difficultyPercent: 80 },
            '5:2': { fast: 0, eat: 0, difficulty: 'พิเศษ', difficultyColor: 'purple', difficultyPercent: 100 }
        };

        const config = configs[this.ifType];
        if (config) {
            this.ifTotalDuration = config.fast * 60 * 60 * 1000;
            this.ifEatingWindow = config.eat * 60 * 60 * 1000;
            
            // Update UI
            const difficultyLevel = document.getElementById('difficultyLevel');
            const difficultyBar = document.getElementById('difficultyBar');
            const ifPhase = document.getElementById('ifPhase');
            
            if (difficultyLevel) {
                difficultyLevel.textContent = config.difficulty;
                difficultyLevel.className = `font-semibold text-${config.difficultyColor}-600`;
            }
            
            if (difficultyBar) {
                difficultyBar.className = `bg-${config.difficultyColor}-500 h-2 rounded-full transition-all duration-300`;
                difficultyBar.style.width = `${config.difficultyPercent}%`;
            }
            
            if (ifPhase) {
                if (this.ifType === '5:2') {
                    ifPhase.textContent = 'ลดแคลอรี่ 500-600 กิโลแคลอรี ในวันที่ไม่ทาน';
                } else {
                    ifPhase.textContent = `กำหนดการ: งดอาหาร ${config.fast} ชั่วโมง`;
                }
            }
            
            this.updateIFGuide();
        }
    }

    updateIFGuide() {
        const guides = {
            '16:8': {
                title: '16:8 คืออะไร?',
                content: [
                    '• งดอาหาร 16 ชั่วโมง',
                    '• กินอาหารได้ 8 ชั่วโมง',
                    '• เหมาะสำหรับผู้เริ่มต้น',
                    '• ช่วยลดน้ำหนัก 2-4 กิโล/เดือน'
                ],
                tips: [
                    '• เริ่มจาก 12:12 แล้วค่อยๆ เพิ่มเวลา',
                    '• ดื่มน้ำมากๆ ในช่วงงดอาหาร',
                    '• กินอาหารสมดุลในช่วง 8 ชั่วโมง'
                ]
            },
            '18:6': {
                title: '18:6 คืออะไร?',
                content: [
                    '• งดอาหาร 18 ชั่วโมง',
                    '• กินอาหารได้ 6 ชั่วโมง',
                    '• ผลลัพธ์เร็วกว่า 16:8',
                    '• ช่วยลดน้ำหนัก 3-5 กิโล/เดือน'
                ],
                tips: [
                    '• ควรทำ 16:8 มา 2-3 สัปดาห์ก่อน',
                    '• เลือกช่วงเวลาที่สะดวก (เช่น 12:00-18:00)',
                    '• ระวังอาการหิวในช่วงแรกๆ'
                ]
            },
            '20:4': {
                title: '20:4 (Warrior Diet) คืออะไร?',
                content: [
                    '• งดอาหาร 20 ชั่วโมง',
                    '• กินอาหารได้ 4 ชั่วโมง',
                    '• ผลลัพธ์รวดเร็วมาก',
                    '• ช่วยลดน้ำหนัก 4-6 กิโล/เดือน'
                ],
                tips: [
                    '• เหมาะสำหรับคนที่มีประสบการณ์ IF แล้ว',
                    '• ดื่มน้ำเกลือแร่เพื่อป้องกันภาวะขาดน้ำ',
                    '• วางแผนมื้ออาหารให้ดีในช่วง 4 ชั่วโมง'
                ]
            },
            'eat-stop-eat': {
                title: 'Eat-Stop-Eat คืออะไร?',
                content: [
                    '• งดอาหาร 24 ชั่วโมง',
                    '• ทำ 1-2 ครั้งต่อสัปดาห์',
                    '• ในวันอื่นกินตามปกติ',
                    '• ช่วยลดน้ำหนัก 1-2 กิโล/สัปดาห์'
                ],
                tips: [
                    '• เริ่มจาก 1 ครั้งต่อสัปดาห์ก่อน',
                    '• งดในวันที่ไม่มีกิจกรรมมาก',
                    '• ดื่มน้ำ ชา กาแฟดำ ได้'
                ]
            },
            '5:2': {
                title: '5:2 Diet คืออะไร?',
                content: [
                    '• กินตามปกติ 5 วัน',
                    '• ลดแคลอรี่เหลือ 500-600 ใน 2 วัน',
                    '• ไม่ต้องงดอาหารสนิท',
                    '• ช่วยลดน้ำหนัก 2-3 กิโล/เดือน'
                ],
                tips: [
                    '• เลือกวันที่สะดวก (เช่น อังคาร-ศุกร์)',
                    '• แบ่งแคลอรี่เป็น 2-3 มื้อเล็กๆ',
                    '• กินอาหารโปรตีนสูงในวันลดแคล'
                ]
            }
        };

        const guide = guides[this.ifType];
        if (guide) {
            const guideContent = document.getElementById('ifGuideContent');
            if (guideContent) {
                let html = `<p><strong>${guide.title}</strong></p>`;
                guide.content.forEach(line => {
                    html += `<p>${line}</p>`;
                });
                html += `<p class="mt-3"><strong>เคล็ดลับ:</strong></p>`;
                guide.tips.forEach(tip => {
                    html += `<p>${tip}</p>`;
                });
                guideContent.innerHTML = html;
            }
        }
    }

    changeIFType() {
        const select = document.getElementById('ifTypeSelect');
        if (select) {
            this.ifType = select.value;
            localStorage.setItem('ifType', this.ifType);
            this.updateIFConfiguration();
            
            // Update display
            const ifTypeDisplay = document.getElementById('ifTypeDisplay');
            if (ifTypeDisplay) {
                ifTypeDisplay.textContent = this.ifType;
            }
            
            // Reset IF if active
            if (this.isIFActive) {
                if (confirm('การเปลี่ยนประเภท IF จะรีเซ็ตการนับเวลา ต้องการเปลี่ยนหรือไม่?')) {
                    this.stopIF();
                } else {
                    // Revert selection
                    select.value = localStorage.getItem('ifType') || '16:8';
                }
            }
        }
    }

    startIF(startTime = new Date()) {
        this.isIFActive = true;
        this.isIFPaused = false;
        this.ifStartTime = startTime;
        this.ifPausedTime = 0;
        
        localStorage.setItem('ifState', 'active');
        localStorage.setItem('ifStartTime', startTime);
        localStorage.setItem('ifPausedTime', 0);
        localStorage.setItem('ifType', this.ifType);
        
        this.ifTimer = setInterval(() => {
            this.updateIFDisplay();
        }, 1000);
        
        this.updateIFDisplay();
        this.updateIFButtons('running');
        
        this.showNotification(`เริ่ม ${this.ifType} แล้ว! 💪`);
    }

    stopIF() {
        this.isIFActive = false;
        this.isIFPaused = false;
        clearInterval(this.ifTimer);
        
        localStorage.setItem('ifState', 'inactive');
        localStorage.removeItem('ifStartTime');
        localStorage.removeItem('ifPausedTime');
        
        this.updateIFDisplay();
        this.updateIFButtons('stopped');
        
        this.showNotification('หยุด IF แล้ว');
    }

    pauseIF() {
        if (!this.isIFActive || this.isIFPaused) return;
        
        this.isIFPaused = true;
        this.ifPausedTime = Date.now() - this.ifStartTime;
        
        localStorage.setItem('ifState', 'paused');
        localStorage.setItem('ifPausedTime', this.ifPausedTime);
        
        clearInterval(this.ifTimer);
        
        this.updateIFButtons('paused');
        this.showNotification('พัก IF ชั่วคราว');
    }

    resumeIF() {
        if (!this.isIFActive || !this.isIFPaused) return;
        
        this.isIFPaused = false;
        this.ifStartTime = new Date(Date.now() - this.ifPausedTime);
        
        localStorage.setItem('ifState', 'active');
        
        this.ifTimer = setInterval(() => {
            this.updateIFDisplay();
        }, 1000);
        
        this.updateIFButtons('running');
        this.showNotification('ทำ IF ต่อ');
    }

    updateIFDisplay() {
        const timerElement = document.getElementById('ifTimer');
        const statusElement = document.getElementById('ifStatus');
        const ifTypeDisplay = document.getElementById('ifTypeDisplay');
        
        if (ifTypeDisplay) {
            ifTypeDisplay.textContent = this.ifType;
        }
        
        if (!timerElement || !statusElement) return;
        
        if (!this.isIFActive) {
            timerElement.textContent = '--:--:--';
            statusElement.textContent = 'ยังไม่ได้เริ่ม';
            return;
        }
        
        if (this.isIFPaused) {
            const pausedDuration = this.ifPausedTime;
            const hours = Math.floor(pausedDuration / 3600000);
            const minutes = Math.floor((pausedDuration % 3600000) / 60000);
            const seconds = Math.floor((pausedDuration % 60000) / 1000);
            
            timerElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            statusElement.textContent = 'พักชั่วคราว';
            return;
        }
        
        const now = new Date();
        const diff = now - this.ifStartTime;
        const hours = Math.floor(diff / 3600000);
        const minutes = Math.floor((diff % 3600000) / 60000);
        const seconds = Math.floor((diff % 60000) / 1000);
        
        timerElement.textContent = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        
        // Calculate progress
        const fastHours = this.ifType === '5:2' ? 0 : parseInt(this.ifType.split(':')[0]);
        const totalDuration = fastHours * 60 * 60 * 1000;
        
        if (this.ifType !== '5:2') {
            const progress = (diff / totalDuration) * 100;
            
            if (progress >= 100) {
                statusElement.textContent = 'ครบกำหนดแล้ว! 🎉';
                this.completeIF();
            } else if (progress >= 75) {
                statusElement.textContent = 'ใกล้ครบแล้ว!';
            } else if (progress >= 50) {
                statusElement.textContent = 'ผ่านครึ่งทางแล้ว';
            } else if (progress >= 25) {
                statusElement.textContent = 'กำลังดำเนินการ';
            } else {
                statusElement.textContent = 'เริ่มต้น';
            }
        } else {
            statusElement.textContent = 'วันลดแคลอรี่';
        }
    }

    updateIFButtons(state) {
        const startBtn = document.getElementById('startIFBtn');
        const stopBtn = document.getElementById('stopIFBtn');
        const pauseBtn = document.getElementById('pauseIFBtn');
        const resumeBtn = document.getElementById('resumeIFBtn');
        
        // Hide all buttons first
        if (startBtn) startBtn.classList.add('hidden');
        if (stopBtn) stopBtn.classList.add('hidden');
        if (pauseBtn) pauseBtn.classList.add('hidden');
        if (resumeBtn) resumeBtn.classList.add('hidden');
        
        // Show buttons based on state
        switch(state) {
            case 'stopped':
                if (startBtn) startBtn.classList.remove('hidden');
                break;
            case 'running':
                if (stopBtn) stopBtn.classList.remove('hidden');
                if (pauseBtn) pauseBtn.classList.remove('hidden');
                break;
            case 'paused':
                if (stopBtn) stopBtn.classList.remove('hidden');
                if (resumeBtn) resumeBtn.classList.remove('hidden');
                break;
        }
    }

    showPausedIF() {
        this.updateIFDisplay();
        this.updateIFButtons('paused');
    }

    completeIF() {
        this.stopIF();
        
        // Save completion record
        const today = new Date().toISOString().split('T')[0];
        const ifHistory = JSON.parse(localStorage.getItem('ifHistory') || '{}');
        if (!ifHistory[today]) {
            ifHistory[today] = [];
        }
        ifHistory[today].push({
            type: this.ifType,
            completedAt: new Date().toISOString(),
            duration: this.ifTotalDuration
        });
        localStorage.setItem('ifHistory', JSON.stringify(ifHistory));
        
        this.showNotification('🎉 ทำ IF ครบกำหนดแล้ว! เยี่ยมมาก!');
        
        // Show achievement notification
        setTimeout(() => {
            this.showNotification('🏆 ได้รับความสำเร็จ: IF Warrior');
        }, 2000);
    }

    toggleIF() {
        if (this.isIFActive) {
            if (this.isIFPaused) {
                this.resumeIF();
            } else {
                this.pauseIF();
            }
        } else {
            this.startIF();
        }
    }
startRealTimeUpdates() {
        // Update vitals every minute
        setInterval(() => {
            this.updateVitals();
        }, 60000);
        
        // Update environmental data every 5 minutes
        setInterval(() => {
            this.updateEnvironmentalData();
        }, 300000);
    }

    updateVitals() {
        // Simulate HRV and other vital changes
        // In real app, this would fetch from HealthKit/Health Connect
        console.log('Updating vitals...');
    }

    async updateEnvironmentalData() {
        try {
            // Get user location
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(async (position) => {
                    const { latitude, longitude } = position.coords;
                    
                    // Fetch AQI data (using Thailand AQI API if available)
                    // This is a placeholder - replace with actual API
                    const aqiData = await this.fetchAQIData(latitude, longitude);
                    this.updateAQIDisplay(aqiData);
                    
                    // Fetch weather data
                    const weatherData = await this.fetchWeatherData(latitude, longitude);
                    this.updateWeatherDisplay(weatherData);
                    
                    // Fetch traffic data (for home/work routes)
                    const trafficData = await this.fetchTrafficData();
                    this.updateTrafficDisplay(trafficData);
                });
            }
        } catch (error) {
            console.error('Error updating environmental data:', error);
        }
    }

    async fetchAQIData(lat, lon) {
        // Placeholder for AQI API
        // In production, use GISTDA or other Thai AQI APIs
        return {
            pm25: 65,
            aqi: 102,
            quality: 'ปานกลาง'
        };
    }

    async fetchWeatherData(lat, lon) {
        // Placeholder for weather API
        // In production, use Thai Meteorological Department API
        return {
            temperature: 35,
            heatIndex: 39,
            uvIndex: 9,
            humidity: 75
        };
    }

    async fetchTrafficData() {
        // Placeholder for traffic API
        // In production, use Google Maps or Longdo Maps API
        return {
            status: 'ติดขัด',
            route: 'กลับบ้าน',
            delay: '45 นาที'
        };
    }

    updateAQIDisplay(data) {
        // Update AQI display in UI
        const aqiElements = document.querySelectorAll('[data-aqi]');
        aqiElements.forEach(el => {
            if (data.aqi > 100) {
                el.classList.add('text-red-600');
                el.classList.remove('text-green-600', 'text-yellow-600');
            } else if (data.aqi > 50) {
                el.classList.add('text-yellow-600');
                el.classList.remove('text-green-600', 'text-red-600');
            } else {
                el.classList.add('text-green-600');
                el.classList.remove('text-yellow-600', 'text-red-600');
            }
        });
    }

    updateWeatherDisplay(data) {
        // Update weather display in UI
        if (data.heatIndex > 37) {
            // Show heat warning
            this.showNotification('⚠️ คำเตือน: ดัชนีความร้อนสูง งดออกกำลังกายกลางแจ้ง');
        }
    }

    updateTrafficDisplay(data) {
        // Update traffic display in UI
        if (data.status === 'ติดขัดหนัก') {
            // Suggest stress management
            this.showNotification('🚗 รถติดหนัก ลองใช้ฟีเจอร์ฝึกหายใจก่อนถึงบ้านนะครับ');
        }
    }

    requestLocationPermission() {
        if ('geolocation' in navigator) {
            navigator.permissions.query({ name: 'geolocation' }).then((result) => {
                if (result.state === 'granted') {
                    console.log('Location permission granted');
                } else if (result.state === 'prompt') {
                    // User hasn't decided yet
                    console.log('Location permission not decided');
                } else {
                    // Permission denied
                    console.log('Location permission denied');
                    this.showNotification('📍 ต้องการอนุญาตตำแหน่งเพื่อแสดงข้อมูล AQI และสภาพอากาศ');
                }
            });
        }
    }

    checkDeviceCapabilities() {
        // Check if device supports HealthKit/Health Connect
        const supportsHealthKit = 'HealthKit' in window;
        const supportsHealthConnect = 'HealthConnect' in window;
        
        if (supportsHealthKit || supportsHealthConnect) {
            console.log('Device supports health data integration');
            // Initialize health data sync
            this.initHealthDataSync();
        } else {
            console.log('Device does not support health data integration');
            // Show alternative input methods
            this.showManualInputOptions();
        }
    }

    initHealthDataSync() {
        // Placeholder for health data integration
        // In production, integrate with HealthKit (iOS) or Health Connect (Android)
        console.log('Initializing health data sync...');
    }

    showManualInputOptions() {
        // Show manual input options for devices without health integration
        console.log('Showing manual input options...');
    }
    showNotification(message) {
        // Create notification element
        const notification = document.createElement('div');
        notification.className = 'fixed top-4 right-4 bg-white rounded-lg shadow-lg p-4 max-w-xs z-50 animate-pulse';
        notification.innerHTML = `
            <p class="text-sm font-medium text-gray-800">${message}</p>
        `;
        
        document.body.appendChild(notification);
        
        // Remove after 5 seconds
        setTimeout(() => {
            notification.remove();
        }, 5000);
    }

    // Modal functions
    showAirQualityModal() {
        document.getElementById('airQualityModal').classList.remove('hidden');
        feather.replace();
    }

    showHeatIndexModal() {
        document.getElementById('heatIndexModal').classList.remove('hidden');
        feather.replace();
    }

    showTrafficModal() {
        document.getElementById('trafficModal').classList.remove('hidden');
        feather.replace();
    }

    showUVIndexModal() {
        document.getElementById('uvIndexModal').classList.remove('hidden');
        feather.replace();
    }

    closeModal(modalId) {
        document.getElementById(modalId).classList.add('hidden');
    }

    updateAirQualityData() {
        const location = document.getElementById('airQualityLocation').value;
        console.log('Updating air quality data for:', location);
        // In real app, fetch new data based on location
        this.showNotification('อัพเดทข้อมูลคุณภาพอากาศ');
    }

    updateHeatIndexData() {
        const location = document.getElementById('heatIndexLocation').value;
        console.log('Updating heat index data for:', location);
        // In real app, fetch new data based on location
        this.showNotification('อัพเดทข้อมูลดัชนีความร้อน');
    }

    updateTrafficData() {
        const route = document.getElementById('trafficRoute').value;
        console.log('Updating traffic data for route:', route);
        // In real app, fetch new data based on route
        this.showNotification('อัพเดทข้อมูลการจราจร');
    }

    updateUVIndexData() {
        const location = document.getElementById('uvIndexLocation').value;
        console.log('Updating UV index data for:', location);
        // In real app, fetch new data based on location
        this.showNotification('อัพเดทข้อมูลดัชนี UV');
    }

    setAirQualityTimeRange(range) {
        // Update button states
        const buttons = document.querySelectorAll('#airQualityModal .flex button');
        buttons.forEach(btn => {
            btn.classList.remove('bg-primary-600', 'text-white');
            btn.classList.add('bg-gray-200', 'text-gray-700');
        });
        event.target.classList.remove('bg-gray-200', 'text-gray-700');
        event.target.classList.add('bg-primary-600', 'text-white');
        
        console.log('Setting air quality time range:', range);
        this.showNotification(`แสดงข้อมูล ${range === 'today' ? 'วันนี้' : range === 'week' ? '7 วัน' : '30 วัน'}`);
    }

    setTrafficTime(time) {
        // Update button states
        const buttons = document.querySelectorAll('#trafficModal .flex button');
        buttons.forEach(btn => {
            btn.classList.remove('bg-primary-600', 'text-white');
            btn.classList.add('bg-gray-200', 'text-gray-700');
        });
        event.target.classList.remove('bg-gray-200', 'text-gray-700');
        event.target.classList.add('bg-primary-600', 'text-white');
        
        console.log('Setting traffic time:', time);
        this.showNotification(`แสดงข้อมูลการจราจร ${time === 'now' ? 'ตอนนี้' : time === 'morning' ? 'ช่วงเช้า' : 'ช่วงเย็น'}`);
    }
// Thai food database helper
    searchThaiFood(query) {
        const thaiFoodDatabase = [
            { name: 'ข้าวมันไก่', calories: 450, protein: 30, carbs: 45, fat: 15 },
            { name: 'กะเพราไข่ดาว', calories: 520, protein: 25, carbs: 35, fat: 30 },
            { name: 'แกงเขียวหวาน', calories: 380, protein: 20, carbs: 25, fat: 22 },
            { name: 'ต้มยำกุ้ง', calories: 180, protein: 25, carbs: 10, fat: 5 },
            { name: 'ส้มตำไทย', calories: 120, protein: 3, carbs: 20, fat: 4 },
            { name: 'ขนมจีนน้ำยา', calories: 420, protein: 12, carbs: 65, fat: 15 },
            { name: 'ข้าวผัด', calories: 480, protein: 15, carbs: 70, fat: 15 },
            { name: 'มักกะโรนีผัด', calories: 550, protein: 18, carbs: 65, fat: 25 },
            { name: 'ชานมไข่มุก', calories: 320, protein: 8, carbs: 55, fat: 8 },
            { name: 'โอเลี้ยง', calories: 400, protein: 12, carbs: 50, fat: 18 }
        ];
        
        return thaiFoodDatabase.filter(food => 
            food.name.toLowerCase().includes(query.toLowerCase())
        );
    }

    // Activity detection
    detectActivity() {
        // Placeholder for activity detection
        // In production, use device sensors or manual input
        console.log('Detecting activity...');
    }

    // AI Coach insights generation
    generateAIInsight() {
        const insights = [
            'วันนี้ฝุ่นเยอะ Recovery 60% แนะนำออกกำลังในร่ม และทานอาหารต้านอักเสบเช่นขิง ข่า ตะไคร้',
            'เราสังเกตว่า HRV ลดลง 15% หลังจากวันที่ PM2.5 สูง ลองพักผ่อนมากขึ้นนะครับ',
            'การจราจรติดขัดเมื่อวานทำให้ HR สูงค้าง ลองใช้ฟีเจอร์ฝึกหายใจก่อนถึงบ้าน',
            'ดัชนีความร้อนสูง การวิ่งสร้าง Strain สูงกว่าปกติ 30% แนะนำให้ดื่มน้ำเกลือแร่'
        ];
        
        return insights[Math.floor(Math.random() * insights.length)];
    }
}

// Initialize app
const app = new PulseApp();
// Global functions for onclick handlers
function showPage(page) {
    app.showPage(page);
}

function toggleIF() {
    app.toggleIF();
}

function startIF() {
    app.startIF();
}

function stopIF() {
    app.stopIF();
}

function pauseIF() {
    app.pauseIF();
}

function resumeIF() {
    app.resumeIF();
}

function changeIFType() {
    app.changeIFType();
}
function showAirQualityModal() {
    app.showAirQualityModal();
}

function showHeatIndexModal() {
    app.showHeatIndexModal();
}

function showTrafficModal() {
    app.showTrafficModal();
}

function showUVIndexModal() {
    app.showUVIndexModal();
}

function closeModal(modalId) {
    app.closeModal(modalId);
}

function updateAirQualityData() {
    app.updateAirQualityData();
}

function updateHeatIndexData() {
    app.updateHeatIndexData();
}

function updateTrafficData() {
    app.updateTrafficData();
}

function updateUVIndexData() {
    app.updateUVIndexData();
}

function setAirQualityTimeRange(range) {
    app.setAirQualityTimeRange(range);
}

function setTrafficTime(time) {
    app.setTrafficTime(time);
}
// Add to global scope for component access
window.PulseApp = PulseApp;