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

interface Upgrade {
  id: string
  name: string
  cost: number
  milkPerSecond: number
  owned: number
  emoji: string
}

interface Cow {
  id: string
  name: string
  country: string
  emoji: string
  unlocked: boolean
  unlockCost: number
  multiplier: number
}

export default function CowClicker() {
  const [milk, setMilk] = useState(0)
  const [milkPerClick, setMilkPerClick] = useState(1)
  const [milkPerSecond, setMilkPerSecond] = useState(0)
  const [clickAnimation, setClickAnimation] = useState(false)
  const [mooText, setMooText] = useState('')
  const [currentCowIndex, setCurrentCowIndex] = useState(0)

  const [cows, setCows] = useState<Cow[]>([
    { id: 'cow1', name: 'Обычная корова', country: 'Россия', emoji: '🐄', unlocked: true, unlockCost: 0, multiplier: 1 },
    { id: 'cow2', name: 'Альпийская корова', country: 'Швейцария', emoji: '🐮', unlocked: false, unlockCost: 100, multiplier: 2 },
    { id: 'cow3', name: 'Техасская корова', country: 'США', emoji: '🐂', unlocked: false, unlockCost: 500, multiplier: 3 },
    { id: 'cow4', name: 'Священная корова', country: 'Индия', emoji: '🐃', unlocked: false, unlockCost: 2000, multiplier: 5 },
    { id: 'cow5', name: 'Космическая корова', country: 'Галактика', emoji: '👽', unlocked: false, unlockCost: 10000, multiplier: 10 },
  ])

  const [upgrades, setUpgrades] = useState<Upgrade[]>([
    { id: 'farmer', name: 'Фермер', cost: 10, milkPerSecond: 0.1, owned: 0, emoji: '👨‍🌾' },
    { id: 'barn', name: 'Сарай', cost: 100, milkPerSecond: 1, owned: 0, emoji: '🏚️' },
    { id: 'pasture', name: 'Пастбище', cost: 500, milkPerSecond: 5, owned: 0, emoji: '🌾' },
    { id: 'factory', name: 'Молокозавод', cost: 2000, milkPerSecond: 20, owned: 0, emoji: '🏭' },
    { id: 'robot', name: 'Робот-дояр', cost: 10000, milkPerSecond: 100, owned: 0, emoji: '🤖' },
  ])

  useEffect(() => {
    const interval = setInterval(() => {
      if (milkPerSecond > 0) {
        setMilk(prev => prev + milkPerSecond)
      }
    }, 1000)
    return () => clearInterval(interval)
  }, [milkPerSecond])

  const handleCowClick = () => {
    const currentCow = cows[currentCowIndex]
    const milkEarned = milkPerClick * currentCow.multiplier
    setMilk(prev => prev + milkEarned)
    setClickAnimation(true)
    
    const moos = ['Муу!', 'Мууу!', 'Му-му!', 'Мууууу!', 'МУ!']
    setMooText(moos[Math.floor(Math.random() * moos.length)])
    
    setTimeout(() => {
      setClickAnimation(false)
      setMooText('')
    }, 300)
  }

  const buyUpgrade = (upgradeId: string) => {
    const upgrade = upgrades.find(u => u.id === upgradeId)
    if (upgrade && milk >= upgrade.cost) {
      setMilk(prev => prev - upgrade.cost)
      setUpgrades(prev => prev.map(u => {
        if (u.id === upgradeId) {
          const newOwned = u.owned + 1
          const newCost = Math.floor(u.cost * 1.5)
          return { ...u, owned: newOwned, cost: newCost }
        }
        return u
      }))
      setMilkPerSecond(prev => prev + upgrade.milkPerSecond)
    }
  }

  const unlockCow = (cowId: string) => {
    const cow = cows.find(c => c.id === cowId)
    if (cow && !cow.unlocked && milk >= cow.unlockCost) {
      setMilk(prev => prev - cow.unlockCost)
      setCows(prev => prev.map(c => {
        if (c.id === cowId) {
          return { ...c, unlocked: true }
        }
        return c
      }))
    }
  }

  const selectCow = (index: number) => {
    if (cows[index].unlocked) {
      setCurrentCowIndex(index)
    }
  }

  const currentCow = cows[currentCowIndex]

  return (
    <div className="min-h-screen bg-gradient-to-b from-sky-200 to-green-200 p-4">
      <div className="max-w-6xl mx-auto">
        <h1 className="text-4xl font-bold text-center mb-8 text-green-800">
          🌍 Мировая Корова Кликер 🐄
        </h1>

        <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
          {/* Левая панель - Улучшения */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-2xl font-bold mb-4 text-gray-800">Улучшения</h2>
            <div className="space-y-3">
              {upgrades.map(upgrade => (
                <button
                  key={upgrade.id}
                  onClick={() => buyUpgrade(upgrade.id)}
                  disabled={milk < upgrade.cost}
                  className={`w-full p-3 rounded-lg transition-all ${
                    milk >= upgrade.cost
                      ? 'bg-green-500 hover:bg-green-600 text-white'
                      : 'bg-gray-200 text-gray-500 cursor-not-allowed'
                  }`}
                >
                  <div className="flex justify-between items-center">
                    <span className="text-2xl">{upgrade.emoji}</span>
                    <div className="text-left flex-1 mx-3">
                      <div className="font-semibold">{upgrade.name}</div>
                      <div className="text-sm">Цена: {upgrade.cost.toFixed(0)} 🥛</div>
                      <div className="text-xs">+{upgrade.milkPerSecond}/сек</div>
                    </div>
                    <div className="text-2xl font-bold">{upgrade.owned}</div>
                  </div>
                </button>
              ))}
            </div>
          </div>

          {/* Центральная панель - Корова */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <div className="text-center mb-4">
              <div className="text-3xl font-bold text-blue-600 mb-2">
                🥛 {Math.floor(milk)} литров молока
              </div>
              <div className="text-gray-600">
                {milkPerSecond.toFixed(1)} литров/сек
              </div>
              <div className="text-sm text-gray-500 mt-2">
                {currentCow.name} из {currentCow.country}
                {currentCow.multiplier > 1 && ` (x${currentCow.multiplier})`}
              </div>
            </div>

            <div className="relative flex justify-center items-center h-64">
              <button
                onClick={handleCowClick}
                className={`text-9xl transition-all transform hover:scale-110 active:scale-95 ${
                  clickAnimation ? 'scale-125' : ''
                }`}
              >
                {currentCow.emoji}
              </button>
              {mooText && (
                <div className="absolute top-0 text-3xl font-bold text-yellow-500 animate-bounce">
                  {mooText}
                </div>
              )}
            </div>

            <div className="mt-6 text-center text-gray-600">
              Нажми на корову для получения молока!
            </div>
          </div>

          {/* Правая панель - Коровы мира */}
          <div className="bg-white rounded-xl shadow-lg p-6">
            <h2 className="text-2xl font-bold mb-4 text-gray-800">Коровы мира</h2>
            <div className="space-y-3">
              {cows.map((cow, index) => (
                <div key={cow.id} className="relative">
                  {cow.unlocked ? (
                    <button
                      onClick={() => selectCow(index)}
                      className={`w-full p-3 rounded-lg transition-all ${
                        currentCowIndex === index
                          ? 'bg-blue-500 text-white'
                          : 'bg-green-100 hover:bg-green-200'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="text-3xl">{cow.emoji}</span>
                        <div className="text-left flex-1 mx-3">
                          <div className="font-semibold">{cow.name}</div>
                          <div className="text-sm">{cow.country}</div>
                          {cow.multiplier > 1 && (
                            <div className="text-xs">Бонус: x{cow.multiplier}</div>
                          )}
                        </div>
                        {currentCowIndex === index && (
                          <span className="text-xl">✓</span>
                        )}
                      </div>
                    </button>
                  ) : (
                    <button
                      onClick={() => unlockCow(cow.id)}
                      disabled={milk < cow.unlockCost}
                      className={`w-full p-3 rounded-lg transition-all ${
                        milk >= cow.unlockCost
                          ? 'bg-yellow-400 hover:bg-yellow-500 text-white'
                          : 'bg-gray-200 text-gray-500 cursor-not-allowed'
                      }`}
                    >
                      <div className="flex items-center justify-between">
                        <span className="text-3xl opacity-50">❓</span>
                        <div className="text-left flex-1 mx-3">
                          <div className="font-semibold">???</div>
                          <div className="text-sm">Разблокировать: {cow.unlockCost} 🥛</div>
                        </div>
                      </div>
                    </button>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* Достижения */}
        <div className="mt-8 bg-white rounded-xl shadow-lg p-6">
          <h2 className="text-2xl font-bold mb-4 text-gray-800 text-center">Достижения</h2>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-4">
            <div className={`p-4 rounded-lg text-center ${
              milk >= 10 ? 'bg-yellow-100' : 'bg-gray-100'
            }`}>
              <div className="text-3xl mb-2">🥛</div>
              <div className="font-semibold">Начинающий</div>
              <div className="text-sm text-gray-600">10 литров</div>
            </div>
            <div className={`p-4 rounded-lg text-center ${
              milk >= 1000 ? 'bg-yellow-100' : 'bg-gray-100'
            }`}>
              <div className="text-3xl mb-2">🧈</div>
              <div className="font-semibold">Маслодел</div>
              <div className="text-sm text-gray-600">1000 литров</div>
            </div>
            <div className={`p-4 rounded-lg text-center ${
              milk >= 10000 ? 'bg-yellow-100' : 'bg-gray-100'
            }`}>
              <div className="text-3xl mb-2">🧀</div>
              <div className="font-semibold">Сыровар</div>
              <div className="text-sm text-gray-600">10000 литров</div>
            </div>
            <div className={`p-4 rounded-lg text-center ${
              milk >= 100000 ? 'bg-yellow-100' : 'bg-gray-100'
            }`}>
              <div className="text-3xl mb-2">👑</div>
              <div className="font-semibold">Молочный король</div>
              <div className="text-sm text-gray-600">100000 литров</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}