Генератор Здорового Меню + Калькулятор Калорий
document.addEventListener('DOMContentLoaded', function() {
const meals = {
breakfast: [
{name: "Овсяная каша на воде", cal: 70, portion: 150},
{name: "Творог обезжиренный", cal: 86, portion: 150},
{name: "Яйцо вареное", cal: 155, portion: 50},
{name: "Греческий йогурт", cal: 59, portion: 150},
{name: "Банан", cal: 90, portion: 120},
{name: "Орехи миндаль", cal: 579, portion: 30},
{name: "Хлеб цельнозерновой", cal: 250, portion: 50},
{name: "Сыр твердый", cal: 330, portion: 30},
{name: "Яблоко", cal: 52, portion: 150},
{name: "Мюсли без сахара", cal: 350, portion: 50},
],
lunch: [
{name: "Куриная грудка отварная", cal: 165, portion: 150},
{name: "Гречка отварная", cal: 110, portion: 150},
{name: "Овощи тушеные", cal: 50, portion: 200},
{name: "Рыба запеченная", cal: 150, portion: 150},
{name: "Картофель отварной", cal: 90, portion: 150},
{name: "Бурый рис", cal: 111, portion: 150},
{name: "Брокколи", cal: 35, portion: 150},
{name: "Индейка на пару", cal: 150, portion: 150},
{name: "Тунец консервированный", cal: 144, portion: 100},
{name: "Фасоль отварная", cal: 127, portion: 150},
],
snack: [
{name: "Финики", cal: 277, portion: 30},
{name: "Орехи грецкие", cal: 654, portion: 30},
{name: "Протеиновый батончик", cal: 200, portion: 50},
{name: "Кефир 1%", cal: 40, portion: 200},
{name: "Миндаль", cal: 579, portion: 30},
{name: "Груша", cal: 57, portion: 150},
{name: "Чернослив", cal: 240, portion: 30},
{name: "Семечки тыквенные", cal: 446, portion: 30},
{name: "Творожная масса", cal: 140, portion: 100},
{name: "Йогурт натуральный", cal: 60, portion: 150},
],
dinner: [
{name: "Индейка на пару", cal: 150, portion: 150},
{name: "Овощной салат", cal: 40, portion: 200},
{name: "Рыба на пару", cal: 120, portion: 150},
{name: "Кабачки запеченные", cal: 20, portion: 150},
{name: "Сыр адыгейский", cal: 264, portion: 50},
{name: "Тофу", cal: 76, portion: 100},
{name: "Огурцы свежие", cal: 15, portion: 150},
{name: "Помидоры свежие", cal: 20, portion: 150},
{name: "Баклажаны тушеные", cal: 60, portion: 150},
{name: "Салат из шпината", cal: 23, portion: 150},
]
};
let customMeals = {
breakfast: [],
lunch: [],
snack: [],
dinner: []
};
function calculateCalories() {
let age = parseInt(document.getElementById('age').value);
let gender = document.getElementById('gender').value;
let goal = document.getElementById('goal').value;
let mealsCount = parseInt(document.getElementById('meals').value);
if (isNaN(age) || isNaN(mealsCount)) {
alert('Заполните все поля.');
return;
}
let baseCalories = gender === 'male' ? 2500 : 2000;
if (age > 50) baseCalories *= 0.9;
if (goal === 'lose') baseCalories *= 0.8;
if (goal === 'gain') baseCalories *= 1.2;
let caloriesPerMeal = baseCalories / mealsCount;
document.getElementById('result').innerHTML = `Ваша суточная норма:
${baseCalories.toFixed(0)} ккал (${caloriesPerMeal.toFixed(0)} ккал за один прием пищи)`;
}
function generateMenu() {
const type = document.getElementById('mealType').value;
const calories = parseInt(document.getElementById('caloriesInput').value);
const list = document.getElementById('menuList');
if (isNaN(calories)) {
alert('Введите калории!');
return;
}
let options = [...meals[type], ...customMeals[type]];
options = options.sort(() => 0.5 - Math.random());
let selected = [], total = 0;
for (let item of options) {
const itemCal = item.cal * item.portion / 100;
if (total + itemCal <= calories * 1.05) {
selected.push(item);
total += itemCal;
}
if (total >= calories * 0.95) break;
}
let html = `
Ваше меню
`;
selected.forEach((i, idx) => {
html += `
${i.name} (${i.portion}г) - ${(i.cal * i.portion / 100).toFixed(0)} ккал
`;
});
html += `
Итого: ${total.toFixed(0)} ккал`;
list.innerHTML = html;
}
function replaceItem(type, index) {
const newItem = [...meals[type], ...customMeals[type]].sort(() => 0.5 - Math.random())[0];
const itemDiv = document.getElementById(`item-${index}`);
if (itemDiv) {
itemDiv.innerHTML = `
${newItem.name} (${newItem.portion}г) - ${(newItem.cal * newItem.portion / 100).toFixed(0)} ккал
`;
}
}
function showAddProductModal() {
document.getElementById('addProductModal').style.display = 'block';
}
function closeAddProductModal() {
document.getElementById('addProductModal').style.display = 'none';
}
function addNewProduct() {
const name = document.getElementById('newProductName').value.trim();
const calories = parseInt(document.getElementById('newProductCalories').value);
const portion = parseInt(document.getElementById('newProductPortion').value);
const mealType = document.getElementById('mealType').value;
if (!name || isNaN(calories) || isNaN(portion)) {
alert('Заполните все поля корректно.');
return;
}
customMeals[mealType].push({name: name, cal: calories, portion: portion});
closeAddProductModal();
alert(`Продукт "${name}" добавлен к ${mealType === 'breakfast' ? 'завтраку' : mealType === 'lunch' ? 'обеду' : mealType === 'snack' ? 'перекусу' : 'ужину'}!`);
}
// Теперь корректно вешаем события на кнопки:
document.getElementById('generateButton').addEventListener('click', generateMenu);
document.querySelector('#calorie-calculator button').addEventListener('click', calculateCalories);
});