const MAX_POKEMON = 151; const CACHE_DURATION = 24 * 60 * 60 * 1000; // 24 hours in milliseconds const listWrapper = document.querySelector(".list-wrapper"); const searchInput = document.querySelector("#search-input"); const numberFilter = document.querySelector("#number"); const nameFilter = document.querySelector("#name"); const notFoundMessage = document.querySelector("#not-found-message"); let allPokemons = []; document.addEventListener("DOMContentLoaded", () => { const cachedData = localStorage.getItem("pokemons"); const cacheTimestamp = localStorage.getItem("pokemons_timestamp"); if (cachedData && cacheTimestamp && (Date.now() - cacheTimestamp) < CACHE_DURATION) { allPokemons = JSON.parse(cachedData); console.log("Loaded Pokémon data from cache:", allPokemons); displayPokemons(allPokemons); } else { fetchPokemons(); } }); function fetchPokemons() { console.log("Fetching Pokémon data from server..."); fetch(`./get-pokemon.php`) .then((response) => response.json()) .then((data) => { if (Array.isArray(data)) { allPokemons = data; localStorage.setItem("pokemons", JSON.stringify(allPokemons)); localStorage.setItem("pokemons_timestamp", Date.now().toString()); console.log("Fetched and cached Pokémon data:", allPokemons); displayPokemons(allPokemons); } else { console.error("Unexpected response format:", data); } }) .catch((error) => { console.error("Error fetching Pokémon data:", error); }); } async function fetchPokemonDataBeforeRedirect(id) { try { console.log(`Fetching data for Pokémon ID ${id} before redirect...`); const response = await fetch(`./get-pokemon.php?id=${id}`); const text = await response.text(); console.log(`Response for Pokémon ID ${id}:`, text); if (!text) { throw new Error("Empty response from server"); } const pokemon = JSON.parse(text); if (pokemon.error) { throw new Error(pokemon.error); } return true; } catch (error) { console.error(`Failed to fetch Pokémon data before redirect for ID ${id}:`, error); return false; } } function displayPokemons(pokemons) { console.log("Displaying Pokémon data:", pokemons); listWrapper.innerHTML = ""; pokemons.forEach((pokemon) => { const listItem = document.createElement("div"); listItem.className = "list-item"; listItem.innerHTML = `
#${pokemon.id}
#${pokemon.name}