← Kapat

calorie-calculator.js

// Kalori Hesaplayıcı JavaScript
document.addEventListener('DOMContentLoaded', function() {
    // Elements
    const genderBtns = document.querySelectorAll('.calorie-gender-btn');
    const weightSlider = document.getElementById('calorie-weightSlider');
    const weightInput = document.getElementById('calorie-weightInput');
    const heightSlider = document.getElementById('calorie-heightSlider');
    const heightInput = document.getElementById('calorie-heightInput');
    const ageSlider = document.getElementById('ageSlider');
    const ageInput = document.getElementById('ageInput');

    // Current values
    let currentGender = 'male';
    let currentWeight = 70;
    let currentHeight = 170;
    let currentAge = 30;
    let currentActivityLevel = 1.2;

    // Initialize
    init();

    function init() {
        setupEventListeners();
        calculateCalories();
    }

    function setupEventListeners() {
        // Gender selection
        genderBtns.forEach(btn => {
            btn.addEventListener('click', function() {
                genderBtns.forEach(b => b.classList.remove('active'));
                this.classList.add('active');
                currentGender = this.dataset.gender;
                calculateCalories();
            });
        });

        // Weight slider and input
        if (weightSlider && weightInput) {
            weightSlider.addEventListener('input', function() {
                currentWeight = parseInt(this.value);
                weightInput.value = currentWeight;
                updateSliderBackground(this);
                calculateCalories();
            });

            weightInput.addEventListener('input', function() {
                let value = parseInt(this.value);
                if (value >= 40 && value <= 200) {
                    currentWeight = value;
                    weightSlider.value = value;
                    updateSliderBackground(weightSlider);
                    calculateCalories();
                }
            });
        }

        // Height slider and input
        if (heightSlider && heightInput) {
            heightSlider.addEventListener('input', function() {
                currentHeight = parseInt(this.value);
                heightInput.value = currentHeight;
                updateSliderBackground(this);
                calculateCalories();
            });

            heightInput.addEventListener('input', function() {
                let value = parseInt(this.value);
                if (value >= 140 && value <= 220) {
                    currentHeight = value;
                    heightSlider.value = value;
                    updateSliderBackground(heightSlider);
                    calculateCalories();
                }
            });
        }

        // Age slider and input
        if (ageSlider && ageInput) {
            ageSlider.addEventListener('input', function() {
                currentAge = parseInt(this.value);
                ageInput.value = currentAge;
                updateSliderBackground(this);
                calculateCalories();
            });

            ageInput.addEventListener('input', function() {
                let value = parseInt(this.value);
                if (value >= 15 && value <= 80) {
                    currentAge = value;
                    ageSlider.value = value;
                    updateSliderBackground(ageSlider);
                    calculateCalories();
                }
            });
        }

        // Initialize slider backgrounds
        if (weightSlider) updateSliderBackground(weightSlider);
        if (heightSlider) updateSliderBackground(heightSlider);
        if (ageSlider) updateSliderBackground(ageSlider);
    }

    function updateSliderBackground(slider) {
        const min = parseFloat(slider.min);
        const max = parseFloat(slider.max);
        const value = parseFloat(slider.value);
        const percentage = ((value - min) / (max - min)) * 100;
        
        slider.style.background = `linear-gradient(to right, #ff8c00 0%, #ff8c00 ${percentage}%, #3f3f46 ${percentage}%, #3f3f46 100%)`;
    }

    
    // Cinsiyet seçimi (legacy function - kept for compatibility)
    window.calorieSelectGender = function(gender) {
        const buttons = document.querySelectorAll('.calorie-gender-btn');
        buttons.forEach(btn => {
            btn.classList.remove('active');
            if (btn.getAttribute('data-gender') === gender) {
                btn.classList.add('active');
            }
        });
        
        currentGender = gender;
        calculateCalories();
    };
    
    // Aktivite seviyesi seçimi
    window.selectActivity = function(level, button) {
        // Tüm butonlardan active class'ını kaldır
        const buttons = document.querySelectorAll('.activity-btn');
        buttons.forEach(btn => btn.classList.remove('active'));
        
        // Seçilen butona active class'ını ekle
        button.classList.add('active');
        
        currentActivityLevel = level;
        calculateCalories();
    };
    
    // Aktivite bilgilerini aç/kapat
    window.toggleActivityInfo = function(event, activityType) {
        // Event propagation'ı durdur (ana butona tıklama olayını engelle)
        event.stopPropagation();
        
        const examplesDiv = document.getElementById(`${activityType}-examples`);
        const activityItem = examplesDiv.closest('.activity-item');
        
        if (!examplesDiv || !activityItem) return;
        
        // Diğer açık olan bilgi kutularını kapat
        const allExamples = document.querySelectorAll('.activity-examples');
        const allItems = document.querySelectorAll('.activity-item');
        
        allExamples.forEach((example, index) => {
            if (example !== examplesDiv) {
                example.classList.remove('show');
                allItems[index].classList.remove('expanded');
            }
        });
        
        // Mevcut kutunun durumunu değiştir
        const isCurrentlyOpen = examplesDiv.classList.contains('show');
        
        if (isCurrentlyOpen) {
            examplesDiv.classList.remove('show');
            activityItem.classList.remove('expanded');
        } else {
            examplesDiv.classList.add('show');
            activityItem.classList.add('expanded');
        }
    };
    
    // Kalori hesaplama fonksiyonu
    function calculateCalories() {
        const bmr = calculateBMR();
        const tdee = bmr * currentActivityLevel;
        const weightLoss = tdee - 500; // 0.5 kg/hafta
        const weightGain = tdee + 500; // 0.5 kg/hafta
        
        // Sonuçları güncelle
        const tdeeElement = document.getElementById('tdee-result');
        const weightLossElement = document.getElementById('weight-loss-result');
        const weightGainElement = document.getElementById('weight-gain-result');
        
        if (tdeeElement) tdeeElement.textContent = Math.round(tdee);
        if (weightLossElement) weightLossElement.textContent = Math.round(weightLoss);
        if (weightGainElement) weightGainElement.textContent = Math.round(weightGain);
        
        // Makro besinleri güncelle
        updateMacroNutrients(tdee);
    }
    
    // Makro besin hesaplama ve güncelleme
    function updateMacroNutrients(tdee) {
        // Protein hesaplama (1.6-2.2g per kg body weight)
        const proteinMin = Math.round(currentWeight * 1.6);
        const proteinMax = Math.round(currentWeight * 2.2);
        
        // Karbonhidrat hesaplama (%40-60 of total calories)
        const carbMin = Math.round((tdee * 0.40) / 4); // 4 cal per gram
        const carbMax = Math.round((tdee * 0.60) / 4);
        
        // Yağ hesaplama (%20-35 of total calories)
        const fatMin = Math.round((tdee * 0.20) / 9); // 9 cal per gram
        const fatMax = Math.round((tdee * 0.35) / 9);
        
        // Su ihtiyacı (33ml per kg body weight)
        const waterNeeds = Math.round(currentWeight * 33);
        
        // HTML elementlerini güncelle
        updateMacroElements('protein', proteinMin, proteinMax, 'g');
        updateMacroElements('carb', carbMin, carbMax, 'g');
        updateMacroElements('fat', fatMin, fatMax, 'g');
        updateWaterNeeds(waterNeeds);
        
        // Öğün dağılımını güncelle
        updateMealDistribution(tdee);
    }
    
    // Makro besin elementlerini güncelle
    function updateMacroElements(type, min, max, unit) {
        // ID'leri kullanarak daha kesin güncelleme
        if (type === 'protein') {
            const proteinElement = document.getElementById('protein-recommendation');
            if (proteinElement) {
                proteinElement.textContent = `${min}${unit} - ${max}${unit}`;
            }
        }
        
        if (type === 'carb') {
            const carbElement = document.getElementById('carb-recommendation');
            if (carbElement) {
                carbElement.textContent = `${min}${unit} - ${max}${unit}`;
            }
        }
        
        if (type === 'fat') {
            const fatElement = document.getElementById('fat-recommendation');
            if (fatElement) {
                fatElement.textContent = `${min}${unit} - ${max}${unit}`;
            }
        }
    }
    
    // Su ihtiyacını güncelle
    function updateWaterNeeds(waterNeeds) {
        const waterElement = document.getElementById('water-needs');
        if (waterElement) {
            waterElement.textContent = `${waterNeeds} ml`;
        }
    }
    
    // Öğün dağılımını güncelle
    function updateMealDistribution(tdee) {
        // Kahvaltı %25-30
        const breakfastMin = Math.round(tdee * 0.25);
        const breakfastMax = Math.round(tdee * 0.30);
        
        // Öğle yemeği %30-35
        const lunchMin = Math.round(tdee * 0.30);
        const lunchMax = Math.round(tdee * 0.35);
        
        // Akşam yemeği %25-30
        const dinnerMin = Math.round(tdee * 0.25);
        const dinnerMax = Math.round(tdee * 0.30);
        
        // Ara öğünler %10-15
        const snackMin = Math.round(tdee * 0.10);
        const snackMax = Math.round(tdee * 0.15);
        
        // Öğün elementlerini güncelle
        updateMealElement('breakfast-calories', breakfastMin, breakfastMax);
        updateMealElement('lunch-calories', lunchMin, lunchMax);
        updateMealElement('dinner-calories', dinnerMin, dinnerMax);
        updateMealElement('snack-calories', snackMin, snackMax);
    }
    
    // Öğün elementini güncelle
    function updateMealElement(elementId, min, max) {
        const element = document.getElementById(elementId);
        if (element) {
            element.textContent = `${min} - ${max} kcal`;
        }
    }
    
    // BMR hesaplama (Mifflin-St Jeor denklemi)
    function calculateBMR() {
        if (currentGender === 'male') {
            return 10 * currentWeight + 6.25 * currentHeight - 5 * currentAge + 5;
        } else {
            return 10 * currentWeight + 6.25 * currentHeight - 5 * currentAge - 161;
        }
    }
    
    // Hata yakalama
    window.addEventListener('error', function(e) {
        console.warn('JavaScript hatası yakalandı:', e.error);
    });
});