const form = document.getElementById("carForm")
const carsDiv = document.getElementById("cars")

async function loadCars() {
  const response = await fetch("/cars")
  const cars = await response.json()

  carsDiv.innerHTML = ""

  cars.forEach(car => {
    carsDiv.innerHTML += `
      <div class="car-card">
        <h2>${car.year} ${car.make} ${car.model}</h2>
        <p>$${car.price}</p>
      </div>
    `
  })
}

form.addEventListener("submit", async (e) => {
  e.preventDefault()

  const car = {
    make: document.getElementById("make").value,
    model: document.getElementById("model").value,
    year: document.getElementById("year").value,
    price: document.getElementById("price").value
  }

  await fetch("/add-car", {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify(car)
  })

  loadCars()
})

loadCars()