<!DOCTYPE html>
<html lang="fr">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Ingrédients</title>
    <style>
       /* Reset */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    font-family: 'Poppins', sans-serif;
    background-color: #f5f7fa;
    color: #333;
    padding: 20px;
    text-align: center;
}

h1 {
    font-size: 2.5rem;
    color: #2c3e50;
    margin-bottom: 20px;
}

.category {
    margin: 15px 0;
    padding: 15px;
    background: #ffffff;
    border-radius: 8px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
    transition: transform 0.2s ease, box-shadow 0.2s ease;
}

.category:hover {
    transform: scale(1.03);
    box-shadow: 0 6px 15px rgba(0, 0, 0, 0.2);
}

.category h3 {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 1.2rem;
    color: #34495e;
    cursor: pointer;
}

.category h3 span {
    font-size: 1rem;
    color: #7f8c8d;
}

.ingredients-list {
    max-height: 0;
    overflow: hidden;
    transition: max-height 0.3s ease-out;
    padding-left: 20px;
}

.ingredients-list.open {
    max-height: 500px;
}

.ingredient-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background: #f9f9f9;
    border-radius: 5px;
    padding: 10px;
    margin: 8px 0;
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.ingredient-item span {
    color: #2c3e50;
    flex-grow: 1;
    margin-left: 10px;
}

.ingredient-item button {
    background: #e74c3c;
    color: #ffffff;
    border: none;
    padding: 8px 12px;
    border-radius: 5px;
    cursor: pointer;
    transition: background 0.3s ease;
}

.ingredient-item button:hover {
    background: #c0392b;
}

#addIngredientButton {
    position: fixed;
    bottom: 20px;
    right: 20px;
    background: #3498db;
    color: #ffffff;
    border: none;
    border-radius: 50%;
    width: 60px;
    height: 60px;
    font-size: 1.5rem;
    cursor: pointer;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
    transition: background 0.3s ease, transform 0.2s ease;
}

#addIngredientButton:hover {
    background: #2980b9;
    transform: scale(1.1);
}

#addIngredientModal {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: #ffffff;
    border-radius: 10px;
    width: 90%;
    max-width: 400px;
    padding: 20px;
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
    z-index: 1000;
}

#addIngredientModal h3 {
    font-size: 1.5rem;
    margin-bottom: 20px;
    color: #2c3e50;
}

#addIngredientModal input,
#addIngredientModal select {
    width: 100%;
    margin: 10px 0;
    padding: 10px;
    font-size: 1rem;
    border: 1px solid #ddd;
    border-radius: 5px;
}

#addIngredientModal button {
    width: 100%;
    padding: 10px;
    font-size: 1rem;
    border: none;
    border-radius: 5px;
    color: #ffffff;
    cursor: pointer;
}

#submitIngredientButton {
    background: #27ae60;
    margin: 10px 0;
}

#submitIngredientButton:hover {
    background: #229954;
}

#closeModalButton {
    background: #e74c3c;
    margin: 10px 0;
}

#closeModalButton:hover {
    background: #c0392b;
}

/* Overlay for the modal */
#modalOverlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 999;
}

/* Responsiveness */
@media (max-width: 768px) {
    h1 {
        font-size: 2rem;
    }

    .category {
        padding: 10px;
    }

    .category h3 {
        font-size: 1rem;
    }

    .ingredient-item {
        flex-direction: column;
        align-items: flex-start;
    }

    .ingredient-item span {
        margin-left: 0;
        margin-bottom: 8px;
        text-align: left;
    }

    #addIngredientButton {
        width: 50px;
        height: 50px;
        font-size: 1.25rem;
    }

    #addIngredientModal {
        width: 95%;
    }
}

@media (max-width: 480px) {
    h1 {
        font-size: 1.8rem;
    }

    .category h3 {
        font-size: 0.9rem;
    }

    .ingredient-item {
        padding: 8px;
    }

    #addIngredientButton {
        width: 45px;
        height: 45px;
        font-size: 1rem;
    }
}
.category-badge {
    display: none; /* Masqué par défaut */
    background-color: #3498db;
    color: white;
    font-size: 0.8rem;
    padding: 2px 6px;
    border-radius: 12px;
    margin-left: 10px;
    font-weight: bold;
}
.category.has-items .category-badge {
    display: inline-block; /* Affiché uniquement si des éléments existent */
}

.category-badge {
    transition: opacity 0.3s ease;
}

    </style>
</head>

<body>
    <h1>Ingrédients de la Liste</h1>

    <div id="categoriesContainer"></div>

    <button id="addIngredientButton">+</button>

    <!-- Modal for adding ingredient -->
    <div id="modalOverlay"></div>
    <div id="addIngredientModal">
        <h3>Ajouter un Ingrédient</h3>
        <input type="text" id="ingredientName" placeholder="Nom de l'Ingrédient" />
        <input type="number" id="ingredientQuantity" placeholder="Quantité" />
        <input type="text" id="ingredientUnit" placeholder="Unité" />
        <select id="ingredientCategory">
            <option value="Viandes et Poissons">Viandes et Poissons</option>
            <option value="Fruits et Légumes">Fruits et Légumes</option>
            <option value="Épicerie">Épicerie</option>
            <option value="Produits Frais">Produits Frais</option>
            <option value="Surgelés">Surgelés</option>
            <option value="Hygiène et Beauté">Hygiène et Beauté</option>
            <option value="Boulangerie et Pâtisserie">Boulangerie et Pâtisserie</option>
            <option value="Boissons">Boissons</option>
            <option value="Autres">Autres</option>
        </select>
        <button id="submitIngredientButton">Ajouter</button>
        <button id="closeModalButton">Fermer</button>
    </div>
</body>

    <script type="module">
       import { initializeApp } from "https://www.gstatic.com/firebasejs/11.1.0/firebase-app.js";
import { getFirestore, doc, getDoc, updateDoc } from "https://www.gstatic.com/firebasejs/11.1.0/firebase-firestore.js";

const firebaseConfig = {
    apiKey: "AIzaSyAnoTZXPZGF1e6OABQNaiTm2azaEwr4nwA",
    authDomain: "courses-35750.firebaseapp.com",
    projectId: "courses-35750",
    storageBucket: "courses-35750.appspot.com",
    messagingSenderId: "579827180001",
    appId: "1:579827180001:web:929b09f8ff002a96b632a0"
};

const app = initializeApp(firebaseConfig);
const db = getFirestore(app);

const urlParams = new URLSearchParams(window.location.search);
const listId = urlParams.get("listId");

const categoriesContainer = document.getElementById('categoriesContainer');
const addIngredientButton = document.getElementById('addIngredientButton');
const addIngredientModal = document.getElementById('addIngredientModal');
const submitIngredientButton = document.getElementById('submitIngredientButton');
const ingredientName = document.getElementById('ingredientName');
const ingredientQuantity = document.getElementById('ingredientQuantity');
const ingredientUnit = document.getElementById('ingredientUnit');
const ingredientCategory = document.getElementById('ingredientCategory');

const modalOverlay = document.getElementById('modalOverlay');
const closeModalButton = document.getElementById('closeModalButton');

addIngredientButton.addEventListener('click', () => {
    addIngredientModal.style.display = 'block';
    modalOverlay.style.display = 'block';
});

closeModalButton.addEventListener('click', () => {
    addIngredientModal.style.display = 'none';
    modalOverlay.style.display = 'none';
});

modalOverlay.addEventListener('click', () => {
    addIngredientModal.style.display = 'none';
    modalOverlay.style.display = 'none';
});

const loadCategories = async () => {
    const listRef = doc(db, "shoppingLists", listId);
    const listDoc = await getDoc(listRef);
    const listData = listDoc.data();

    categoriesContainer.innerHTML = '';

    const categories = [
        "Viandes et Poissons",
        "Fruits et Légumes",
        "Épicerie",
        "Produits Frais",
        "Surgelés",
        "Hygiène et Beauté",
        "Boulangerie et Pâtisserie",
        "Boissons",
        "Autres"
    ];

    categories.forEach(category => {
        const categoryDiv = document.createElement('div');
        categoryDiv.classList.add('category');

        // Vérifie si la catégorie contient des ingrédients
        const hasItems = listData.ingredients.some(ingredient => ingredient.category === category);

        // Ajoute une classe si la catégorie a des éléments
        if (hasItems) {
            categoryDiv.classList.add('has-items');
        }

        const categoryHeader = document.createElement('h3');
        categoryHeader.innerHTML = `
            ${category} 
            <span class="category-badge">${hasItems ? '●' : ''}</span>
            <span class="toggle-arrow">▼</span>
        `;
        categoryDiv.appendChild(categoryHeader);

        const ingredientsList = document.createElement('div');
        ingredientsList.classList.add('ingredients-list');

        listData.ingredients.forEach(ingredient => {
            if (ingredient.category === category) {
                const ingredientItem = document.createElement('div');
                ingredientItem.classList.add('ingredient-item');
                const quantityUnit = ingredient.quantity
                    ? `${ingredient.quantity}${ingredient.unit || ''}`
                    : '';
                ingredientItem.innerHTML = `
                    <input type="checkbox" ${ingredient.valid ? 'checked' : ''} onchange="toggleValid('${ingredient.id}')">
                    <span>${ingredient.name} ${quantityUnit}</span>
                    <button onclick="deleteIngredient('${ingredient.id}')">Supprimer</button>
                `;
                ingredientsList.appendChild(ingredientItem);
            }
        });

        categoryDiv.appendChild(ingredientsList);
        categoriesContainer.appendChild(categoryDiv);

        categoryHeader.addEventListener('click', () => {
            ingredientsList.classList.toggle('open');
        });
    });
};

window.toggleValid = async (ingredientId) => {
    const listRef = doc(db, "shoppingLists", listId);
    const listDoc = await getDoc(listRef);
    const listData = listDoc.data();

    const updatedIngredients = listData.ingredients.map(ingredient => {
        if (ingredient.id === ingredientId) {
            ingredient.valid = !ingredient.valid;
        }
        return ingredient;
    });

    await updateDoc(listRef, { ingredients: updatedIngredients });
    loadCategories();
};

window.deleteIngredient = async (ingredientId) => {
    const listRef = doc(db, "shoppingLists", listId);
    const listDoc = await getDoc(listRef);
    const listData = listDoc.data();

    const updatedIngredients = listData.ingredients.filter(ingredient => ingredient.id !== ingredientId);
    await updateDoc(listRef, { ingredients: updatedIngredients });
    loadCategories();
};

submitIngredientButton.addEventListener("click", async () => {
    const newIngredient = {
        name: ingredientName.value,
        quantity: ingredientQuantity.value,
        unit: ingredientUnit.value,
        category: ingredientCategory.value,
        valid: false,
        id: Date.now().toString()
    };

    const listRef = doc(db, "shoppingLists", listId);
    const listDoc = await getDoc(listRef);
    const listData = listDoc.data();

    listData.ingredients.push(newIngredient);
    await updateDoc(listRef, { ingredients: listData.ingredients });

    ingredientName.value = '';
    ingredientQuantity.value = '';
    ingredientUnit.value = '';
    loadCategories();
    addIngredientModal.style.display = 'none';
});

addIngredientButton.addEventListener("click", () => {
    addIngredientModal.style.display = 'block';
});

// Charger les catégories et les ingrédients au chargement de la page
loadCategories();


    </script>
</body>

</html>
