//fetch: send a url request, client side rendering
//update the list, by default: fetch uses "get"
fetch("/get-todos", { method: "GET" }).then((response) => {
	response.json().then((data) => {
		const ol = document.querySelector("ol");
		data.forEach((item) => {
			//Create li
			const li = document.createElement("li");
			//add text to li
			li.textContent = item;

			// Create button
			const button = document.createElement("button");
			button.type = "submit";

			// Add icon to button
			const icon = document.createElement("i");
			icon.className = "fa-solid fa-delete-left";

			// Append icon to button
			button.appendChild(icon);

			// Append button to li
			li.appendChild(button);

			// Add delete functionality
			button.addEventListener("click", () => {
				// Send DELETE request
				fetch(`/delete-todo`, {
					method: "DELETE",
					headers: {
						"Content-Type": "application/json",
					},
					body: JSON.stringify({ todo: item }),
				})
					.then((response) => {
						if (response.ok) {
							// Remove the item from the DOM
							li.remove();
						} else {
							console.error("Failed to delete to-do item");
						}
					})
					.catch((error) => console.error("Error:", error));
			});

			// Append li underneath (child) ol
			ol.appendChild(li);
		});
	});
});
