document.addEventListener("DOMContentLoaded", () => {
    loadItems();
    loadHealth();

    document.getElementById("add-form").addEventListener("submit", async (e) => {
        e.preventDefault();
        const name = document.getElementById("item-name").value.trim();
        const desc = document.getElementById("item-desc").value.trim();
        if (!name) return;

        await fetch("/api/items", {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify({ name, description: desc }),
        });

        document.getElementById("item-name").value = "";
        document.getElementById("item-desc").value = "";
        loadItems();
    });
});

async function loadItems() {
    const el = document.getElementById("items-list");
    try {
        const res = await fetch("/api/items");
        const data = await res.json();
        if (!data.items || data.items.length === 0) {
            el.innerHTML = "<p style='color:var(--muted)'>No items yet.</p>";
            return;
        }
        el.innerHTML = data.items
            .map(
                (item) => `
            <div class="item-row">
                <div class="item-info">
                    <strong>${escapeHtml(item.name)}</strong>
                    <span>${escapeHtml(item.description)}</span>
                </div>
                <button class="delete-btn" onclick="deleteItem(${item.id})">Delete</button>
            </div>`
            )
            .join("");
    } catch {
        el.innerHTML = "<p style='color:var(--danger)'>Failed to load items.</p>";
    }
}

async function deleteItem(id) {
    await fetch(`/api/items/${id}`, { method: "DELETE" });
    loadItems();
}

async function loadHealth() {
    const el = document.getElementById("health");
    try {
        const res = await fetch("/api/health");
        const data = await res.json();
        el.textContent = JSON.stringify(data, null, 2);
    } catch {
        el.textContent = "Health check failed";
    }
}

function escapeHtml(text) {
    const div = document.createElement("div");
    div.appendChild(document.createTextNode(text));
    return div.innerHTML;
}
