const KEY = "vpet_state";
const petEl = document.getElementById("petEmoji");
const moodEl = document.getElementById("mood");

let state = JSON.parse(localStorage.getItem(KEY) || '{"hunger":80,"happiness":80,"energy":80}');

function clamp(v) { return Math.max(0, Math.min(100, v)); }

function update() {
  document.getElementById("hunger").value = state.hunger;
  document.getElementById("happiness").value = state.happiness;
  document.getElementById("energy").value = state.energy;
  const avg = (state.hunger + state.happiness + state.energy) / 3;
  moodEl.textContent = avg > 70 ? "Happy 😊" : avg > 40 ? "Okay 😐" : "Sad 😢";
  petEl.textContent = avg > 70 ? "🐶" : avg > 40 ? "🐕" : "😿";
  localStorage.setItem(KEY, JSON.stringify(state));
}

document.querySelectorAll("[data-act]").forEach(btn =>
  btn.addEventListener("click", () => {
    const act = btn.dataset.act;
    if (act === "feed") { state.hunger = clamp(state.hunger + 20); state.energy = clamp(state.energy + 5); }
    else if (act === "play") { state.happiness = clamp(state.happiness + 20); state.hunger = clamp(state.hunger - 10); state.energy = clamp(state.energy - 15); }
    else if (act === "sleep") { state.energy = clamp(state.energy + 30); state.hunger = clamp(state.hunger - 10); }
    petEl.classList.add("bounce");
    setTimeout(() => petEl.classList.remove("bounce"), 300);
    update();
  })
);

setInterval(() => {
  state.hunger = clamp(state.hunger - 2);
  state.happiness = clamp(state.happiness - 2);
  state.energy = clamp(state.energy - 1);
  update();
}, 5000);

update();