document.addEventListener("DOMContentLoaded", () => {
    const addForm = document.getElementById("addForm");
    const shoppingTableBody = document.querySelector("#shoppingTable tbody");

    // Liste laden und Tabelle rendern
    const loadList = async () => {
        const response = await fetch("data/list.json");
        const items = await response.json();
        renderTable(items);
    };

    // Tabelle rendern
    const renderTable = (items) => {
        shoppingTableBody.innerHTML = ""; // Leere die Tabelle
        items.forEach((item, index) => {
            const row = document.createElement("tr");
            row.draggable = true; // Drag-and-Drop aktivieren
            row.innerHTML = `
                <td>
                    <div class="drag-handle" data-index="${index}">⇅</div>
                </td>
                <td>${item.name}</td>
                <td>${item.price.toFixed(2)} €</td>
                <td>${item.amount}</td>
                <td>${item.unit}</td>
                <td><button data-index="${index}" class="delete-btn">Löschen</button></td>
            `;
            shoppingTableBody.appendChild(row);

            // Drag-and-Drop Events
            row.addEventListener("dragstart", (e) => e.target.classList.add("dragging"));
            row.addEventListener("dragend", (e) => e.target.classList.remove("dragging"));
        });
    };

    // Artikel löschen
    shoppingTableBody.addEventListener("click", async (e) => {
        if (e.target.classList.contains("delete-btn")) {
            const index = e.target.getAttribute("data-index");
            const response = await fetch("php/delete_item.php", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ index })
            });
            const updatedList = await response.json();
            renderTable(updatedList);
        }
    });

    // Drag-and-Drop (Desktop)
    shoppingTableBody.addEventListener("dragover", (e) => {
        e.preventDefault();
        const afterElement = getDragAfterElement(shoppingTableBody, e.clientY);
        const dragging = document.querySelector(".dragging");
        if (afterElement == null) {
            shoppingTableBody.appendChild(dragging);
        } else {
            shoppingTableBody.insertBefore(dragging, afterElement);
        }
    });

    // Funktion zum Finden der Position (Desktop & Touch)
    const getDragAfterElement = (container, y) => {
        const draggableElements = [...container.querySelectorAll("tr:not(.dragging)")];
        return draggableElements.reduce(
            (closest, child) => {
                const box = child.getBoundingClientRect();
                const offset = y - box.top - box.height / 2;
                if (offset < 0 && offset > closest.offset) {
                    return { offset, element: child };
                } else {
                    return closest;
                }
            },
            { offset: Number.NEGATIVE_INFINITY }
        ).element;
    };

    // Artikel hinzufügen
    addForm.addEventListener("submit", async (e) => {
        e.preventDefault();
        const itemName = document.getElementById("itemName").value.trim();
        const itemPrice = parseFloat(document.getElementById("itemPrice").value) || 0; // Standardpreis auf 0
        const itemAmount = parseInt(document.getElementById("itemAmount").value) || 1; // Standardmenge auf 1
        const itemUnit = document.getElementById("itemUnit").value;

        if (!itemName) {
            alert("Bitte geben Sie einen Artikelnamen ein.");
            return;
        }

        const newItem = {
            name: itemName,
            price: itemPrice,
            amount: itemAmount,
            unit: itemUnit
        };

        const response = await fetch("php/add_item.php", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(newItem)
        });
        const updatedList = await response.json();
        renderTable(updatedList);
        addForm.reset();
    });

    // Liste beim Laden initialisieren
    loadList();
});
