import React, { useState, useEffect } from 'react';

const petList = [
  {
    id: 'cat01',
    name: '喵喵',
    image: '/pets/cat.png',
    mood: '开心',
    hunger: 50,
  },
  {
    id: 'dog01',
    name: '汪汪',
    image: '/pets/dog.png',
    mood: '饥饿',
    hunger: 70,
  }
];

const PetGame = () => {
  const [selectedPetIndex, setSelectedPetIndex] = useState(0);
  const [petStates, setPetStates] = useState(petList);

  // 定时每 5 秒减少一点饥饿值
  useEffect(() => {
    const timer = setInterval(() => {
      setPetStates(prev =>
        prev.map((pet, index) =>
          index === selectedPetIndex
            ? {
                ...pet,
                hunger: Math.min(100, pet.hunger + 2),
                mood: pet.hunger > 80 ? '生气' : pet.mood
              }
            : pet
        )
      );
    }, 5000);
    return () => clearInterval(timer);
  }, [selectedPetIndex]);

  const handleFeed = () => {
    setPetStates(prev =>
      prev.map((pet, index) =>
        index === selectedPetIndex
          ? {
              ...pet,
              hunger: Math.max(0, pet.hunger - 20),
              mood: '开心'
            }
          : pet
      )
    );
  };

  const handlePet = () => {
    setPetStates(prev =>
      prev.map((pet, index) =>
        index === selectedPetIndex
          ? { ...pet, mood: '超级开心' }
          : pet
      )
    );
  };

  const currentPet = petStates[selectedPetIndex];

  return (
    <div style={{ textAlign: 'center', padding: 20 }}>
      <h2>当前宠物：{currentPet.name}</h2>
      <img
        src={currentPet.image}
        alt={currentPet.name}
        style={{ width: 200, height: 200, cursor: 'pointer' }}
        onClick={handlePet}
      />
      <p>情绪：{currentPet.mood}</p>
      <p>饥饿值：{currentPet.hunger}/100</p>

      <button onClick={handleFeed}>🍖 喂食</button>

      <div style={{ marginTop: 20 }}>
        <h4>切换宠物：</h4>
        {petStates.map((pet, index) => (
          <button key={pet.id} onClick={() => setSelectedPetIndex(index)} style={{ marginRight: 8 }}>
            {pet.name}
          </button>
        ))}
      </div>
    </div>
  );
};

export default PetGame;
