const form = document.getElementById("searchForm");
const input = document.getElementById("pokeInput");
const status = document.getElementById("status");
const card = document.getElementById("card");

async function fetchPokemon(name) {
  status.textContent = "Loading...";
  card.classList.add("hidden");
  try {
    const res = await fetch(`https://pokeapi.co/api/v2/pokemon/${name.toLowerCase()}`);
    if (!res.ok) throw new Error("Pokémon not found");
    const data = await res.json();
    render(data);
    status.textContent = "";
  } catch (err) {
    status.textContent = err.message;
  }
}

function render(p) {
  document.getElementById("pokeImg").src = p.sprites.other["official-artwork"].front_default || p.sprites.front_default;
  document.getElementById("pokeName").textContent = p.name;
  document.getElementById("pokeId").textContent = `#${String(p.id).padStart(3,"0")}`;
  document.getElementById("types").innerHTML = p.types.map(t => `<span class="type">${t.type.name}</span>`).join("");
  document.getElementById("stats").innerHTML = p.stats.map(s =>
    `<div class="stat"><strong>${s.stat.name}:</strong> ${s.base_stat}</div>`).join("");
  card.classList.remove("hidden");
}

form.addEventListener("submit", (e) => {
  e.preventDefault();
  const q = input.value.trim();
  if (q) fetchPokemon(q);
});

fetchPokemon("pikachu");