const addIngredientBtn = document.getElementById('add-ingredient-btn');
const overlay = document.getElementById('overlay');
const ingModal = document.getElementById('ingredient-modal');

addIngredientBtn.addEventListener('click', () => {
    ingModal.classList.remove('hidden');
    overlay.classList.remove('hidden');
});


document.addEventListener('click', (e) => {
    if (!ingModal.contains(e.target) && !addIngredientBtn.contains(e.target)) {
        ingModal.classList.add('hidden');
        overlay.classList.add('hidden');
    }
});

const ingredientSubmitBtn = document.getElementById('new-ingredient-submit');
const ingredientName = document.getElementById('ing-name-input');
const ingredientUnit = document.getElementById('ing-unit-input');

ingredientSubmitBtn.addEventListener('click', async (e) => {

    const name = ingredientName.value.trim();
    const unit = ingredientUnit.value.trim();

    if (!name || !unit) {
        showToastify('Please fill in all fields.', 'error');
        return;
    }

    const formData = new FormData();
    formData.append('action', 'create_ingredient');
    formData.append('name', name);
    formData.append('unit', unit);

    const response = await fetch('/ajax', {
        method: 'POST',
        body: formData
    });

    const json = await response.json();

    if (!response.ok) {
        const message = json.error;
        showToastify(message, 'error');
        return;
    }

    showToastify(json.success, 'success');
    ingredientName.value = '';
    ingredientUnit.value = '';
    ingModal.classList.add('hidden');
    overlay.classList.add('hidden');
});